blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d42a40d8385c00810fa042d93afde22e6e2f7c48 | [
"super(ConfigSystemWriter, self).__init__(cmd_tlm_data, deployment_name, cosmos_directory, old_definition)\nself.token = 'DECLARE_TARGET'\nself.argument = ''\nself.destination = cosmos_directory + '/config/system/'\nself.fl_loc = self.destination + 'system.txt'",
"ignored_lines = []\nignored_lines.append(self.tok... | <|body_start_0|>
super(ConfigSystemWriter, self).__init__(cmd_tlm_data, deployment_name, cosmos_directory, old_definition)
self.token = 'DECLARE_TARGET'
self.argument = ''
self.destination = cosmos_directory + '/config/system/'
self.fl_loc = self.destination + 'system.txt'
<|end_... | This class generates the system config file in cosmos_directory/config/system/ | ConfigSystemWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigSystemWriter:
"""This class generates the system config file in cosmos_directory/config/system/"""
def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory, old_definition=None):
"""@param cmd_tlm_data: Tuple containing lists channels [0], commands [1], and events [2]... | stack_v2_sparse_classes_36k_train_026400 | 4,127 | permissive | [
{
"docstring": "@param cmd_tlm_data: Tuple containing lists channels [0], commands [1], and events [2] @param deployment_name: name of the COSMOS target @param cosmos_directory: Directory of COSMOS @param old_definition: COSMOS target name that you want to remove",
"name": "__init__",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_007504 | Implement the Python class `ConfigSystemWriter` described below.
Class description:
This class generates the system config file in cosmos_directory/config/system/
Method signatures and docstrings:
- def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory, old_definition=None): @param cmd_tlm_data: Tuple co... | Implement the Python class `ConfigSystemWriter` described below.
Class description:
This class generates the system config file in cosmos_directory/config/system/
Method signatures and docstrings:
- def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory, old_definition=None): @param cmd_tlm_data: Tuple co... | d19cade2140231b4e0879b2f6ab4a62b25792dea | <|skeleton|>
class ConfigSystemWriter:
"""This class generates the system config file in cosmos_directory/config/system/"""
def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory, old_definition=None):
"""@param cmd_tlm_data: Tuple containing lists channels [0], commands [1], and events [2]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigSystemWriter:
"""This class generates the system config file in cosmos_directory/config/system/"""
def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory, old_definition=None):
"""@param cmd_tlm_data: Tuple containing lists channels [0], commands [1], and events [2] @param deplo... | the_stack_v2_python_sparse | Autocoders/Python/src/fprime_ac/utils/cosmos/writers/ConfigSystemWriter.py | nodcah/fprime | train | 0 |
f8ad6c24c48aae7aebae08dad359a7d659ac3098 | [
"def createSegmentNode(nums, l, r):\n if l > r:\n return None\n if l == r:\n return SegmentNode(l, r, nums[l])\n m = l + (r - l) // 2\n left = createSegmentNode(nums, l, m)\n right = createSegmentNode(nums, m + 1, r)\n ret = SegmentNode(l, r, left.val + right.val)\n ret.left, ret.... | <|body_start_0|>
def createSegmentNode(nums, l, r):
if l > r:
return None
if l == r:
return SegmentNode(l, r, nums[l])
m = l + (r - l) // 2
left = createSegmentNode(nums, l, m)
right = createSegmentNode(nums, m + 1, r)
... | NumArray2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray2:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2... | stack_v2_sparse_classes_36k_train_026401 | 4,469 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray2` described below.
Class description:
Implement the NumArray2 class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtyp... | Implement the Python class `NumArray2` described below.
Class description:
Implement the NumArray2 class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtyp... | 9190d3d178f1733aa226973757ee7e045b7bab00 | <|skeleton|>
class NumArray2:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray2:
def __init__(self, nums):
""":type nums: List[int]"""
def createSegmentNode(nums, l, r):
if l > r:
return None
if l == r:
return SegmentNode(l, r, nums[l])
m = l + (r - l) // 2
left = createSegmentNode(n... | the_stack_v2_python_sparse | RangeSumQuery-Mutable.py | ellinx/LC-python | train | 1 | |
c8d644bc0ff209c8f31ce22d37c9588f6c40fc47 | [
"if not root:\n return 0\nif not root.left:\n return self.minDepth(root.right) + 1\nif not root.right:\n return self.minDepth(root.left) + 1\nleft = self.minDepth(root.left)\nright = self.minDepth(root.right)\nreturn min(left, right) + 1",
"if not root:\n return 0\nqueue = [root]\nmin_result = 0\nwhil... | <|body_start_0|>
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
left = self.minDepth(root.left)
right = self.minDepth(root.right)
return min(left, righ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS 递归解法 Args: root: Returns:"""
<|body_0|>
def minDepth(self, root: TreeNode) -> int:
"""BFS 解法 Args: root: Returns:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
re... | stack_v2_sparse_classes_36k_train_026402 | 1,801 | no_license | [
{
"docstring": "DFS 递归解法 Args: root: Returns:",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "BFS 解法 Args: root: Returns:",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: DFS 递归解法 Args: root: Returns:
- def minDepth(self, root: TreeNode) -> int: BFS 解法 Args: root: Returns: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: DFS 递归解法 Args: root: Returns:
- def minDepth(self, root: TreeNode) -> int: BFS 解法 Args: root: Returns:
<|skeleton|>
class Solution:
... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS 递归解法 Args: root: Returns:"""
<|body_0|>
def minDepth(self, root: TreeNode) -> int:
"""BFS 解法 Args: root: Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS 递归解法 Args: root: Returns:"""
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
left = self.m... | the_stack_v2_python_sparse | leetcode/111_二叉树的最小深度.py | tenqaz/crazy_arithmetic | train | 0 | |
5f0bfdd669500b8c4613a3d41eca607186bad0f0 | [
"c = Counter(A)\nfor x in sorted(A, key=abs):\n if c[x] > c[2 * x]:\n return False\n c[2 * x] -= c[x]\nreturn True",
"A.sort(key=lambda x: (x < 0, abs(x)))\nj, dummy = (1, 100000)\nn = len(A)\nfor i in xrange(n):\n if A[i] == dummy:\n continue\n if j <= i:\n j = i + 1\n while j... | <|body_start_0|>
c = Counter(A)
for x in sorted(A, key=abs):
if c[x] > c[2 * x]:
return False
c[2 * x] -= c[x]
return True
<|end_body_0|>
<|body_start_1|>
A.sort(key=lambda x: (x < 0, abs(x)))
j, dummy = (1, 100000)
n = len(A)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canReorderDoubled1(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def canReorderDoubled2(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def canReorderDoubled3(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_026403 | 1,891 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "canReorderDoubled1",
"signature": "def canReorderDoubled1(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "canReorderDoubled2",
"signature": "def canReorderDoubled2(self, A)"
},
{
"docstring": ":typ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled1(self, A): :type A: List[int] :rtype: bool
- def canReorderDoubled2(self, A): :type A: List[int] :rtype: bool
- def canReorderDoubled3(self, A): :type A: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled1(self, A): :type A: List[int] :rtype: bool
- def canReorderDoubled2(self, A): :type A: List[int] :rtype: bool
- def canReorderDoubled3(self, A): :type A: Li... | 3a7f20f79281fcaedb10696723dcb39c816ce258 | <|skeleton|>
class Solution:
def canReorderDoubled1(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def canReorderDoubled2(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def canReorderDoubled3(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canReorderDoubled1(self, A):
""":type A: List[int] :rtype: bool"""
c = Counter(A)
for x in sorted(A, key=abs):
if c[x] > c[2 * x]:
return False
c[2 * x] -= c[x]
return True
def canReorderDoubled2(self, A):
""":t... | the_stack_v2_python_sparse | 954_array_of_doubled_pairs.py | haohanz/Leetcode-Solution | train | 1 | |
c19dc4d06e3352320daef1e6684eee0b79e32c59 | [
"self._name = name or 'forward_rate_agreement'\nif rate_term is None and maturity_date is None:\n raise ValueError('Error creating FRA. Either rate_term or maturity_date is required.')\nwith tf.name_scope(self._name):\n self._dtype = dtype\n self._notional = tf.convert_to_tensor(notional, dtype=self._dtype... | <|body_start_0|>
self._name = name or 'forward_rate_agreement'
if rate_term is None and maturity_date is None:
raise ValueError('Error creating FRA. Either rate_term or maturity_date is required.')
with tf.name_scope(self._name):
self._dtype = dtype
self._noti... | Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based on the spot Libor rate for term `tau`. The cashflows are exchanged at the settlement tim... | ForwardRateAgreement | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardRateAgreement:
"""Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based on the spot Libor rate for term `tau`. T... | stack_v2_sparse_classes_36k_train_026404 | 7,988 | permissive | [
{
"docstring": "Initialize the batch of FRA contracts. Args: settlement_date: A rank 1 `DateTensor` specifying the dates on which cashflows are settled. The shape of the input correspond to the number of instruments being created. fixing_date: A rank 1 `DateTensor` specifying the dates on which forward rate wil... | 2 | stack_v2_sparse_classes_30k_train_021235 | Implement the Python class `ForwardRateAgreement` described below.
Class description:
Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based o... | Implement the Python class `ForwardRateAgreement` described below.
Class description:
Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based o... | 0d3a2193c0f2d320b65e602cf01d7a617da484df | <|skeleton|>
class ForwardRateAgreement:
"""Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based on the spot Libor rate for term `tau`. T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForwardRateAgreement:
"""Represents a batch of Forward Rate Agreements (FRA). An FRA is a contract for the period [T, T+tau] where the holder exchanges a fixed rate (agreed at the start of the contract) against a floating payment determined at time T based on the spot Libor rate for term `tau`. The cashflows ... | the_stack_v2_python_sparse | tf_quant_finance/experimental/instruments/forward_rate_agreement.py | google/tf-quant-finance | train | 4,165 |
fcb6dab7f8b77083a166d75c28c46c515c9f73ce | [
"summary_re = re.compile('^.+$')\nif len(summary) > 512:\n raise ValidationError('Summary should be less than 512 chars.')\nif not summary_re.match(summary):\n raise ValidationError('Summary should contain one line only.')\nreturn summary",
"if not requires_dist:\n return ''\nif not isinstance(requires_d... | <|body_start_0|>
summary_re = re.compile('^.+$')
if len(summary) > 512:
raise ValidationError('Summary should be less than 512 chars.')
if not summary_re.match(summary):
raise ValidationError('Summary should contain one line only.')
return summary
<|end_body_0|>
... | PackageCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageCreate:
def validate_summary(cls, summary: str) -> str:
"""Check if summary is a valid one line string."""
<|body_0|>
def validate_requires_dist(cls, requires_dist: Union[str, List[str]]) -> str:
"""Translate a list of requires to a string using ## as a separa... | stack_v2_sparse_classes_36k_train_026405 | 3,537 | no_license | [
{
"docstring": "Check if summary is a valid one line string.",
"name": "validate_summary",
"signature": "def validate_summary(cls, summary: str) -> str"
},
{
"docstring": "Translate a list of requires to a string using ## as a separator.",
"name": "validate_requires_dist",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_013595 | Implement the Python class `PackageCreate` described below.
Class description:
Implement the PackageCreate class.
Method signatures and docstrings:
- def validate_summary(cls, summary: str) -> str: Check if summary is a valid one line string.
- def validate_requires_dist(cls, requires_dist: Union[str, List[str]]) -> ... | Implement the Python class `PackageCreate` described below.
Class description:
Implement the PackageCreate class.
Method signatures and docstrings:
- def validate_summary(cls, summary: str) -> str: Check if summary is a valid one line string.
- def validate_requires_dist(cls, requires_dist: Union[str, List[str]]) -> ... | 26759c37375d04ab202a490ca5d1063faab042e6 | <|skeleton|>
class PackageCreate:
def validate_summary(cls, summary: str) -> str:
"""Check if summary is a valid one line string."""
<|body_0|>
def validate_requires_dist(cls, requires_dist: Union[str, List[str]]) -> str:
"""Translate a list of requires to a string using ## as a separa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackageCreate:
def validate_summary(cls, summary: str) -> str:
"""Check if summary is a valid one line string."""
summary_re = re.compile('^.+$')
if len(summary) > 512:
raise ValidationError('Summary should be less than 512 chars.')
if not summary_re.match(summary):... | the_stack_v2_python_sparse | pypis/api/models/packages.py | jurelou/pypis | train | 1 | |
dd0b105c69a8379e3deba813f791b9cb73b1e711 | [
"hash_map = {}\nvote = defaultdict(int)\ncnt_max = float('-inf')\ncnt_person = -1\nfor idx, t in enumerate(times):\n vote[persons[idx]] += 1\n if vote[persons[idx]] >= cnt_max:\n cnt_person = persons[idx]\n cnt_max = vote[persons[idx]]\n hash_map[t] = cnt_person\nself.hash_map = hash_map\nsel... | <|body_start_0|>
hash_map = {}
vote = defaultdict(int)
cnt_max = float('-inf')
cnt_person = -1
for idx, t in enumerate(times):
vote[persons[idx]] += 1
if vote[persons[idx]] >= cnt_max:
cnt_person = persons[idx]
cnt_max = vot... | TopVotedCandidate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hash_map = {}
vote = defaultd... | stack_v2_sparse_classes_36k_train_026406 | 1,190 | permissive | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | null | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
hash_map = {}
vote = defaultdict(int)
cnt_max = float('-inf')
cnt_person = -1
for idx, t in enumerate(times):
vote[persons[idx]] += 1
... | the_stack_v2_python_sparse | 911.Online-Election.py | mickey0524/leetcode | train | 27 | |
bf52cdb366bf2827c2168f9a33a80c59443be497 | [
"super().__init__()\nself._mask = mask\nself._use_condition = use_condition\nself._hidden_conv = tf.keras.Sequential([layer for num in num_channels_hidden for layer in [tf.keras.layers.Conv2D(num, kernel_size=[5, 5], padding='same', activation='relu', use_bias=False), tf.keras.layers.BatchNormalization()]])\nself._... | <|body_start_0|>
super().__init__()
self._mask = mask
self._use_condition = use_condition
self._hidden_conv = tf.keras.Sequential([layer for num in num_channels_hidden for layer in [tf.keras.layers.Conv2D(num, kernel_size=[5, 5], padding='same', activation='relu', use_bias=False), tf.ker... | Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress: | EmbeddingConditionedConvAffineCouplingLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddingConditionedConvAffineCouplingLayer:
"""Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress:"""
def __init__(self, num_channels_hidden, compression_size, mask, use_condition):
"""Initializes ... | stack_v2_sparse_classes_36k_train_026407 | 12,897 | no_license | [
{
"docstring": "Initializes the object. Args: num_channels_hidden: compression_size: mask: use_condition:",
"name": "__init__",
"signature": "def __init__(self, num_channels_hidden, compression_size, mask, use_condition)"
},
{
"docstring": "Applies the layer to the inputs. Args: image: embedding... | 2 | stack_v2_sparse_classes_30k_train_017067 | Implement the Python class `EmbeddingConditionedConvAffineCouplingLayer` described below.
Class description:
Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress:
Method signatures and docstrings:
- def __init__(self, num_channels_hid... | Implement the Python class `EmbeddingConditionedConvAffineCouplingLayer` described below.
Class description:
Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress:
Method signatures and docstrings:
- def __init__(self, num_channels_hid... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class EmbeddingConditionedConvAffineCouplingLayer:
"""Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress:"""
def __init__(self, num_channels_hidden, compression_size, mask, use_condition):
"""Initializes ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmbeddingConditionedConvAffineCouplingLayer:
"""Embedding conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _hidden_conv: _log_scale: _shift: _compress:"""
def __init__(self, num_channels_hidden, compression_size, mask, use_condition):
"""Initializes the object. A... | the_stack_v2_python_sparse | flow.py | gaotianxiang/text-to-image-synthesis | train | 0 |
55dc1ccf0a009ba7c6302577b9e058650eb2c233 | [
"from django.core.exceptions import ObjectDoesNotExist\nresult = super(UserSerializer, self).to_representation(value)\nif result['tenant_admin'] and result['tenant']:\n try:\n row = Tenant.objects.get(pk=result['tenant'])\n except ObjectDoesNotExist:\n logger.warning('Tenant_admin without a tena... | <|body_start_0|>
from django.core.exceptions import ObjectDoesNotExist
result = super(UserSerializer, self).to_representation(value)
if result['tenant_admin'] and result['tenant']:
try:
row = Tenant.objects.get(pk=result['tenant'])
except ObjectDoesNotExis... | Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant. | UserSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant."""
def to_representation(self, value):
... | stack_v2_sparse_classes_36k_train_026408 | 5,786 | permissive | [
{
"docstring": "Include Goldstone tenant and cloud information if the user is a tenant_admin.",
"name": "to_representation",
"signature": "def to_representation(self, value)"
},
{
"docstring": "Update the corresponding Cloud row for this User, if she is a tenant_admin AND changed any Cloud field... | 2 | stack_v2_sparse_classes_30k_train_001297 | Implement the Python class `UserSerializer` described below.
Class description:
Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant.
Metho... | Implement the Python class `UserSerializer` described below.
Class description:
Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant.
Metho... | d7f1f1f1ff926148d2aa541d0bd4758173aa76d5 | <|skeleton|>
class UserSerializer:
"""Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant."""
def to_representation(self, value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSerializer:
"""Expose a subset of the available User fields, treat some as read-only, and allow tenant_adminds to read/write their Cloud row. This presently handles at most one Goldstone tenant per user, and at most one OpenStack cloud per tenant."""
def to_representation(self, value):
"""Inc... | the_stack_v2_python_sparse | goldstone/user/views.py | leftees/goldstone-server | train | 0 |
8b3f61222332b276c900f83c0287b3a7eea38922 | [
"if datacenter is None:\n pylogger.error('Datacenter name is required')\nroot_folder = client_object.get_root_folder()\nfor folder in root_folder.childEntity:\n if isinstance(folder, vim.Datacenter):\n if folder.name == datacenter:\n for component in folder.networkFolder.childEntity:\n ... | <|body_start_0|>
if datacenter is None:
pylogger.error('Datacenter name is required')
root_folder = client_object.get_root_folder()
for folder in root_folder.childEntity:
if isinstance(folder, vim.Datacenter):
if folder.name == datacenter:
... | VC55SwitchImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VC55SwitchImpl:
def check_DVS_exists(cls, client_object, name=None, datacenter=None):
"""Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param client_object: VCAPIClient instance @type name: str @param name: DVS name @type datacenter: str @param ... | stack_v2_sparse_classes_36k_train_026409 | 2,762 | no_license | [
{
"docstring": "Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param client_object: VCAPIClient instance @type name: str @param name: DVS name @type datacenter: str @param datacenter: Datacenter name @rtype: str @return: Success or Failure",
"name": "check_DVS_exis... | 2 | null | Implement the Python class `VC55SwitchImpl` described below.
Class description:
Implement the VC55SwitchImpl class.
Method signatures and docstrings:
- def check_DVS_exists(cls, client_object, name=None, datacenter=None): Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param ... | Implement the Python class `VC55SwitchImpl` described below.
Class description:
Implement the VC55SwitchImpl class.
Method signatures and docstrings:
- def check_DVS_exists(cls, client_object, name=None, datacenter=None): Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param ... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class VC55SwitchImpl:
def check_DVS_exists(cls, client_object, name=None, datacenter=None):
"""Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param client_object: VCAPIClient instance @type name: str @param name: DVS name @type datacenter: str @param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VC55SwitchImpl:
def check_DVS_exists(cls, client_object, name=None, datacenter=None):
"""Checks if a distributed virtual switch exists. @type client_object: VCAPIClient instance @param client_object: VCAPIClient instance @type name: str @param name: DVS name @type datacenter: str @param datacenter: Da... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/vsphere/vc/api/vc55_switch_impl.py | Cloudxtreme/MyProject | train | 0 | |
c28cb205c3779ef5728cf1eb3280c64ecd4cecb0 | [
"new = sorted(nums)\nmid = (len(new) + 1) / 2\nsmall = new[:mid]\nlarge = new[mid:]\nfor i in xrange(len(new)):\n if i % 2 == 0:\n if small:\n nums[i] = small.pop()\n elif large:\n nums[i] = large.pop()",
"nums.sort()\nmid = (len(nums) + 1) / 2\nsmall = nums[:mid]\nlarge = nums[mid:... | <|body_start_0|>
new = sorted(nums)
mid = (len(new) + 1) / 2
small = new[:mid]
large = new[mid:]
for i in xrange(len(new)):
if i % 2 == 0:
if small:
nums[i] = small.pop()
elif large:
nums[i] = large.pop()... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k_train_026410 | 1,745 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "wiggleSort",
"signature": "def wiggleSort(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "wi... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def wiggleSort2(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def wiggleSort2(self, nums): :type nums: List[int] :rtype: ... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def wiggleSort2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
new = sorted(nums)
mid = (len(new) + 1) / 2
small = new[:mid]
large = new[mid:]
for i in xrange(len(new)):
if i % 2 =... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00324.Wiggle_Sort_II.py | roger6blog/LeetCode | train | 0 | |
3bb8d8de5ccfeb50446189311cf121012290f461 | [
"if isinstance(tracked_modules, tf.Module):\n tracked_modules = [tracked_modules] + list(tracked_modules.submodules)\nself._tracked_modules = list(tracked_modules)",
"logged_tensors = collections.OrderedDict()\nfor submodule in self._tracked_modules:\n if not isinstance(submodule, LoggingModule):\n c... | <|body_start_0|>
if isinstance(tracked_modules, tf.Module):
tracked_modules = [tracked_modules] + list(tracked_modules.submodules)
self._tracked_modules = list(tracked_modules)
<|end_body_0|>
<|body_start_1|>
logged_tensors = collections.OrderedDict()
for submodule in self._... | Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors | LoggingTape | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingTape:
"""Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors"""
def __init__(self, tracked_modules):... | stack_v2_sparse_classes_36k_train_026411 | 4,662 | permissive | [
{
"docstring": "Creates a LoggingTape. Args: tracked_modules: Specifies a list of tf.Modules from which tensors should be collected for logging (if they are LoggingModules) Can either be a list of tf.Modules or a single tf.Module, in which case the tracked set of modules consists of the tf.Module and its set of... | 3 | null | Implement the Python class `LoggingTape` described below.
Class description:
Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors
Meth... | Implement the Python class `LoggingTape` described below.
Class description:
Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors
Meth... | 0e1e0ac9178a670ad1e1463baed92020e88905ec | <|skeleton|>
class LoggingTape:
"""Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors"""
def __init__(self, tracked_modules):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggingTape:
"""Context manager that allows to collect logging tensors from LoggingModules. Sample usage: >>> with LoggingTape(my_tf_module) as logged_tensors: >>> result = my_tf_module.arbitrary_function(input_tensor) >>> return result, logged_tensors"""
def __init__(self, tracked_modules):
"""C... | the_stack_v2_python_sparse | agents/policy_gradient/modules/logging_module.py | google-research/seed_rl | train | 818 |
eedc647d421195246fd8a46d998b671ae95678df | [
"super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label))\nself.register_buffer('fake_label', torch.tensor(target_fake_label))\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\nelif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLo... | <|body_start_0|>
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.gan_mode = gan_mode
if gan_mode == 'lsgan':
self.loss = nn.MSELoss()
e... | Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. | GANLoss | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: ga... | stack_v2_sparse_classes_36k_train_026412 | 13,787 | permissive | [
{
"docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discrimin... | 3 | stack_v2_sparse_classes_30k_train_010405 | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake... | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake... | ebb8c0333bbd33c063b6dd4a21a0559eb86d13e9 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: gan_mode (str) ... | the_stack_v2_python_sparse | simplegan_experiments/models/base_networks.py | Qun-Li/OroJaR | train | 0 |
71585efbea0bb8d05a41df1d1f1e0279bcabe658 | [
"try:\n if not self.args:\n return self.display_main_categories()\n if not self.switches:\n return self.display_category_or_entry()\n if 'search' in self.switches:\n return self.search_knowledge_base()\n if 'request' in self.switches:\n return self.create_lore_question()\n ... | <|body_start_0|>
try:
if not self.args:
return self.display_main_categories()
if not self.switches:
return self.display_category_or_entry()
if 'search' in self.switches:
return self.search_knowledge_base()
if 'reques... | View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list of answers to questions about the setting of the game, from the perspective of t... | CmdLoreSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdLoreSearch:
"""View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list of answers to questions about the setti... | stack_v2_sparse_classes_36k_train_026413 | 5,868 | permissive | [
{
"docstring": "Executes Lore cmd",
"name": "func",
"signature": "def func(self)"
},
{
"docstring": "Displays the main categories for no input",
"name": "display_main_categories",
"signature": "def display_main_categories(self)"
},
{
"docstring": "Display a category and/or an ent... | 5 | null | Implement the Python class `CmdLoreSearch` described below.
Class description:
View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list ... | Implement the Python class `CmdLoreSearch` described below.
Class description:
View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list ... | 363a1f14fd1a640580a4bf4486a1afe776757557 | <|skeleton|>
class CmdLoreSearch:
"""View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list of answers to questions about the setti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CmdLoreSearch:
"""View the Lore/Theme Knowledge Base or ask a question to be added Usage: lore [<entry or category name>] lore/search <keyword or phrase> lore/request <category>/<entry title>=[question to be answered] The Lore/Theme Knowledge Base is a list of answers to questions about the setting of the gam... | the_stack_v2_python_sparse | web/helpdesk/lore_commands.py | Arx-Game/arxcode | train | 52 |
eb39cd6014d393a90854bd3bf949ff5ec25522e3 | [
"if not validated_data.get('created', None):\n validated_data['created'] = timezone.now()\nvalidated_data['updated'] = timezone.now()\nif validated_data.get('created_by', None) is None:\n validated_data['created_by'] = self.context['request'].user\nif not validated_data.get('updated_by', None):\n validated... | <|body_start_0|>
if not validated_data.get('created', None):
validated_data['created'] = timezone.now()
validated_data['updated'] = timezone.now()
if validated_data.get('created_by', None) is None:
validated_data['created_by'] = self.context['request'].user
if not... | Injects the fields in the abstract base model as a model instance is being saved. | AbstractFieldsMixin | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
<|body_0|>
def get_fields(self):
"""Overridden to tak... | stack_v2_sparse_classes_36k_train_026414 | 2,081 | permissive | [
{
"docstring": "`created` and `created_by` are only mutated if they are null",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Overridden to take advantage of partial response",
"name": "get_fields",
"signature": "def get_fields(self)"
}
] | 2 | null | Implement the Python class `AbstractFieldsMixin` described below.
Class description:
Injects the fields in the abstract base model as a model instance is being saved.
Method signatures and docstrings:
- def create(self, validated_data): `created` and `created_by` are only mutated if they are null
- def get_fields(sel... | Implement the Python class `AbstractFieldsMixin` described below.
Class description:
Injects the fields in the abstract base model as a model instance is being saved.
Method signatures and docstrings:
- def create(self, validated_data): `created` and `created_by` are only mutated if they are null
- def get_fields(sel... | ecbb8954053be06bbcac7e1132811d73534c78d9 | <|skeleton|>
class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
<|body_0|>
def get_fields(self):
"""Overridden to tak... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
if not validated_data.get('created', None):
validated_data['created... | the_stack_v2_python_sparse | common/serializers/serializer_base.py | MasterFacilityList/mfl_api | train | 20 |
3812932b9c7d8d2ae46ac406c102129afcabe53d | [
"self._crossover_prob = crossover_prob\nself._uniform_prob = uniform_prob\nreturn",
"new_org_1 = org_1.copy()\nnew_org_2 = org_2.copy()\ncrossover_chance = random.random()\nif crossover_chance <= self._crossover_prob:\n minlen = min(len(new_org_1.genome), len(new_org_2.genome))\n for i in range(minlen):\n ... | <|body_start_0|>
self._crossover_prob = crossover_prob
self._uniform_prob = uniform_prob
return
<|end_body_0|>
<|body_start_1|>
new_org_1 = org_1.copy()
new_org_2 = org_2.copy()
crossover_chance = random.random()
if crossover_chance <= self._crossover_prob:
... | Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability to occur. | UniformCrossover | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniformCrossover:
"""Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability to occur."""
def __init__(self, c... | stack_v2_sparse_classes_36k_train_026415 | 1,744 | permissive | [
{
"docstring": "Initialize to do uniform crossover at the specified probability and frequency.",
"name": "__init__",
"signature": "def __init__(self, crossover_prob=0.1, uniform_prob=0.7)"
},
{
"docstring": "Potentially do a crossover between the two organisms.",
"name": "do_crossover",
... | 2 | stack_v2_sparse_classes_30k_train_010770 | Implement the Python class `UniformCrossover` described below.
Class description:
Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability... | Implement the Python class `UniformCrossover` described below.
Class description:
Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class UniformCrossover:
"""Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability to occur."""
def __init__(self, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UniformCrossover:
"""Perform single point crossover between genomes at some defined rates. This performs a single crossover between two genomes at some defined frequency. The location of the crossover is chosen randomly if the crossover meets the probability to occur."""
def __init__(self, crossover_prob... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/GA/Crossover/Uniform.py | LyonsLab/coge | train | 41 |
546209af8eefca0f39acd608d996b9e31f628460 | [
"super().__init__(coordinator, api_port, description.key)\nself.entity_description = description\nif description.name != UNDEFINED:\n self._attr_has_entity_name = False",
"try:\n return cast(StateType, self.entity_description.value(self.coordinator.data))\nexcept TypeError:\n return None"
] | <|body_start_0|>
super().__init__(coordinator, api_port, description.key)
self.entity_description = description
if description.name != UNDEFINED:
self._attr_has_entity_name = False
<|end_body_0|>
<|body_start_1|>
try:
return cast(StateType, self.entity_descriptio... | Define a System Bridge sensor. | SystemBridgeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemBridgeSensor:
"""Define a System Bridge sensor."""
def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None:
"""Initialize."""
<|body_0|>
def native_value(self) -> StateType:
... | stack_v2_sparse_classes_36k_train_026416 | 21,816 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None"
},
{
"docstring": "Return the state.",
"name": "native_value",
"signature": "def na... | 2 | null | Implement the Python class `SystemBridgeSensor` described below.
Class description:
Define a System Bridge sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None: Initialize.
- def native_v... | Implement the Python class `SystemBridgeSensor` described below.
Class description:
Define a System Bridge sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None: Initialize.
- def native_v... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SystemBridgeSensor:
"""Define a System Bridge sensor."""
def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None:
"""Initialize."""
<|body_0|>
def native_value(self) -> StateType:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemBridgeSensor:
"""Define a System Bridge sensor."""
def __init__(self, coordinator: SystemBridgeDataUpdateCoordinator, description: SystemBridgeSensorEntityDescription, api_port: int) -> None:
"""Initialize."""
super().__init__(coordinator, api_port, description.key)
self.ent... | the_stack_v2_python_sparse | homeassistant/components/system_bridge/sensor.py | home-assistant/core | train | 35,501 |
600b474162e535fa590fe388601d73e476261085 | [
"super().__init__()\nself.add_module('conv', Conv(in_channels=in_feats, out_channels=out_feats, kernel_size=3, stride=1, padding=1, bias=False))\nself.add_module('norm', Norm(out_feats))\nself.add_module('relu', nn.ReLU(inplace=True))",
"x = self.conv(x)\nx = self.norm(x)\nx = self.relu(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.add_module('conv', Conv(in_channels=in_feats, out_channels=out_feats, kernel_size=3, stride=1, padding=1, bias=False))
self.add_module('norm', Norm(out_feats))
self.add_module('relu', nn.ReLU(inplace=True))
<|end_body_0|>
<|body_start_1|>
... | A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Module): A convolutional layer. | _ConvBlock | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ConvBlock:
"""A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Module): A convolutional layer."""
def... | stack_v2_sparse_classes_36k_train_026417 | 24,719 | permissive | [
{
"docstring": "Initializes the ConvBlock. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Module): A convolutional layer.",
"name": "__init__",
"signature": "def __init__(self, in_feats, out_feats, Norm, Conv)... | 2 | stack_v2_sparse_classes_30k_train_014540 | Implement the Python class `_ConvBlock` described below.
Class description:
A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Modu... | Implement the Python class `_ConvBlock` described below.
Class description:
A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Modu... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class _ConvBlock:
"""A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Module): A convolutional layer."""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ConvBlock:
"""A block consisting of a convolutional layer followed by batch normalization and ReLU activation. Args: in_feats (int): Number of input features. out_feats (int): Number of output features. Norm (nn.Module): A normalization layer. Conv (nn.Module): A convolutional layer."""
def __init__(sel... | the_stack_v2_python_sparse | GANDLF/models/unetr.py | mlcommons/GaNDLF | train | 45 |
663a62b5eab366384fadf7e9f3b4e48215a2dfa1 | [
"self.name = name\nself.lan_ip = lan_ip\nself.uplink = uplink\nself.public_port = public_port\nself.local_port = local_port\nself.allowed_ips = allowed_ips\nself.protocol = protocol",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nlan_ip = dictionary.get('lanIp')\nuplink = dictionary.get... | <|body_start_0|>
self.name = name
self.lan_ip = lan_ip
self.uplink = uplink
self.public_port = public_port
self.local_port = local_port
self.allowed_ips = allowed_ips
self.protocol = protocol
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): The physical WAN interface on which the ... | Rule9Model | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): Th... | stack_v2_sparse_classes_36k_train_026418 | 3,221 | permissive | [
{
"docstring": "Constructor for the Rule9Model class",
"name": "__init__",
"signature": "def __init__(self, name=None, lan_ip=None, uplink=None, public_port=None, local_port=None, allowed_ips=None, protocol=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | stack_v2_sparse_classes_30k_train_019597 | Implement the Python class `Rule9Model` described below.
Class description:
Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make a... | Implement the Python class `Rule9Model` described below.
Class description:
Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make a... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): The physical WA... | the_stack_v2_python_sparse | meraki_sdk/models/rule_9_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
a6cf2f8b4e4dcffa41fa250d806c622a52027b86 | [
"self.ignores = dict()\nself.bits = dict()\nif physicsObjectList != None:\n if len(physicsObjectList) > CollisionManager.MAX_SIZE:\n raise ValueError('The maximum number of Rigid Bodies which may be mapped is 16', len(physicsObjectList), '>16')\n for physicsObject in physicsObjectList:\n t_id = ... | <|body_start_0|>
self.ignores = dict()
self.bits = dict()
if physicsObjectList != None:
if len(physicsObjectList) > CollisionManager.MAX_SIZE:
raise ValueError('The maximum number of Rigid Bodies which may be mapped is 16', len(physicsObjectList), '>16')
f... | This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies, this limitation may be lifted with the implementation of BroadPhaseFilter. | CollisionManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionManager:
"""This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies, this limitation may be lifted with the... | stack_v2_sparse_classes_36k_train_026419 | 4,634 | no_license | [
{
"docstring": "Initializes an empty CollisionManager, optionally if a list of PhysicsObjects are supplied, the dictionary is initialized to contain those physicsObjects with NO IGNORED collisions.",
"name": "__init__",
"signature": "def __init__(self, physicsObjectList=None)"
},
{
"docstring": ... | 6 | stack_v2_sparse_classes_30k_test_000872 | Implement the Python class `CollisionManager` described below.
Class description:
This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies,... | Implement the Python class `CollisionManager` described below.
Class description:
This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies,... | 907f60c3580d964b0be2e2b2c3b25216854aeedb | <|skeleton|>
class CollisionManager:
"""This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies, this limitation may be lifted with the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollisionManager:
"""This object manages collision groups for RigidBodies by providing a simple interface to declare collisions between pairs of rigid bodies as ignored by the physics engine. Currently this manager is limited to a maximum of 16 Rigid Bodies, this limitation may be lifted with the implementati... | the_stack_v2_python_sparse | critters/physics/collisionManager.py | hbcbh1999/PyCritters | train | 0 |
91093f8de2b68e57eb4a7a9666f6aa9c23dbc50d | [
"if sideAngle is None:\n if len(loop) > 0:\n sideAngle = 2.0 * math.pi / float(len(loop))\n else:\n sideAngle = 1.0\n print('Warning, loop has no sides in SideLoop in lineation.')\nif sideLength is None:\n if len(loop) > 0:\n sideLength = euclidean.getLoopLength(loop) / float(le... | <|body_start_0|>
if sideAngle is None:
if len(loop) > 0:
sideAngle = 2.0 * math.pi / float(len(loop))
else:
sideAngle = 1.0
print('Warning, loop has no sides in SideLoop in lineation.')
if sideLength is None:
if len(loop... | Class to handle loop, side angle and side length. | SideLoop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SideLoop:
"""Class to handle loop, side angle and side length."""
def __init__(self, loop, sideAngle=None, sideLength=None):
"""Initialize."""
<|body_0|>
def getManipulationPluginLoops(self, elementNode):
"""Get loop manipulated by the plugins in the manipulation... | stack_v2_sparse_classes_36k_train_026420 | 12,603 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, loop, sideAngle=None, sideLength=None)"
},
{
"docstring": "Get loop manipulated by the plugins in the manipulation paths folder.",
"name": "getManipulationPluginLoops",
"signature": "def getManipulationPlu... | 3 | stack_v2_sparse_classes_30k_train_007800 | Implement the Python class `SideLoop` described below.
Class description:
Class to handle loop, side angle and side length.
Method signatures and docstrings:
- def __init__(self, loop, sideAngle=None, sideLength=None): Initialize.
- def getManipulationPluginLoops(self, elementNode): Get loop manipulated by the plugin... | Implement the Python class `SideLoop` described below.
Class description:
Class to handle loop, side angle and side length.
Method signatures and docstrings:
- def __init__(self, loop, sideAngle=None, sideLength=None): Initialize.
- def getManipulationPluginLoops(self, elementNode): Get loop manipulated by the plugin... | ef1732ade7b1ae3c676e5321333c7ca88c9db514 | <|skeleton|>
class SideLoop:
"""Class to handle loop, side angle and side length."""
def __init__(self, loop, sideAngle=None, sideLength=None):
"""Initialize."""
<|body_0|>
def getManipulationPluginLoops(self, elementNode):
"""Get loop manipulated by the plugins in the manipulation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SideLoop:
"""Class to handle loop, side angle and side length."""
def __init__(self, loop, sideAngle=None, sideLength=None):
"""Initialize."""
if sideAngle is None:
if len(loop) > 0:
sideAngle = 2.0 * math.pi / float(len(loop))
else:
... | the_stack_v2_python_sparse | fabmetheus_utilities/geometry/creation/lineation.py | joewalnes/SFACT | train | 1 |
745ba62ecc7fbfe8a1efeb84d3f5a000a396f6ef | [
"b = (m ^ n).bit_length()\nb = int(log(m ^ n) // log(2)) + 1\nm >>= b\nreturn m << b",
"if m == n:\n return m\ncnt, digits = (0, 1)\ntmp = n\nwhile tmp > 1:\n digits += 1\n tmp >>= 1\nwhile digits > 1:\n if m < 2 ** (digits - 1):\n return cnt\n cnt += 2 ** (digits - 1)\n m -= 2 ** (digits... | <|body_start_0|>
b = (m ^ n).bit_length()
b = int(log(m ^ n) // log(2)) + 1
m >>= b
return m << b
<|end_body_0|>
<|body_start_1|>
if m == n:
return m
cnt, digits = (0, 1)
tmp = n
while tmp > 1:
digits += 1
tmp >>= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeBitwiseAnd_math(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
b = (m ^ n).bit_length()... | stack_v2_sparse_classes_36k_train_026421 | 1,248 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd_math",
"signature": "def rangeBitwiseAnd_math(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd",
"signature": "def rangeBitwiseAnd(self, m, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd_math(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd_math(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def rangeBitwiseAnd_math(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rangeBitwiseAnd_math(self, m, n):
""":type m: int :type n: int :rtype: int"""
b = (m ^ n).bit_length()
b = int(log(m ^ n) // log(2)) + 1
m >>= b
return m << b
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
... | the_stack_v2_python_sparse | 201_rangeBitwiseAnd.py | jennyChing/leetCode | train | 2 | |
b353b707cacb15d728f60c135063e4f6b488eee8 | [
"pygame.init()\nself.screen = pygame.display.set_mode((1200, 800))\npygame.display.set_caption('Empty Screen')",
"while True:\n self._check_events()\n pygame.display.flip()",
"for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n ... | <|body_start_0|>
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Empty Screen')
<|end_body_0|>
<|body_start_1|>
while True:
self._check_events()
pygame.display.flip()
<|end_body_1|>
<|body_start_2|>
for event ... | Uses pygame to create an empty screen, and detects KEY_DOWN. | EmptyScreen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmptyScreen:
"""Uses pygame to create an empty screen, and detects KEY_DOWN."""
def __init__(self):
"""Initialize the game, and create game resources."""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
def _check_eve... | stack_v2_sparse_classes_36k_train_026422 | 878 | no_license | [
{
"docstring": "Initialize the game, and create game resources.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Start the main loop for the game.",
"name": "run_game",
"signature": "def run_game(self)"
},
{
"docstring": "Respond to keypress events.",
... | 3 | stack_v2_sparse_classes_30k_train_021038 | Implement the Python class `EmptyScreen` described below.
Class description:
Uses pygame to create an empty screen, and detects KEY_DOWN.
Method signatures and docstrings:
- def __init__(self): Initialize the game, and create game resources.
- def run_game(self): Start the main loop for the game.
- def _check_events(... | Implement the Python class `EmptyScreen` described below.
Class description:
Uses pygame to create an empty screen, and detects KEY_DOWN.
Method signatures and docstrings:
- def __init__(self): Initialize the game, and create game resources.
- def run_game(self): Start the main loop for the game.
- def _check_events(... | 1c3ad17467c3d8deea9f3566b5eb66cbc6358a6d | <|skeleton|>
class EmptyScreen:
"""Uses pygame to create an empty screen, and detects KEY_DOWN."""
def __init__(self):
"""Initialize the game, and create game resources."""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
def _check_eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmptyScreen:
"""Uses pygame to create an empty screen, and detects KEY_DOWN."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Empty Screen')
def ru... | the_stack_v2_python_sparse | projects/exercises/empty_screen/empty_screen.py | iloverugs/pcc_2e_student | train | 0 |
c03843725a4cac8f35e3e0025e33cdb394523ba2 | [
"fmt_text = ''\nfor sentence in document.sentences:\n fmt_text += CabochaDumper.sent_to_format(sentence)\nfmt_text += 'EOT\\n'\nreturn fmt_text",
"fmt_text = ''\nfor chunk in sentence.chunks:\n fmt_text += CabochaDumper.chunk_to_format(chunk)\n for token in chunk.tokens:\n fmt_text += CabochaDumpe... | <|body_start_0|>
fmt_text = ''
for sentence in document.sentences:
fmt_text += CabochaDumper.sent_to_format(sentence)
fmt_text += 'EOT\n'
return fmt_text
<|end_body_0|>
<|body_start_1|>
fmt_text = ''
for chunk in sentence.chunks:
fmt_text += Caboc... | CabochaDumper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CabochaDumper:
def doc_to_format(document: nlelement.Document):
"""DocumentオブジェクトからCaboChaフォーマットを生成する"""
<|body_0|>
def sent_to_format(sentence: nlelement.Sentence):
"""SentenceオブジェクトからCaboChaフォーマットを生成する"""
<|body_1|>
def chunk_to_format(chunk: nlelement... | stack_v2_sparse_classes_36k_train_026423 | 15,056 | no_license | [
{
"docstring": "DocumentオブジェクトからCaboChaフォーマットを生成する",
"name": "doc_to_format",
"signature": "def doc_to_format(document: nlelement.Document)"
},
{
"docstring": "SentenceオブジェクトからCaboChaフォーマットを生成する",
"name": "sent_to_format",
"signature": "def sent_to_format(sentence: nlelement.Sentence)"
... | 4 | stack_v2_sparse_classes_30k_train_006697 | Implement the Python class `CabochaDumper` described below.
Class description:
Implement the CabochaDumper class.
Method signatures and docstrings:
- def doc_to_format(document: nlelement.Document): DocumentオブジェクトからCaboChaフォーマットを生成する
- def sent_to_format(sentence: nlelement.Sentence): SentenceオブジェクトからCaboChaフォーマットを生成... | Implement the Python class `CabochaDumper` described below.
Class description:
Implement the CabochaDumper class.
Method signatures and docstrings:
- def doc_to_format(document: nlelement.Document): DocumentオブジェクトからCaboChaフォーマットを生成する
- def sent_to_format(sentence: nlelement.Sentence): SentenceオブジェクトからCaboChaフォーマットを生成... | 4573b91c3108cc56fd9023ba217985b729ed793e | <|skeleton|>
class CabochaDumper:
def doc_to_format(document: nlelement.Document):
"""DocumentオブジェクトからCaboChaフォーマットを生成する"""
<|body_0|>
def sent_to_format(sentence: nlelement.Sentence):
"""SentenceオブジェクトからCaboChaフォーマットを生成する"""
<|body_1|>
def chunk_to_format(chunk: nlelement... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CabochaDumper:
def doc_to_format(document: nlelement.Document):
"""DocumentオブジェクトからCaboChaフォーマットを生成する"""
fmt_text = ''
for sentence in document.sentences:
fmt_text += CabochaDumper.sent_to_format(sentence)
fmt_text += 'EOT\n'
return fmt_text
def sent_to... | the_stack_v2_python_sparse | nlelement/loaders/cabocha.py | rokurosatp/nlelement | train | 0 | |
d9f34536eca44349f6a7c0bf12d4855b55c7f585 | [
"self.describer_model = _load_model(name)\nif level is None:\n n_layers = sum((i.startswith(('meg_net', 'megnet')) for i in self.describer_model.valid_names)) // 3\n level = n_layers\nself.name = name\nself.level = level\nself.mode = mode\nif stats is None:\n stats = ['min', 'max', 'range', 'mean', 'mean_a... | <|body_start_0|>
self.describer_model = _load_model(name)
if level is None:
n_layers = sum((i.startswith(('meg_net', 'megnet')) for i in self.describer_model.valid_names)) // 3
level = n_layers
self.name = name
self.level = level
self.mode = mode
i... | Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the feature-wise statistics. This requires the specification of level 'site_readout': ... | MEGNetStructure | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MEGNetStructure:
"""Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the feature-wise statistics. This requires ... | stack_v2_sparse_classes_36k_train_026424 | 7,639 | permissive | [
{
"docstring": "Args:s name (str or megnet.models.GraphModel): models name keys, megnet models path or a MEGNet GraphModel, if no name is provided, the models will be Eform_MP_2019. mode (str): choose one from ['site_stats', 'site_readout', 'final']. 'site_stats': Calculate the site features, and then use maml.... | 4 | stack_v2_sparse_classes_30k_train_012312 | Implement the Python class `MEGNetStructure` described below.
Class description:
Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the ... | Implement the Python class `MEGNetStructure` described below.
Class description:
Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the ... | 6ae3c7029b939e1183684358a3ae2fef41053be5 | <|skeleton|>
class MEGNetStructure:
"""Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the feature-wise statistics. This requires ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MEGNetStructure:
"""Use megnet pre-trained models as featurizer to get structural features. There are two methods to get structural descriptors from megnet models. mode: 'site_stats': Calculate the site features, and then use maml.utils.stats to compute the feature-wise statistics. This requires the specifica... | the_stack_v2_python_sparse | maml/describers/_megnet.py | materialsvirtuallab/maml | train | 266 |
138eb3ab5e261f8bc5ec13406a1c5a1a472aa0a6 | [
"self.application_id_local = kwargs.pop('id')\nself.adult = kwargs.pop('adult')\nself.name = kwargs.pop('name')\nsuper(OtherPeopleAdultDBSForm, self).__init__(*args, **kwargs)\nfull_stop_stripper(self)\nif AdultInHome.objects.filter(application_id=self.application_id_local, adult=self.adult).count() > 0:\n adult... | <|body_start_0|>
self.application_id_local = kwargs.pop('id')
self.adult = kwargs.pop('adult')
self.name = kwargs.pop('name')
super(OtherPeopleAdultDBSForm, self).__init__(*args, **kwargs)
full_stop_stripper(self)
if AdultInHome.objects.filter(application_id=self.applicat... | GOV.UK form for the People in your home: adult DBS page | OtherPeopleAdultDBSForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtherPeopleAdultDBSForm:
"""GOV.UK form for the People in your home: adult DBS page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult DBS form :param args: arguments passed to the form :param kwargs: keyword arguments ... | stack_v2_sparse_classes_36k_train_026425 | 20,631 | no_license | [
{
"docstring": "Method to configure the initialisation of the People in your home: adult DBS form :param args: arguments passed to the form :param kwargs: keyword arguments passed to the form, e.g. application ID",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_004969 | Implement the Python class `OtherPeopleAdultDBSForm` described below.
Class description:
GOV.UK form for the People in your home: adult DBS page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: adult DBS form :param args: argum... | Implement the Python class `OtherPeopleAdultDBSForm` described below.
Class description:
GOV.UK form for the People in your home: adult DBS page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: adult DBS form :param args: argum... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class OtherPeopleAdultDBSForm:
"""GOV.UK form for the People in your home: adult DBS page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult DBS form :param args: arguments passed to the form :param kwargs: keyword arguments ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OtherPeopleAdultDBSForm:
"""GOV.UK form for the People in your home: adult DBS page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult DBS form :param args: arguments passed to the form :param kwargs: keyword arguments passed to the... | the_stack_v2_python_sparse | application/forms/other_people.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
0a15d41669a326813b9736d5f679f23bfb6562c5 | [
"user_id = payload['user_id']\nprobes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)\nprobes_schema = ProbeSchema(many=True)\nprobes_schema.context = {'user': user_id}\ndata, errors = probes_schema.dump(probes)\nif errors:\n return json_response({'error': errors}, status=400)\nreturn jso... | <|body_start_0|>
user_id = payload['user_id']
probes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)
probes_schema = ProbeSchema(many=True)
probes_schema.context = {'user': user_id}
data, errors = probes_schema.dump(probes)
if errors:
r... | Get info, create and remove probes. | Probe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
<|body_0|>
async def post(self, payload: type_payload):
"""Create new probes."""
<|body_1|>
async def delete(self, payload: type_payload):
... | stack_v2_sparse_classes_36k_train_026426 | 3,127 | permissive | [
{
"docstring": "Get probes.",
"name": "get",
"signature": "async def get(self, payload: type_payload)"
},
{
"docstring": "Create new probes.",
"name": "post",
"signature": "async def post(self, payload: type_payload)"
},
{
"docstring": "Delete probes.",
"name": "delete",
... | 3 | null | Implement the Python class `Probe` described below.
Class description:
Get info, create and remove probes.
Method signatures and docstrings:
- async def get(self, payload: type_payload): Get probes.
- async def post(self, payload: type_payload): Create new probes.
- async def delete(self, payload: type_payload): Dele... | Implement the Python class `Probe` described below.
Class description:
Get info, create and remove probes.
Method signatures and docstrings:
- async def get(self, payload: type_payload): Get probes.
- async def post(self, payload: type_payload): Create new probes.
- async def delete(self, payload: type_payload): Dele... | e94889ce784f4399ca74f78be3bc42a5cd880d70 | <|skeleton|>
class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
<|body_0|>
async def post(self, payload: type_payload):
"""Create new probes."""
<|body_1|>
async def delete(self, payload: type_payload):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
user_id = payload['user_id']
probes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)
probes_schema = ProbeSchema(many=True)
probes_... | the_stack_v2_python_sparse | probes/views.py | cassinyio/cassiny-spawner | train | 1 |
e0cb9e87bfe0e7844f78546e691bcb686aec055a | [
"super(Transformer, self).__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enc_output = self.encoder(inputs, training, encoder_mask)\n... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_... | builds a transformer network | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""builds a transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""initialization constructor"""
<|body_0|>
def call(self, inputs, target, training, encoder_mask, look_ahead_ma... | stack_v2_sparse_classes_36k_train_026427 | 1,140 | no_license | [
{
"docstring": "initialization constructor",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1)"
},
{
"docstring": "call function",
"name": "call",
"signature": "def call(self, inputs, target, tr... | 2 | stack_v2_sparse_classes_30k_train_009719 | Implement the Python class `Transformer` described below.
Class description:
builds a transformer network
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): initialization constructor
- def call(self, inputs, target, train... | Implement the Python class `Transformer` described below.
Class description:
builds a transformer network
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): initialization constructor
- def call(self, inputs, target, train... | 80bf8d3354702f7fb9f79bbb5ed7e00fc19f788d | <|skeleton|>
class Transformer:
"""builds a transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""initialization constructor"""
<|body_0|>
def call(self, inputs, target, training, encoder_mask, look_ahead_ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""builds a transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""initialization constructor"""
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab,... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | Immaannn2222/holbertonschool-machine_learning | train | 1 |
c8e6384d2005695a635396ac73e6012212b2f42b | [
"extra_params = {} if extra_params is None else extra_params\nparams = {}\nfor key, parameter in self.Parameters.items():\n passed_value = extra_params.pop(key, None)\n ref_value = parameter.get_ref_value(passed_value)\n if ref_value is not None:\n params[key] = ref_value\nextended_parameters = {**s... | <|body_start_0|>
extra_params = {} if extra_params is None else extra_params
params = {}
for key, parameter in self.Parameters.items():
passed_value = extra_params.pop(key, None)
ref_value = parameter.get_ref_value(passed_value)
if ref_value is not None:
... | Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated values. - Metadata: Additional information about the template. - Outputs: ... | CFModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CFModel:
"""Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated values. - Metadata: Additional informat... | stack_v2_sparse_classes_36k_train_026428 | 5,447 | permissive | [
{
"docstring": "Resolve all intrinsic functions on the template. Arguments: extra_params: Values of parameters passed to the Cloudformation. Returns: A new CFModel.",
"name": "resolve",
"signature": "def resolve(self, extra_params=None) -> 'CFModel'"
},
{
"docstring": "Returns a model which has ... | 3 | stack_v2_sparse_classes_30k_train_016342 | Implement the Python class `CFModel` described below.
Class description:
Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated ... | Implement the Python class `CFModel` described below.
Class description:
Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated ... | 40290b9612af65a406489b7e120330c38f797f3f | <|skeleton|>
class CFModel:
"""Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated values. - Metadata: Additional informat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CFModel:
"""Template that describes AWS infrastructure. Properties: - AWSTemplateFormatVersion - Conditions: Conditions that control behaviour of the template. - Description: Description for the template. - Mappings: A 3 level mapping of keys and associated values. - Metadata: Additional information about the... | the_stack_v2_python_sparse | pycfmodel/model/cf_model.py | Skyscanner/pycfmodel | train | 25 |
2d0291479ba802c4944a356d7d2b12936a30165a | [
"if not isinstance(gate, Gate):\n raise TypeError('Expected gate object, got %s' % type(gate))\nself.gate = gate\nself.tag = tag\nself.name = 'Tagged(%s:%s)' % (gate.get_name(), tag)\nself.num_params = gate.get_num_params()\nself.size = gate.get_size()\nself.radixes = gate.get_radixes()\nif self.num_params == 0:... | <|body_start_0|>
if not isinstance(gate, Gate):
raise TypeError('Expected gate object, got %s' % type(gate))
self.gate = gate
self.tag = tag
self.name = 'Tagged(%s:%s)' % (gate.get_name(), tag)
self.num_params = gate.get_num_params()
self.size = gate.get_size(... | The TaggedGate Class. Allows a user to place a tag on a gate. | TaggedGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaggedGate:
"""The TaggedGate Class. Allows a user to place a tag on a gate."""
def __init__(self, gate: Gate, tag: Any) -> None:
"""Associate `tag` with `gate`."""
<|body_0|>
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unit... | stack_v2_sparse_classes_36k_train_026429 | 2,289 | permissive | [
{
"docstring": "Associate `tag` with `gate`.",
"name": "__init__",
"signature": "def __init__(self, gate: Gate, tag: Any) -> None"
},
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Sequenc... | 4 | stack_v2_sparse_classes_30k_train_012272 | Implement the Python class `TaggedGate` described below.
Class description:
The TaggedGate Class. Allows a user to place a tag on a gate.
Method signatures and docstrings:
- def __init__(self, gate: Gate, tag: Any) -> None: Associate `tag` with `gate`.
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMat... | Implement the Python class `TaggedGate` described below.
Class description:
The TaggedGate Class. Allows a user to place a tag on a gate.
Method signatures and docstrings:
- def __init__(self, gate: Gate, tag: Any) -> None: Associate `tag` with `gate`.
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMat... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class TaggedGate:
"""The TaggedGate Class. Allows a user to place a tag on a gate."""
def __init__(self, gate: Gate, tag: Any) -> None:
"""Associate `tag` with `gate`."""
<|body_0|>
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaggedGate:
"""The TaggedGate Class. Allows a user to place a tag on a gate."""
def __init__(self, gate: Gate, tag: Any) -> None:
"""Associate `tag` with `gate`."""
if not isinstance(gate, Gate):
raise TypeError('Expected gate object, got %s' % type(gate))
self.gate = ... | the_stack_v2_python_sparse | bqskit/ir/gates/composed/tagged.py | mtreinish/bqskit | train | 0 |
302c780ee6c9e6bdaf11138406aa3005def3a15d | [
"super(Clusters, self).__init__(gis=gis, url=url)\nself._con = gis\nself._url = url\nif url.lower().endswith('/clusters'):\n self._url = url\nelse:\n self._url = url + '/clusters'\nif initialize:\n self._init(gis)",
"url = self._url + '/create'\nparams = {'f': 'json', 'clusterName': cluster_name, 'machin... | <|body_start_0|>
super(Clusters, self).__init__(gis=gis, url=url)
self._con = gis
self._url = url
if url.lower().endswith('/clusters'):
self._url = url
else:
self._url = url + '/clusters'
if initialize:
self._init(gis)
<|end_body_0|>
<... | This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----------------------------------------... | Clusters | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----... | stack_v2_sparse_classes_36k_train_026430 | 14,794 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, url, gis, initialize=False)"
},
{
"docstring": "Creating a new cluster involves defining a clustering protocol that will be shared by all server machines participating in the cluster. All server machines that are ... | 3 | stack_v2_sparse_classes_30k_train_004507 | Implement the Python class `Clusters` described below.
Class description:
This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument... | Implement the Python class `Clusters` described below.
Class description:
This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument... | a874fe7e5c95196e4de68db2da0e2a05eb70e5d8 | <|skeleton|>
class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- ----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Clusters:
"""This resource is a collection of all the clusters created within your site. The Create Cluster operation lets you define a new cluster configuration. =============== ==================================================================== **Argument** **Description** --------------- -----------------... | the_stack_v2_python_sparse | arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/gis/server/admin/_clusters.py | SherbazHashmi/HackathonServer | train | 3 |
1f149501ee1f991a2fe0e31947b627d399d8a74a | [
"self.distance_x = distance_x\nself.distance_y = distance_y\nself.rho = rho\nself.eps = eps\nself.auditor_nsteps = auditor_nsteps\nself.auditor_lr = auditor_lr\nsuper().__init__(module=module, criterion=criterion, regression=regression, **kwargs)",
"self.initialize_criterion()\nkwargs = self.get_params_for('modul... | <|body_start_0|>
self.distance_x = distance_x
self.distance_y = distance_y
self.rho = rho
self.eps = eps
self.auditor_nsteps = auditor_nsteps
self.auditor_lr = auditor_lr
super().__init__(module=module, criterion=criterion, regression=regression, **kwargs)
<|end_b... | Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individual fairness. References: .. [#yuro... | SenSeI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenSeI:
"""Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individu... | stack_v2_sparse_classes_36k_train_026431 | 15,710 | permissive | [
{
"docstring": "Args: module (torch.nn.Module): Network architecture. criterion (torch.nn.Module): Loss function. distance_x (inFairness.distances.Distance): Distance metric in the input space. distance_y (inFairness.distances.Distance): Distance metric in the output space. rho (float): :math:`\\\\rho` paramete... | 2 | stack_v2_sparse_classes_30k_train_001963 | Implement the Python class `SenSeI` described below.
Class description:
Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer... | Implement the Python class `SenSeI` described below.
Class description:
Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class SenSeI:
"""Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SenSeI:
"""Sensitive Set Invariance (SenSeI). SenSeI is an in-processing method for individual fairness [#yurochkin20]_. In this method, individual fairness is formulated as invariance on certain sensitive sets. SenSeI minimizes a transport-based regularizer that enforces this version of individual fairness. ... | the_stack_v2_python_sparse | aif360/sklearn/inprocessing/infairness.py | Trusted-AI/AIF360 | train | 1,157 |
72344d8005be478611be8c85ded02e3e26a2c6b7 | [
"@layer_cache.cache(layer=layer_cache.Layers.Memcache | layer_cache.Layers.InAppMemory, compress_chunks=False)\ndef func(result):\n return result\nfunc(_BIG_STRING)\ninstance_cache.flush()\nself.assertIsNone(instance_cache.get(self.key))\nself.assertEqualTruncateError(_BIG_STRING, func('a'))\nself.assertEqualTru... | <|body_start_0|>
@layer_cache.cache(layer=layer_cache.Layers.Memcache | layer_cache.Layers.InAppMemory, compress_chunks=False)
def func(result):
return result
func(_BIG_STRING)
instance_cache.flush()
self.assertIsNone(instance_cache.get(self.key))
self.assertE... | LayerCacheLayerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerCacheLayerTest:
def test_repopulate_missing_inapp_cache_when_reading_from_memcache(self):
"""Tests if missing inapp cache gets repopulated from memcache It performs the checks on large values that will make use of the ChunkedResult"""
<|body_0|>
def test_missing_inapp_a... | stack_v2_sparse_classes_36k_train_026432 | 9,636 | no_license | [
{
"docstring": "Tests if missing inapp cache gets repopulated from memcache It performs the checks on large values that will make use of the ChunkedResult",
"name": "test_repopulate_missing_inapp_cache_when_reading_from_memcache",
"signature": "def test_repopulate_missing_inapp_cache_when_reading_from_m... | 2 | null | Implement the Python class `LayerCacheLayerTest` described below.
Class description:
Implement the LayerCacheLayerTest class.
Method signatures and docstrings:
- def test_repopulate_missing_inapp_cache_when_reading_from_memcache(self): Tests if missing inapp cache gets repopulated from memcache It performs the checks... | Implement the Python class `LayerCacheLayerTest` described below.
Class description:
Implement the LayerCacheLayerTest class.
Method signatures and docstrings:
- def test_repopulate_missing_inapp_cache_when_reading_from_memcache(self): Tests if missing inapp cache gets repopulated from memcache It performs the checks... | c6a3907d96d30f1cb43bf7bf2a392ff3e77a2568 | <|skeleton|>
class LayerCacheLayerTest:
def test_repopulate_missing_inapp_cache_when_reading_from_memcache(self):
"""Tests if missing inapp cache gets repopulated from memcache It performs the checks on large values that will make use of the ChunkedResult"""
<|body_0|>
def test_missing_inapp_a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerCacheLayerTest:
def test_repopulate_missing_inapp_cache_when_reading_from_memcache(self):
"""Tests if missing inapp cache gets repopulated from memcache It performs the checks on large values that will make use of the ChunkedResult"""
@layer_cache.cache(layer=layer_cache.Layers.Memcache |... | the_stack_v2_python_sparse | layer_cache_test.py | PerceptumNL/KhanLatest | train | 3 | |
363938c0bb29fea7b4a7eecd965948a6549c67c7 | [
"if root is None:\n return ''\ncode = str(root.val) + '\\n'\nq = Queue()\nq.put(root)\nwhile not q.empty():\n next_q = Queue()\n layer_code = list()\n while not q.empty():\n node = q.get()\n node_code = list()\n for child in node.children:\n next_q.put(child)\n ... | <|body_start_0|>
if root is None:
return ''
code = str(root.val) + '\n'
q = Queue()
q.put(root)
while not q.empty():
next_q = Queue()
layer_code = list()
while not q.empty():
node = q.get()
node_code ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_026433 | 2,344 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 78ed11f34fd03e9a188c9c6cb352e883016d05d9 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if root is None:
return ''
code = str(root.val) + '\n'
q = Queue()
q.put(root)
while not q.empty():
next_q = Queue()
... | the_stack_v2_python_sparse | 428_Serialize_and_Deserialize_N-ary_Tree.py | 26XINXIN/leetcode | train | 0 | |
bdc328f720aa38604d17a6fe12a61dfd4936e472 | [
"self.fp = None\nself.out = out\nif path:\n if not os.path.isdir(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n self.fp = open(path, mode='a')",
"if self.fp:\n self.fp.write(msg + os.linesep)\n self.fp.flush()\nif self.out:\n print(msg, file=self.out)"
] | <|body_start_0|>
self.fp = None
self.out = out
if path:
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path), exist_ok=True)
self.fp = open(path, mode='a')
<|end_body_0|>
<|body_start_1|>
if self.fp:
self.fp.w... | Logs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logs:
def __init__(self, path, out=sys.stderr):
"""Create a logs instance on a logs file."""
<|body_0|>
def log(self, msg):
"""Log a new message to the opened logs file, and optionnaly on stdout or stderr too."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_026434 | 6,259 | permissive | [
{
"docstring": "Create a logs instance on a logs file.",
"name": "__init__",
"signature": "def __init__(self, path, out=sys.stderr)"
},
{
"docstring": "Log a new message to the opened logs file, and optionnaly on stdout or stderr too.",
"name": "log",
"signature": "def log(self, msg)"
... | 2 | stack_v2_sparse_classes_30k_train_007980 | Implement the Python class `Logs` described below.
Class description:
Implement the Logs class.
Method signatures and docstrings:
- def __init__(self, path, out=sys.stderr): Create a logs instance on a logs file.
- def log(self, msg): Log a new message to the opened logs file, and optionnaly on stdout or stderr too. | Implement the Python class `Logs` described below.
Class description:
Implement the Logs class.
Method signatures and docstrings:
- def __init__(self, path, out=sys.stderr): Create a logs instance on a logs file.
- def log(self, msg): Log a new message to the opened logs file, and optionnaly on stdout or stderr too.
... | 8f92f14da8cd4bb815d81e1be083ff0a669a4f3c | <|skeleton|>
class Logs:
def __init__(self, path, out=sys.stderr):
"""Create a logs instance on a logs file."""
<|body_0|>
def log(self, msg):
"""Log a new message to the opened logs file, and optionnaly on stdout or stderr too."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logs:
def __init__(self, path, out=sys.stderr):
"""Create a logs instance on a logs file."""
self.fp = None
self.out = out
if path:
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path), exist_ok=True)
self.fp = o... | the_stack_v2_python_sparse | robosat_pink/core.py | dselivanov/robosat.pink | train | 8 | |
161931a27a3b4cf2723745b0e9d3a7fe758b305c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.externalConnectors.externalActivityResult'.... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | ExternalActivity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalActivity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalActivity:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k_train_026435 | 3,665 | 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: ExternalActivity",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `ExternalActivity` described below.
Class description:
Implement the ExternalActivity class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalActivity: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ExternalActivity` described below.
Class description:
Implement the ExternalActivity class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalActivity: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ExternalActivity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalActivity:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalActivity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalActivity:
"""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: Extern... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/external_activity.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
cc6504c5135d5801da67bb78d82f4ea6bddbe2f5 | [
"super(MultiHeadedAttention, self).__init__()\nassert dim_model % num_heads == 0\nself.d_k = dim_model // num_heads\nself.num_heads = num_heads\nself.linears = clones(nn.Linear(dim_model, dim_model), 4)\nself.attn = None",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nquery, key, ... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert dim_model % num_heads == 0
self.d_k = dim_model // num_heads
self.num_heads = num_heads
self.linears = clones(nn.Linear(dim_model, dim_model), 4)
self.attn = None
<|end_body_0|>
<|body_start_1|>
... | MultiHeadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, num_heads, dim_model):
"""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(Mu... | stack_v2_sparse_classes_36k_train_026436 | 28,143 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, num_heads, dim_model)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014041 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, num_heads, dim_model): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, num_heads, dim_model): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure 2
... | 6e2213b3ce7d809ba5435980f6775fcbe2ac11a1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, num_heads, dim_model):
"""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_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, num_heads, dim_model):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert dim_model % num_heads == 0
self.d_k = dim_model // num_heads
self.num_heads = num_heads
self.linears... | the_stack_v2_python_sparse | experiments/reinforce_transformer/reinforce_transformer_classes.py | czxttkl/Tutorials | train | 1 | |
277830f8b688774a55b3d5f33101d7bd61f14771 | [
"self.manager = manager\nself.async_add_entities = async_add_entities\nself.current_entities: dict[tuple[str, str | None, str], EnergyCostSensor] = {}",
"self.manager.async_listen_updates(self._process_manager_data)\nif self.manager.data:\n await self._process_manager_data()",
"to_add: list[EnergyCostSensor]... | <|body_start_0|>
self.manager = manager
self.async_add_entities = async_add_entities
self.current_entities: dict[tuple[str, str | None, str], EnergyCostSensor] = {}
<|end_body_0|>
<|body_start_1|>
self.manager.async_listen_updates(self._process_manager_data)
if self.manager.data... | Class to handle creation/removal of sensor data. | SensorManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorManager:
"""Class to handle creation/removal of sensor data."""
def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None:
"""Initialize sensor manager."""
<|body_0|>
async def async_start(self) -> None:
"""Start."""
... | stack_v2_sparse_classes_36k_train_026437 | 15,472 | permissive | [
{
"docstring": "Initialize sensor manager.",
"name": "__init__",
"signature": "def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None"
},
{
"docstring": "Start.",
"name": "async_start",
"signature": "async def async_start(self) -> None"
},
{
"... | 4 | null | Implement the Python class `SensorManager` described below.
Class description:
Class to handle creation/removal of sensor data.
Method signatures and docstrings:
- def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None: Initialize sensor manager.
- async def async_start(self) -> N... | Implement the Python class `SensorManager` described below.
Class description:
Class to handle creation/removal of sensor data.
Method signatures and docstrings:
- def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None: Initialize sensor manager.
- async def async_start(self) -> N... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SensorManager:
"""Class to handle creation/removal of sensor data."""
def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None:
"""Initialize sensor manager."""
<|body_0|>
async def async_start(self) -> None:
"""Start."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SensorManager:
"""Class to handle creation/removal of sensor data."""
def __init__(self, manager: EnergyManager, async_add_entities: AddEntitiesCallback) -> None:
"""Initialize sensor manager."""
self.manager = manager
self.async_add_entities = async_add_entities
self.curr... | the_stack_v2_python_sparse | homeassistant/components/energy/sensor.py | home-assistant/core | train | 35,501 |
9f40ea1c9c0ca2e59645b570f78456821219f777 | [
"self.duration = duration\nself.ip = ip\nself.is_udp = is_udp\nself.is_uplink = is_uplink\nself.port = port",
"link_type = 'UPLINK' if self.is_uplink else 'DOWNLINK'\nprotocol = 'UDP' if self.is_udp else 'TCP'\nreturn f'{type(self).__name__}: {link_type} {protocol} test, {self.duration} seconds for test device at... | <|body_start_0|>
self.duration = duration
self.ip = ip
self.is_udp = is_udp
self.is_uplink = is_uplink
self.port = port
<|end_body_0|>
<|body_start_1|>
link_type = 'UPLINK' if self.is_uplink else 'DOWNLINK'
protocol = 'UDP' if self.is_udp else 'TCP'
retur... | Information about the test instance for a single uplink/downlink traffic channel | TrafficTestInstance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficTestInstance:
"""Information about the test instance for a single uplink/downlink traffic channel"""
def __init__(self, is_uplink, is_udp, duration, ip, port):
"""Create a traffic test instance with the given values Args: is_uplink (bool): whether the test is uplink (else down... | stack_v2_sparse_classes_36k_train_026438 | 7,143 | permissive | [
{
"docstring": "Create a traffic test instance with the given values Args: is_uplink (bool): whether the test is uplink (else downlink) is_udp (bool): whether the test is UDP (else TCP) duration (int): the duration of the test, in seconds ip (ipaddress.ip_address): the IP of the test device (UE) port (int): the... | 2 | stack_v2_sparse_classes_30k_train_007746 | Implement the Python class `TrafficTestInstance` described below.
Class description:
Information about the test instance for a single uplink/downlink traffic channel
Method signatures and docstrings:
- def __init__(self, is_uplink, is_udp, duration, ip, port): Create a traffic test instance with the given values Args... | Implement the Python class `TrafficTestInstance` described below.
Class description:
Information about the test instance for a single uplink/downlink traffic channel
Method signatures and docstrings:
- def __init__(self, is_uplink, is_udp, duration, ip, port): Create a traffic test instance with the given values Args... | 0e1d895dfe625681229e181fbc2dbad83e13c5cb | <|skeleton|>
class TrafficTestInstance:
"""Information about the test instance for a single uplink/downlink traffic channel"""
def __init__(self, is_uplink, is_udp, duration, ip, port):
"""Create a traffic test instance with the given values Args: is_uplink (bool): whether the test is uplink (else down... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrafficTestInstance:
"""Information about the test instance for a single uplink/downlink traffic channel"""
def __init__(self, is_uplink, is_udp, duration, ip, port):
"""Create a traffic test instance with the given values Args: is_uplink (bool): whether the test is uplink (else downlink) is_udp ... | the_stack_v2_python_sparse | lte/gateway/python/integ_tests/s1aptests/util/traffic_messages.py | magma/magma | train | 1,219 |
6d7ee50ab2d4a7a866292407fe8ff1a1c88a84b8 | [
"norm = kwargs.pop('norm', None)\nactivation = kwargs.pop('activation', None)\nsuper().__init__(*args, **kwargs)\nself.norm = norm\nself.activation = activation\nself.conv2d = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=self.kernel_size, stride=self.stride, pad_mode=self.pad_... | <|body_start_0|>
norm = kwargs.pop('norm', None)
activation = kwargs.pop('activation', None)
super().__init__(*args, **kwargs)
self.norm = norm
self.activation = activation
self.conv2d = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=s... | A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features. | Conv2d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2d:
"""A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features."""
def __init__(self, *args, **kwargs):
"""Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm (nn.Module, optional): a normalization layer activation (... | stack_v2_sparse_classes_36k_train_026439 | 7,797 | permissive | [
{
"docstring": "Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm (nn.Module, optional): a normalization layer activation (callable(Tensor) -> Tensor): a callable activation function It assumes that norm layer is used before activation.",
"name": "__init__",
"signat... | 2 | null | Implement the Python class `Conv2d` described below.
Class description:
A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm ... | Implement the Python class `Conv2d` described below.
Class description:
A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Conv2d:
"""A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features."""
def __init__(self, *args, **kwargs):
"""Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm (nn.Module, optional): a normalization layer activation (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2d:
"""A wrapper around :class:`torch.nn.Conv2d` to support empty inputs and more features."""
def __init__(self, *args, **kwargs):
"""Extra keyword arguments supported in addition to those in `torch.nn.Conv2d`: Args: norm (nn.Module, optional): a normalization layer activation (callable(Tens... | the_stack_v2_python_sparse | community/cv/pointrend/maskrcnn_pointrend/src/point_rend/coarse_mask_head.py | mindspore-ai/models | train | 301 |
9040f70b37339c23dd6eab0140735a1e1ec76e4b | [
"skeleton_diffs = np.diff(skeleton, axis=0)\nchain_code_lengths = np.linalg.norm(skeleton_diffs, axis=1)\nreturn chain_code_lengths",
"if np.size(skeleton) == 0:\n return np.empty([])\nelse:\n distances = WormParserHelpers.chain_code_lengths(skeleton)\n distances = np.concatenate([np.array([0.0]), distan... | <|body_start_0|>
skeleton_diffs = np.diff(skeleton, axis=0)
chain_code_lengths = np.linalg.norm(skeleton_diffs, axis=1)
return chain_code_lengths
<|end_body_0|>
<|body_start_1|>
if np.size(skeleton) == 0:
return np.empty([])
else:
distances = WormParserHe... | WormParserHelpers | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WormParserHelpers:
def chain_code_lengths(skeleton):
"""Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel length to microns. These chain-code lengths are based on the Freeman 8-direction chain codes: 3 2 1 4 P 0 ... | stack_v2_sparse_classes_36k_train_026440 | 9,375 | permissive | [
{
"docstring": "Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel length to microns. These chain-code lengths are based on the Freeman 8-direction chain codes: 3 2 1 4 P 0 5 6 7 Given a sequence of (x,y)-coordinates, we could obtain a s... | 5 | null | Implement the Python class `WormParserHelpers` described below.
Class description:
Implement the WormParserHelpers class.
Method signatures and docstrings:
- def chain_code_lengths(skeleton): Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel ... | Implement the Python class `WormParserHelpers` described below.
Class description:
Implement the WormParserHelpers class.
Method signatures and docstrings:
- def chain_code_lengths(skeleton): Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel ... | 4e3dc2da29ed56292da4a533437604defed0705b | <|skeleton|>
class WormParserHelpers:
def chain_code_lengths(skeleton):
"""Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel length to microns. These chain-code lengths are based on the Freeman 8-direction chain codes: 3 2 1 4 P 0 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WormParserHelpers:
def chain_code_lengths(skeleton):
"""Computes the chain-code lengths of the skeleton for each frame. Computed from the skeleton by converting the chain-code pixel length to microns. These chain-code lengths are based on the Freeman 8-direction chain codes: 3 2 1 4 P 0 5 6 7 Given a ... | the_stack_v2_python_sparse | tierpsy/features/open_worm_analysis_toolbox/prefeatures/pre_features_helpers.py | Tierpsy/tierpsy-tracker | train | 18 | |
5a96ba46fd930eec4b41b6c7d926948309d8713b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TermsAndConditions()",
"from .entity import Entity\nfrom .terms_and_conditions_acceptance_status import TermsAndConditionsAcceptanceStatus\nfrom .terms_and_conditions_assignment import TermsAndConditionsAssignment\nfrom .entity import ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TermsAndConditions()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .terms_and_conditions_acceptance_status import TermsAndConditionsAcceptanceStatus
from .terms... | A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits where an administrator has required re-acceptance. They enable administrators to communi... | TermsAndConditions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TermsAndConditions:
"""A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits where an administrator has required re-acc... | stack_v2_sparse_classes_36k_train_026441 | 5,989 | 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: TermsAndConditions",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `TermsAndConditions` described below.
Class description:
A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits whe... | Implement the Python class `TermsAndConditions` described below.
Class description:
A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits whe... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TermsAndConditions:
"""A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits where an administrator has required re-acc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TermsAndConditions:
"""A termsAndConditions entity represents the metadata and contents of a given Terms and Conditions (T&C) policy. T&C policies’ contents are presented to users upon their first attempt to enroll into Intune and subsequently upon edits where an administrator has required re-acceptance. They... | the_stack_v2_python_sparse | msgraph/generated/models/terms_and_conditions.py | microsoftgraph/msgraph-sdk-python | train | 135 |
6daae0224b7e97ce995a68440691d77ed888b217 | [
"self.number = number\nself.holder_name = holder_name\nself.exp_month = exp_month\nself.exp_year = exp_year\nself.cvv = cvv\nself.brand = brand\nself.label = label",
"if dictionary is None:\n return None\nnumber = dictionary.get('number')\nholder_name = dictionary.get('holder_name')\nexp_month = dictionary.get... | <|body_start_0|>
self.number = number
self.holder_name = holder_name
self.exp_month = exp_month
self.exp_year = exp_year
self.cvv = cvv
self.brand = brand
self.label = label
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informed with 2 or 4 digits cvv (string): The card's secu... | CreateCardTokenRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informe... | stack_v2_sparse_classes_36k_train_026442 | 2,734 | permissive | [
{
"docstring": "Constructor for the CreateCardTokenRequest class",
"name": "__init__",
"signature": "def __init__(self, number=None, holder_name=None, exp_month=None, exp_year=None, cvv=None, brand=None, label=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | null | Implement the Python class `CreateCardTokenRequest` described below.
Class description:
Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): T... | Implement the Python class `CreateCardTokenRequest` described below.
Class description:
Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): T... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informed with 2 or 4... | the_stack_v2_python_sparse | mundiapi/models/create_card_token_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
b1f0347558fc6f9fe0f88dff164d07cce413765d | [
"token = User.objects.make_random_password(64)\nrp = PasswordRequest.objects.create(user=user, token=token)\nuser.add_to_log('Password reset request')\nurl = absolute_url(request, 'accounts:set_password', args=(user.alias, token))\ncontext = {'user': user, 'token': token, 'url': url}\nmsg = EmailMessage('Password r... | <|body_start_0|>
token = User.objects.make_random_password(64)
rp = PasswordRequest.objects.create(user=user, token=token)
user.add_to_log('Password reset request')
url = absolute_url(request, 'accounts:set_password', args=(user.alias, token))
context = {'user': user, 'token': to... | Reset password view. | ResetPasswordView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordView:
"""Reset password view."""
def create_token(cls, request, user):
"""Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse"""
<|body_0|>
def form_valid(self, form):
"""Validate form and processing of ... | stack_v2_sparse_classes_36k_train_026443 | 23,477 | permissive | [
{
"docstring": "Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse",
"name": "create_token",
"signature": "def create_token(cls, request, user)"
},
{
"docstring": "Validate form and processing of it. :param form: Bound form :return: HttpResponse",
... | 2 | stack_v2_sparse_classes_30k_train_000695 | Implement the Python class `ResetPasswordView` described below.
Class description:
Reset password view.
Method signatures and docstrings:
- def create_token(cls, request, user): Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse
- def form_valid(self, form): Validate fo... | Implement the Python class `ResetPasswordView` described below.
Class description:
Reset password view.
Method signatures and docstrings:
- def create_token(cls, request, user): Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse
- def form_valid(self, form): Validate fo... | 8f4a3d3d07a1f80b7225a415cea30dfc65a38bf1 | <|skeleton|>
class ResetPasswordView:
"""Reset password view."""
def create_token(cls, request, user):
"""Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse"""
<|body_0|>
def form_valid(self, form):
"""Validate form and processing of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResetPasswordView:
"""Reset password view."""
def create_token(cls, request, user):
"""Create password reset request. :param request: HttpRequest :param user: User :return: HttpResponse"""
token = User.objects.make_random_password(64)
rp = PasswordRequest.objects.create(user=user,... | the_stack_v2_python_sparse | accounts/views.py | nocnokneo/ydns | train | 0 |
d4a33d100c1a3b15ace4f1c91d47961e7d167e4b | [
"argument_group.add_argument('--status_view', '--status-view', dest='status_view_mode', choices=cls._STATUS_VIEW_TYPES, action='store', metavar='TYPE', default=status_view.StatusView.MODE_WINDOW, help='The processing status view mode: \"file\", \"linear\", \"none\" or \"window\".')\nargument_group.add_argument('--s... | <|body_start_0|>
argument_group.add_argument('--status_view', '--status-view', dest='status_view_mode', choices=cls._STATUS_VIEW_TYPES, action='store', metavar='TYPE', default=status_view.StatusView.MODE_WINDOW, help='The processing status view mode: "file", "linear", "none" or "window".')
argument_grou... | Status view CLI arguments helper. | StatusViewArgumentsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper ... | stack_v2_sparse_classes_36k_train_026444 | 3,122 | permissive | [
{
"docstring": "Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.",
"name": "AddArgum... | 2 | stack_v2_sparse_classes_30k_train_007622 | Implement the Python class `StatusViewArgumentsHelper` described below.
Class description:
Status view CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object a... | Implement the Python class `StatusViewArgumentsHelper` described below.
Class description:
Status view CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object a... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Arg... | the_stack_v2_python_sparse | plaso/cli/helpers/status_view.py | log2timeline/plaso | train | 1,506 |
e5e211931340ee9eae72b55740632233aef06255 | [
"def traverse(root, l):\n if not root:\n return\n l.append(root)\n traverse(root.left, l)\n traverse(root.right, l)\nl = []\ntraverse(root, l)\ntmp = root\ni = 1\nwhile i < len(l):\n tmp.left = None\n tmp.right = l[i]\n i += 1\n tmp = tmp.right",
"if root:\n previous, current = (... | <|body_start_0|>
def traverse(root, l):
if not root:
return
l.append(root)
traverse(root.left, l)
traverse(root.right, l)
l = []
traverse(root, l)
tmp = root
i = 1
while i < len(l):
tmp.left = Non... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten0(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k_train_026445 | 1,308 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten0",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten0(self, root): :type root: TreeNode :rtype: void Do ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten0(self, root): :type root: TreeNode :rtype: void Do ... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten0(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
def traverse(root, l):
if not root:
return
l.append(root)
traverse(root.left, l)
traverse(root.right,... | the_stack_v2_python_sparse | PythonCode/src/0114_Flatten_Binary_Tree_to_Linked_List.py | oneyuan/CodeforFun | train | 0 | |
f8a21da8ead78a9443897b3f4079ab842e9afc21 | [
"for p in ADDITIONAL_NET_PARAMS.keys():\n if p not in net_params.additional_params:\n raise KeyError('Network parameter \"{}\" not supplied'.format(p))\nself.length = net_params.additional_params['length']\nself.lanes = net_params.additional_params['lanes']\nsuper().__init__(name, generator_class, vehicle... | <|body_start_0|>
for p in ADDITIONAL_NET_PARAMS.keys():
if p not in net_params.additional_params:
raise KeyError('Network parameter "{}" not supplied'.format(p))
self.length = net_params.additional_params['length']
self.lanes = net_params.additional_params['lanes']
... | LoopScenario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLights()):
"""Initializes a loop scenario. Requires from net_params: - length: length of the circle - lanes: number of lanes in the circle - speed_limit: ma... | stack_v2_sparse_classes_36k_train_026446 | 1,674 | permissive | [
{
"docstring": "Initializes a loop scenario. Requires from net_params: - length: length of the circle - lanes: number of lanes in the circle - speed_limit: max speed limit of the circle - resolution: number of nodes resolution See Scenario.py for description of params.",
"name": "__init__",
"signature":... | 2 | null | Implement the Python class `LoopScenario` described below.
Class description:
Implement the LoopScenario class.
Method signatures and docstrings:
- def __init__(self, name, generator_class, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLights()): Initializes a loop scenario. Requires fro... | Implement the Python class `LoopScenario` described below.
Class description:
Implement the LoopScenario class.
Method signatures and docstrings:
- def __init__(self, name, generator_class, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLights()): Initializes a loop scenario. Requires fro... | fb3f0d54e06b9e940b7a2ba8772395ee7ea0f17b | <|skeleton|>
class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLights()):
"""Initializes a loop scenario. Requires from net_params: - length: length of the circle - lanes: number of lanes in the circle - speed_limit: ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLights()):
"""Initializes a loop scenario. Requires from net_params: - length: length of the circle - lanes: number of lanes in the circle - speed_limit: max speed limit ... | the_stack_v2_python_sparse | flow/scenarios/loop/loop_scenario.py | lijunsun/flow | train | 0 | |
e88db4589a9f0746f6feef2ebb164eba6e4790e2 | [
"if not nums:\n return 0\nans = float('INF')\nrecord = [nums[0]]\nfor i in range(1, len(nums)):\n record.append(record[i - 1] + nums[i])\nfor i in range(len(nums)):\n for j in range(i, len(nums)):\n sm = record[j] - record[i] + nums[i]\n if sm >= s:\n ans = min(ans, j - i + 1)\nret... | <|body_start_0|>
if not nums:
return 0
ans = float('INF')
record = [nums[0]]
for i in range(1, len(nums)):
record.append(record[i - 1] + nums[i])
for i in range(len(nums)):
for j in range(i, len(nums)):
sm = record[j] - record[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen_bruteforce(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_binarysearch(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
def minSubArrayLen_one... | stack_v2_sparse_classes_36k_train_026447 | 2,020 | no_license | [
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_bruteforce",
"signature": "def minSubArrayLen_bruteforce(self, s, nums)"
},
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_binarysearch",
"signature": "def m... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_bruteforce(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen_binarysearch(self, s, nums): :type s: int :type nums: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_bruteforce(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen_binarysearch(self, s, nums): :type s: int :type nums: List[int] ... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def minSubArrayLen_bruteforce(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_binarysearch(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
def minSubArrayLen_one... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen_bruteforce(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
if not nums:
return 0
ans = float('INF')
record = [nums[0]]
for i in range(1, len(nums)):
record.append(record[i - 1] + nums[i])
... | the_stack_v2_python_sparse | medium/slidewindow/test_209_Minimum_Size_Subarray_Sum.py | wuxu1019/leetcode_sophia | train | 1 | |
b7a377f365890f762b03320621f58954df94009a | [
"def build(s, id, l, r, nums):\n if l == r:\n s[id] = nums[l]\n return\n mid = (l + r) // 2\n build(s, id * 2 + 1, l, mid, nums)\n build(s, id * 2 + 2, mid + 1, r, nums)\n s[id] = s[id * 2 + 1] + s[id * 2 + 2]\nself.nums = nums\nif not nums:\n return\nh = math.ceil(math.log(len(nums)... | <|body_start_0|>
def build(s, id, l, r, nums):
if l == r:
s[id] = nums[l]
return
mid = (l + r) // 2
build(s, id * 2 + 1, l, mid, nums)
build(s, id * 2 + 2, mid + 1, r, nums)
s[id] = s[id * 2 + 1] + s[id * 2 + 2]
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def build(s, id, l, r, nums):
if l == r:
... | stack_v2_sparse_classes_36k_train_026448 | 1,558 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 690adf05774a1c500d6c9160223dab7bcc38ccc1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
def build(s, id, l, r, nums):
if l == r:
s[id] = nums[l]
return
mid = (l + r) // 2
build(s, id * 2 + 1, l, mid, nums)
build(s, id * 2 + 2, mid + 1, r,... | the_stack_v2_python_sparse | 303. Range Sum Query - Immutable.py | supersj/LeetCode | train | 2 | |
73882da4cba390e7a3e64a9e2c5552b5fc35e03b | [
"if 'user_id' not in in_data:\n in_data['user_id'] = 'us-' + str(uuid4())\nreturn in_data",
"if value:\n return pwd_context.encrypt(value)\nreturn None",
"if value:\n return int(value * 100)\nreturn None",
"if obj.budget:\n return obj.budget / 100.0\nreturn None"
] | <|body_start_0|>
if 'user_id' not in in_data:
in_data['user_id'] = 'us-' + str(uuid4())
return in_data
<|end_body_0|>
<|body_start_1|>
if value:
return pwd_context.encrypt(value)
return None
<|end_body_1|>
<|body_start_2|>
if value:
return in... | Schema to store details about a user. | UserSchema | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSchema:
"""Schema to store details about a user."""
def get_id(self, in_data: dict, **kwargs: Any) -> dict:
"""Add generated user_id."""
<|body_0|>
def get_password_hash(self, value: str) -> Optional[str]:
"""Convert password to password_hash."""
<|bo... | stack_v2_sparse_classes_36k_train_026449 | 4,600 | permissive | [
{
"docstring": "Add generated user_id.",
"name": "get_id",
"signature": "def get_id(self, in_data: dict, **kwargs: Any) -> dict"
},
{
"docstring": "Convert password to password_hash.",
"name": "get_password_hash",
"signature": "def get_password_hash(self, value: str) -> Optional[str]"
... | 4 | stack_v2_sparse_classes_30k_train_007616 | Implement the Python class `UserSchema` described below.
Class description:
Schema to store details about a user.
Method signatures and docstrings:
- def get_id(self, in_data: dict, **kwargs: Any) -> dict: Add generated user_id.
- def get_password_hash(self, value: str) -> Optional[str]: Convert password to password_... | Implement the Python class `UserSchema` described below.
Class description:
Schema to store details about a user.
Method signatures and docstrings:
- def get_id(self, in_data: dict, **kwargs: Any) -> dict: Add generated user_id.
- def get_password_hash(self, value: str) -> Optional[str]: Convert password to password_... | 822dbd3ccee25180cc48efd2f891504b6b5edc14 | <|skeleton|>
class UserSchema:
"""Schema to store details about a user."""
def get_id(self, in_data: dict, **kwargs: Any) -> dict:
"""Add generated user_id."""
<|body_0|>
def get_password_hash(self, value: str) -> Optional[str]:
"""Convert password to password_hash."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSchema:
"""Schema to store details about a user."""
def get_id(self, in_data: dict, **kwargs: Any) -> dict:
"""Add generated user_id."""
if 'user_id' not in in_data:
in_data['user_id'] = 'us-' + str(uuid4())
return in_data
def get_password_hash(self, value: st... | the_stack_v2_python_sparse | services/users/users/schema.py | Open-EO/openeo-eodc-driver | train | 3 |
a9ecba124d32a502be83060c6b7be9df2fb513d7 | [
"streams = {s.stream.name for s in configured_catalog.streams}\nwith establish_connection(config) as connection:\n writer = create_firebolt_wirter(connection, config, logger)\n for configured_stream in configured_catalog.streams:\n if configured_stream.destination_sync_mode == DestinationSyncMode.overw... | <|body_start_0|>
streams = {s.stream.name for s in configured_catalog.streams}
with establish_connection(config) as connection:
writer = create_firebolt_wirter(connection, config, logger)
for configured_stream in configured_catalog.streams:
if configured_stream.de... | DestinationFirebolt | [
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestinationFirebolt:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method re... | stack_v2_sparse_classes_36k_train_026450 | 6,193 | permissive | [
{
"docstring": "Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an iterable (typically a generator of AirbyteMessages via yield) containing state messages received in the input message stream. Outputting a state message means that every AirbyteRecord... | 2 | null | Implement the Python class `DestinationFirebolt` described below.
Class description:
Implement the DestinationFirebolt class.
Method signatures and docstrings:
- def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessag... | Implement the Python class `DestinationFirebolt` described below.
Class description:
Implement the DestinationFirebolt class.
Method signatures and docstrings:
- def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessag... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DestinationFirebolt:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DestinationFirebolt:
def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]:
"""Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an itera... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/destination-firebolt/destination_firebolt/destination.py | alldatacenter/alldata | train | 774 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nproject_type_list = adm.get_all_project_types()\nreturn project_type_list",
"adm = ProjectAdministration()\nproposal = ProjectType.from_dict(api.payload)\nif proposal is not None:\n 'Wir verwenden Name und project_type_id des Proposals für die Erzeugung eines ProjectType-Objekte... | <|body_start_0|>
adm = ProjectAdministration()
project_type_list = adm.get_all_project_types()
return project_type_list
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
proposal = ProjectType.from_dict(api.payload)
if proposal is not None:
'Wir v... | ProjectTypeListOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = ProjectAdministration()
project_ty... | stack_v2_sparse_classes_36k_train_026451 | 44,493 | no_license | [
{
"docstring": "Auslesen aller ProjectType-Objekte",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Anlegen eines neuen ProjectType-Objekts",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020990 | Implement the Python class `ProjectTypeListOperations` described below.
Class description:
Implement the ProjectTypeListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller ProjectType-Objekte
- def post(self): Anlegen eines neuen ProjectType-Objekts | Implement the Python class `ProjectTypeListOperations` described below.
Class description:
Implement the ProjectTypeListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller ProjectType-Objekte
- def post(self): Anlegen eines neuen ProjectType-Objekts
<|skeleton|>
class ProjectTypeListO... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectTypeListOperations:
def get(self):
"""Auslesen aller ProjectType-Objekte"""
adm = ProjectAdministration()
project_type_list = adm.get_all_project_types()
return project_type_list
def post(self):
"""Anlegen eines neuen ProjectType-Objekts"""
adm = Pro... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
24ea6155aaa1e01b7da02bd80e23acf7b1e20c10 | [
"obj.save()\ngenerate_static_sku_detail_html(obj.sku.id)\nsku = obj.sku\nif not sku.default_image_url:\n sku.default_image_url = obj.image.url\n sku.save()",
"sku_id = obj.sku.id\nobj.delete()\ngenerate_static_sku_detail_html(sku_id)"
] | <|body_start_0|>
obj.save()
generate_static_sku_detail_html(obj.sku.id)
sku = obj.sku
if not sku.default_image_url:
sku.default_image_url = obj.image.url
sku.save()
<|end_body_0|>
<|body_start_1|>
sku_id = obj.sku.id
obj.delete()
generate_... | SKUImageAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SKUImageAdmin:
def save_model(self, request, obj, form, change):
"""新增商品图片"""
<|body_0|>
def delete_model(self, request, obj):
"""删除商品图片"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj.save()
generate_static_sku_detail_html(obj.sku.id)
... | stack_v2_sparse_classes_36k_train_026452 | 3,090 | no_license | [
{
"docstring": "新增商品图片",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "删除商品图片",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | null | Implement the Python class `SKUImageAdmin` described below.
Class description:
Implement the SKUImageAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增商品图片
- def delete_model(self, request, obj): 删除商品图片 | Implement the Python class `SKUImageAdmin` described below.
Class description:
Implement the SKUImageAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 新增商品图片
- def delete_model(self, request, obj): 删除商品图片
<|skeleton|>
class SKUImageAdmin:
def save_model(self, req... | 12b52f21a4ec20b4853870468c28d2385dc185a8 | <|skeleton|>
class SKUImageAdmin:
def save_model(self, request, obj, form, change):
"""新增商品图片"""
<|body_0|>
def delete_model(self, request, obj):
"""删除商品图片"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SKUImageAdmin:
def save_model(self, request, obj, form, change):
"""新增商品图片"""
obj.save()
generate_static_sku_detail_html(obj.sku.id)
sku = obj.sku
if not sku.default_image_url:
sku.default_image_url = obj.image.url
sku.save()
def delete_mode... | the_stack_v2_python_sparse | django_prj/meiduo/meiduo_mall/meiduo_mall/apps/goods/admin.py | 123wuyu/demo_prj | train | 1 | |
c2c3be13d84f01a2ee31af5ccf40702c5f71015e | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')\nself.source_language = args.get('source_language') or self.language\nself.source_selector = args.get('source_selector')\nif self.source_selector is None:\n self.source_selector = self.select... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
self.source_language = args.get('source_language') or self.language
self.source_selector = args.get('source_selector')
if self.source_se... | This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target) source_selector the selector of the SOURCE zone (defaults to same as targ... | CopyTree | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyTree:
"""This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target) source_selector the selector of the S... | stack_v2_sparse_classes_36k_train_026453 | 2,949 | permissive | [
{
"docstring": "Constructor, checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "For each bundle, copy the tree on the given layer in the given zone to another zone.",
"name": "process_bundle",
"signature": "def process_... | 3 | null | Implement the Python class `CopyTree` described below.
Class description:
This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target... | Implement the Python class `CopyTree` described below.
Class description:
This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class CopyTree:
"""This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target) source_selector the selector of the S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopyTree:
"""This block is able to copy a tree on the same layer from a different zone. Arguments: language: the language of the TARGET zone selector: the selector of the TARGET zone source_language the language of the SOURCE zone (defaults to same as target) source_selector the selector of the SOURCE zone (d... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/util/copytree.py | oplatek/alex | train | 0 |
5ca46cb606ec89b9b9504c52ac71fa93a87daaec | [
"obj = super().get_object()\nlogger.debug('ReductionScriptUpdateMixin :: get_object = {}'.format(obj))\nif self.request.method == 'GET':\n script_builder = self._get_script_builder()\n if obj.script is None or obj.script == '':\n logger.debug('Generate the script for %s.', obj)\n try:\n ... | <|body_start_0|>
obj = super().get_object()
logger.debug('ReductionScriptUpdateMixin :: get_object = {}'.format(obj))
if self.request.method == 'GET':
script_builder = self._get_script_builder()
if obj.script is None or obj.script == '':
logger.debug('Gene... | Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster | ReductionScriptUpdateMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReductionScriptUpdateMixin:
"""Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster"""
def get_object(self, queryset=None):
"""Always called has the script form is an edit form We get the object alr... | stack_v2_sparse_classes_36k_train_026454 | 13,068 | no_license | [
{
"docstring": "Always called has the script form is an edit form We get the object already in the DB. This is called by get and post: * on GET: Generate the script (if the script field in the DB is empty!) and add it to object shown on the form It does the same for script path.",
"name": "get_object",
... | 5 | stack_v2_sparse_classes_30k_train_014709 | Implement the Python class `ReductionScriptUpdateMixin` described below.
Class description:
Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster
Method signatures and docstrings:
- def get_object(self, queryset=None): Always called ... | Implement the Python class `ReductionScriptUpdateMixin` described below.
Class description:
Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster
Method signatures and docstrings:
- def get_object(self, queryset=None): Always called ... | 507ff81617abf583edd4ef4858985daefc0afcbe | <|skeleton|>
class ReductionScriptUpdateMixin:
"""Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster"""
def get_object(self, queryset=None):
"""Always called has the script form is an edit form We get the object alr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReductionScriptUpdateMixin:
"""Edit a Reduction Script on GET: Generate the script and show it to the user on POST: - Save it - Save it and submit the job to the cluster"""
def get_object(self, queryset=None):
"""Always called has the script form is an edit form We get the object already in the D... | the_stack_v2_python_sparse | src/server/apps/reduction/views/mixins.py | bidochon/WebReduction | train | 0 |
b725a94bdf1d0590943a7a3602d82cd473616d5c | [
"def twoSum(start, target):\n l = start\n r = length - 1\n while l < r:\n if nums[l] + nums[r] == target:\n vl, vr = (nums[l], nums[r])\n ans.append([-target, vl, vr])\n while l < r and nums[l] == vl:\n l += 1\n while l < r and nums[r] == vr... | <|body_start_0|>
def twoSum(start, target):
l = start
r = length - 1
while l < r:
if nums[l] + nums[r] == target:
vl, vr = (nums[l], nums[r])
ans.append([-target, vl, vr])
while l < r and nums[l] == v... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def threeSum(self, nums):
""":type nums: List[int] :rtyp... | stack_v2_sparse_classes_36k_train_026455 | 2,715 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum1",
"signature": "def threeSum1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
},
{
"docstring": ":type ... | 3 | stack_v2_sparse_classes_30k_train_019170 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum1(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum1(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :t... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def threeSum1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def threeSum(self, nums):
""":type nums: List[int] :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum1(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
def twoSum(start, target):
l = start
r = length - 1
while l < r:
if nums[l] + nums[r] == target:
vl, vr = (nums[l], nums[r])
... | the_stack_v2_python_sparse | 15_3sum/15.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
b300b34faff5c2b1bd2577a76e083bb9bcde0776 | [
"if p.val > root.val < q.val:\n return self.lowestCommonAncestor(root.right, p, q)\nelif p.val < root.val > q.val:\n return self.lowestCommonAncestor(root.left, p, q)\nelse:\n return root",
"if root is None or root == p or root == q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nri... | <|body_start_0|>
if p.val > root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
elif p.val < root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root
<|end_body_0|>
<|body_start_1|>
if root is None or root... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉的那个节点就是他们的最近公共祖先 执行用时 :80 ms, 在所有 Python3 提交中击败了100.00% 的用户 内存消耗 :18 MB, 在所有 Python3 提交中击败了5.48%的... | stack_v2_sparse_classes_36k_train_026456 | 2,069 | no_license | [
{
"docstring": "20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉的那个节点就是他们的最近公共祖先 执行用时 :80 ms, 在所有 Python3 提交中击败了100.00% 的用户 内存消耗 :18 MB, 在所有 Python3 提交中击败了5.48%的用户",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'Tre... | 2 | stack_v2_sparse_classes_30k_train_019940 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉的那个节点就是他们的最近公共祖先 执行用时 :80 ms, 在所有 Python3 提交中击败了100.00% 的用户 内存消耗 :18 MB, 在所有 Python3 提交中击败了5.48%的... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""20190921 模模糊糊地有这样的概念, 最近公共祖先的值应该是介于 p 和 q 之间的, 因为分叉了, 看了覃超的算法课之后, 发现他的解法很清晰, 就是第一次分叉的那个节点就是他们的最近公共祖先 执行用时 :80 ms, 在所有 Python3 提交中击败了100.00% 的用户 内存消耗 :18 MB, 在所有 Python3 提交中击败了5.48%的用户"""
... | the_stack_v2_python_sparse | leetcode/235.lowest-common-ancestor-of-a-binary-search-tree.py | iamkissg/leetcode | train | 0 | |
d6f86e784f52338a15b3247df1ea7444ac07595f | [
"self.card = card\nself.fromZoneType = fromZoneType\nself.toZoneType = toZoneType",
"fromZone = context.loadZone(self.fromZoneType)\ntoZone = context.loadZone(self.toZoneType)\ncards = [self.card]\nif self.card is None:\n cards = list(fromZone)\nfor card in cards:\n if card in fromZone:\n fromZone.re... | <|body_start_0|>
self.card = card
self.fromZoneType = fromZoneType
self.toZoneType = toZoneType
<|end_body_0|>
<|body_start_1|>
fromZone = context.loadZone(self.fromZoneType)
toZone = context.loadZone(self.toZoneType)
cards = [self.card]
if self.card is None:
... | Represents an effect to Put a Card on the Bottom | PutOnBottom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_026457 | 750 | no_license | [
{
"docstring": "Initialize the Effect",
"name": "__init__",
"signature": "def __init__(self, fromZoneType, toZoneType, card=None)"
},
{
"docstring": "Perform the Game Effect",
"name": "perform",
"signature": "def perform(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000578 | Implement the Python class `PutOnBottom` described below.
Class description:
Represents an effect to Put a Card on the Bottom
Method signatures and docstrings:
- def __init__(self, fromZoneType, toZoneType, card=None): Initialize the Effect
- def perform(self, context): Perform the Game Effect | Implement the Python class `PutOnBottom` described below.
Class description:
Represents an effect to Put a Card on the Bottom
Method signatures and docstrings:
- def __init__(self, fromZoneType, toZoneType, card=None): Initialize the Effect
- def perform(self, context): Perform the Game Effect
<|skeleton|>
class Put... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
<|body_0|>
def perform(self, context):
"""Perform the Game Effect"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PutOnBottom:
"""Represents an effect to Put a Card on the Bottom"""
def __init__(self, fromZoneType, toZoneType, card=None):
"""Initialize the Effect"""
self.card = card
self.fromZoneType = fromZoneType
self.toZoneType = toZoneType
def perform(self, context):
... | the_stack_v2_python_sparse | src/Game/Effects/put_on_bottom.py | dfwarden/DeckBuilding | train | 0 |
f5803cee62c416c20685a5efaea72ecd7946eb16 | [
"self.features_generators = features_generators\nself.is_adding_hs = is_adding_hs\nsuper().__init__(use_original_atom_ranks)",
"src: List[int] = []\ndest: List[int] = []\nfor bond in datapoint.GetBonds():\n start, end = (bond.GetBeginAtomIdx(), bond.GetEndAtomIdx())\n src += [start, end]\n dest += [end, ... | <|body_start_0|>
self.features_generators = features_generators
self.is_adding_hs = is_adding_hs
super().__init__(use_original_atom_ranks)
<|end_body_0|>
<|body_start_1|>
src: List[int] = []
dest: List[int] = []
for bond in datapoint.GetBonds():
start, end = ... | This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <https://arxiv.org/pdf/1904.01561.pdf>`_. The default node representation are const... | DMPNNFeaturizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMPNNFeaturizer:
"""This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <https://arxiv.org/pdf/1904.01561.pdf>`_... | stack_v2_sparse_classes_36k_train_026458 | 19,123 | permissive | [
{
"docstring": "Parameters ---------- features_generator: List[str], default None List of global feature generators to be used. is_adding_hs: bool, default False Whether to add Hs or not. use_original_atom_ranks: bool, default False Whether to use original atom mapping or canonical atom mapping",
"name": "_... | 4 | null | Implement the Python class `DMPNNFeaturizer` described below.
Class description:
This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <... | Implement the Python class `DMPNNFeaturizer` described below.
Class description:
This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class DMPNNFeaturizer:
"""This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <https://arxiv.org/pdf/1904.01561.pdf>`_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DMPNNFeaturizer:
"""This class is a featurizer for Directed Message Passing Neural Network (D-MPNN) implementation The default node(atom) and edge(bond) representations are based on `Analyzing Learned Molecular Representations for Property Prediction paper <https://arxiv.org/pdf/1904.01561.pdf>`_. The default... | the_stack_v2_python_sparse | deepchem/feat/molecule_featurizers/dmpnn_featurizer.py | deepchem/deepchem | train | 4,876 |
aab36332aa1007c936aa021f6a1c8da110cd952c | [
"if constraints == None:\n constraints = []\nChain.__init__(self, constraints)",
"searchFor = True\nfor const in self._constraints:\n if const.is_valid(value):\n if searchFor:\n searchFor = False\n else:\n return False\nreturn searchFor == False"
] | <|body_start_0|>
if constraints == None:
constraints = []
Chain.__init__(self, constraints)
<|end_body_0|>
<|body_start_1|>
searchFor = True
for const in self._constraints:
if const.is_valid(value):
if searchFor:
searchFor = Fa... | Rappresenta una And Chain di condizioni sugli attributi | XorChain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XorChain:
"""Rappresenta una And Chain di condizioni sugli attributi"""
def __init__(self, constraints=None):
"""Constructor"""
<|body_0|>
def is_valid(self, value):
"""Ammesso esattamente 1 valore True fra le condizioni della Chain"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_026459 | 800 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, constraints=None)"
},
{
"docstring": "Ammesso esattamente 1 valore True fra le condizioni della Chain",
"name": "is_valid",
"signature": "def is_valid(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002212 | Implement the Python class `XorChain` described below.
Class description:
Rappresenta una And Chain di condizioni sugli attributi
Method signatures and docstrings:
- def __init__(self, constraints=None): Constructor
- def is_valid(self, value): Ammesso esattamente 1 valore True fra le condizioni della Chain | Implement the Python class `XorChain` described below.
Class description:
Rappresenta una And Chain di condizioni sugli attributi
Method signatures and docstrings:
- def __init__(self, constraints=None): Constructor
- def is_valid(self, value): Ammesso esattamente 1 valore True fra le condizioni della Chain
<|skelet... | 468a9ba295ab658670472a0156772f428d7f3fe4 | <|skeleton|>
class XorChain:
"""Rappresenta una And Chain di condizioni sugli attributi"""
def __init__(self, constraints=None):
"""Constructor"""
<|body_0|>
def is_valid(self, value):
"""Ammesso esattamente 1 valore True fra le condizioni della Chain"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XorChain:
"""Rappresenta una And Chain di condizioni sugli attributi"""
def __init__(self, constraints=None):
"""Constructor"""
if constraints == None:
constraints = []
Chain.__init__(self, constraints)
def is_valid(self, value):
"""Ammesso esattamente 1 v... | the_stack_v2_python_sparse | src/icse/ps/constraints/XorChain.py | ximarx/icse-ps | train | 0 |
2acd034ef3caa4a68ef922c687606857b7431922 | [
"ageAnnees = situation.AgeEnAnnees()\ntraitsPerso = situation.GetDicoTraits()\nreturn self.DeterminerPortraits(situation, ageAnnees, 'Saint Louis', traitsPerso, masculin)",
"portraits = []\nportraitCourant = situation.GetValCarac(portrait.Portrait.C_PORTRAIT)\nif nom == heros.Heros.C_NOM:\n if ageAnnees >= 30 ... | <|body_start_0|>
ageAnnees = situation.AgeEnAnnees()
traitsPerso = situation.GetDicoTraits()
return self.DeterminerPortraits(situation, ageAnnees, 'Saint Louis', traitsPerso, masculin)
<|end_body_0|>
<|body_start_1|>
portraits = []
portraitCourant = situation.GetValCarac(portrai... | PortraitSpe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortraitSpe:
def DeterminerPortraitPersoPrincipal(self, situation, masculin):
"""retourne l'adresse du portrait à afficher pour le perso courant"""
<|body_0|>
def DeterminerPortraits(self, situation, ageAnnees, nom, valeursTraits, masculin):
"""retourne l'adresse du ... | stack_v2_sparse_classes_36k_train_026460 | 1,861 | no_license | [
{
"docstring": "retourne l'adresse du portrait à afficher pour le perso courant",
"name": "DeterminerPortraitPersoPrincipal",
"signature": "def DeterminerPortraitPersoPrincipal(self, situation, masculin)"
},
{
"docstring": "retourne l'adresse du portrait à afficher pour le perso courant valeursT... | 2 | stack_v2_sparse_classes_30k_train_015798 | Implement the Python class `PortraitSpe` described below.
Class description:
Implement the PortraitSpe class.
Method signatures and docstrings:
- def DeterminerPortraitPersoPrincipal(self, situation, masculin): retourne l'adresse du portrait à afficher pour le perso courant
- def DeterminerPortraits(self, situation, ... | Implement the Python class `PortraitSpe` described below.
Class description:
Implement the PortraitSpe class.
Method signatures and docstrings:
- def DeterminerPortraitPersoPrincipal(self, situation, masculin): retourne l'adresse du portrait à afficher pour le perso courant
- def DeterminerPortraits(self, situation, ... | ece5e7b6aeac787bd3d5dee2c245496a5a4f4c50 | <|skeleton|>
class PortraitSpe:
def DeterminerPortraitPersoPrincipal(self, situation, masculin):
"""retourne l'adresse du portrait à afficher pour le perso courant"""
<|body_0|>
def DeterminerPortraits(self, situation, ageAnnees, nom, valeursTraits, masculin):
"""retourne l'adresse du ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PortraitSpe:
def DeterminerPortraitPersoPrincipal(self, situation, masculin):
"""retourne l'adresse du portrait à afficher pour le perso courant"""
ageAnnees = situation.AgeEnAnnees()
traitsPerso = situation.GetDicoTraits()
return self.DeterminerPortraits(situation, ageAnnees, ... | the_stack_v2_python_sparse | game/spe/humanite/portrait_saint_louis.py | gabriellevy/destinSaintLouis | train | 2 | |
3b9c0f7ab915320cbe66dd2e0206240d2305fee8 | [
"n1, n2, n3 = (len(s1), len(s2), len(s3))\nif n1 + n2 != n3:\n return False\n\ndef dfs(i, j, k):\n if i == n1:\n return s2[j:] == s3[k:]\n elif j == n2:\n return s1[i:] == s3[k:]\n if memo[i][j] != None:\n return memo[i][j]\n memo[i][j] = s1[i] == s3[k] and dfs(i + 1, j, k + 1) o... | <|body_start_0|>
n1, n2, n3 = (len(s1), len(s2), len(s3))
if n1 + n2 != n3:
return False
def dfs(i, j, k):
if i == n1:
return s2[j:] == s3[k:]
elif j == n2:
return s1[i:] == s3[k:]
if memo[i][j] != None:
... | [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""[97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)"""
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""思路:动态规划,自顶向下"""
<|body_0|>
def isInterleave2(self, s1: str, s2: str, s3: str) -> bool:
"""思路:自底向上"""
<|body_1|... | stack_v2_sparse_classes_36k_train_026461 | 2,520 | no_license | [
{
"docstring": "思路:动态规划,自顶向下",
"name": "isInterleave",
"signature": "def isInterleave(self, s1: str, s2: str, s3: str) -> bool"
},
{
"docstring": "思路:自底向上",
"name": "isInterleave2",
"signature": "def isInterleave2(self, s1: str, s2: str, s3: str) -> bool"
},
{
"docstring": "思路:dp... | 3 | null | Implement the Python class `Solution` described below.
Class description:
[97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)
Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 思路:动态规划,自顶向下
- def isInterleave2(self, s1: str, s2: str, s3: str) -> bool: 思路:自底向上... | Implement the Python class `Solution` described below.
Class description:
[97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)
Method signatures and docstrings:
- def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 思路:动态规划,自顶向下
- def isInterleave2(self, s1: str, s2: str, s3: str) -> bool: 思路:自底向上... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class Solution:
"""[97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)"""
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""思路:动态规划,自顶向下"""
<|body_0|>
def isInterleave2(self, s1: str, s2: str, s3: str) -> bool:
"""思路:自底向上"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""[97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)"""
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
"""思路:动态规划,自顶向下"""
n1, n2, n3 = (len(s1), len(s2), len(s3))
if n1 + n2 != n3:
return False
def dfs(i, j, k):
... | the_stack_v2_python_sparse | leetcode/1-300/97.py | Rivarrl/leetcode_python | train | 3 |
c23ce6598da18687bd7ae46d14cb5d4914c503b6 | [
"self._basis_name = 'Kazhdan-Lusztig'\nCombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))\nE = M.E()\nphi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice.... | <|body_start_0|>
self._basis_name = 'Kazhdan-Lusztig'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
E = M.E()
phi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lo... | The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW14]_. EXAMPLES: W... | KL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ... | stack_v2_sparse_classes_36k_train_026462 | 26,467 | no_license | [
{
"docstring": "Initialize ``self``. TESTS:: sage: L = posets.BooleanLattice(4) sage: M = L.quantum_moebius_algebra() sage: TestSuite(M.KL()).run() # long time",
"name": "__init__",
"signature": "def __init__(self, M, prefix='KL')"
},
{
"docstring": "Convert the element indexed by ``x`` to the n... | 2 | stack_v2_sparse_classes_30k_train_010419 | Implement the Python class `KL` described below.
Class description:
The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn... | Implement the Python class `KL` described below.
Class description:
The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW... | the_stack_v2_python_sparse | sage/src/sage/combinat/posets/moebius_algebra.py | bopopescu/geosci | train | 0 |
ec8c83396a32a565f4ad616357d6160b5e4cfc56 | [
"profile_ = Profile.objects.get(user__username__iexact=username_to_toggle)\nuser = requested_user\nis_following = False\nif user in profile_.followers.all():\n profile_.followers.remove(user)\nelse:\n profile_.followers.add(user)\n is_following = True\nreturn (profile_, is_following)",
"user = requested_... | <|body_start_0|>
profile_ = Profile.objects.get(user__username__iexact=username_to_toggle)
user = requested_user
is_following = False
if user in profile_.followers.all():
profile_.followers.remove(user)
else:
profile_.followers.add(user)
is_fol... | Profile manager | ProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileManager:
"""Profile manager"""
def toggle_follow(self, requested_user, username_to_toggle):
"""Toggles follow on and off"""
<|body_0|>
def toggle_favorite(self, requested_user, shop_to_toggle):
"""Toggles favourites for shops"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_026463 | 3,497 | no_license | [
{
"docstring": "Toggles follow on and off",
"name": "toggle_follow",
"signature": "def toggle_follow(self, requested_user, username_to_toggle)"
},
{
"docstring": "Toggles favourites for shops",
"name": "toggle_favorite",
"signature": "def toggle_favorite(self, requested_user, shop_to_tog... | 2 | stack_v2_sparse_classes_30k_val_000843 | Implement the Python class `ProfileManager` described below.
Class description:
Profile manager
Method signatures and docstrings:
- def toggle_follow(self, requested_user, username_to_toggle): Toggles follow on and off
- def toggle_favorite(self, requested_user, shop_to_toggle): Toggles favourites for shops | Implement the Python class `ProfileManager` described below.
Class description:
Profile manager
Method signatures and docstrings:
- def toggle_follow(self, requested_user, username_to_toggle): Toggles follow on and off
- def toggle_favorite(self, requested_user, shop_to_toggle): Toggles favourites for shops
<|skelet... | 3571eafe13d0fd447a31fa4323caa0eccc8fbd8a | <|skeleton|>
class ProfileManager:
"""Profile manager"""
def toggle_follow(self, requested_user, username_to_toggle):
"""Toggles follow on and off"""
<|body_0|>
def toggle_favorite(self, requested_user, shop_to_toggle):
"""Toggles favourites for shops"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileManager:
"""Profile manager"""
def toggle_follow(self, requested_user, username_to_toggle):
"""Toggles follow on and off"""
profile_ = Profile.objects.get(user__username__iexact=username_to_toggle)
user = requested_user
is_following = False
if user in profil... | the_stack_v2_python_sparse | authentification/models.py | KieranHauser/TorontoCoffee | train | 1 |
d09e902719804baca27f4b107dcb407bd898e8cd | [
"with steps.start('Shut Bgp process') as step:\n try:\n uut.execute('process shutdown bgp')\n except Exception as e:\n step.failed('Failed to shut the feature', from_exception=e)",
"with steps.start('UnShut Bgp process') as step:\n try:\n uut.execute('process restart bpm')\n excep... | <|body_start_0|>
with steps.start('Shut Bgp process') as step:
try:
uut.execute('process shutdown bgp')
except Exception as e:
step.failed('Failed to shut the feature', from_exception=e)
<|end_body_0|>
<|body_start_1|>
with steps.start('UnShut Bgp... | Trigger class for ShutNoShut action | TriggerShutNoShut | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerShutNoShut:
"""Trigger class for ShutNoShut action"""
def shut(self, uut, method, abstract, steps):
"""Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results"""
... | stack_v2_sparse_classes_36k_train_026464 | 5,672 | permissive | [
{
"docstring": "Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results",
"name": "shut",
"signature": "def shut(self, uut, method, abstract, steps)"
},
{
"docstring": "restart proc... | 2 | null | Implement the Python class `TriggerShutNoShut` described below.
Class description:
Trigger class for ShutNoShut action
Method signatures and docstrings:
- def shut(self, uut, method, abstract, steps): Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): a... | Implement the Python class `TriggerShutNoShut` described below.
Class description:
Trigger class for ShutNoShut action
Method signatures and docstrings:
- def shut(self, uut, method, abstract, steps): Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): a... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerShutNoShut:
"""Trigger class for ShutNoShut action"""
def shut(self, uut, method, abstract, steps):
"""Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerShutNoShut:
"""Trigger class for ShutNoShut action"""
def shut(self, uut, method, abstract, steps):
"""Send configuration to shut Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results"""
with ... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/shutnoshut/bgp/iosxr/shutnoshut.py | CiscoTestAutomation/genielibs | train | 109 |
ef0d35f80da8d9ee84f69a6605a7c3240511ecbb | [
"urls = response.css('ul li a::attr(\"href\")')\nprint('urls', urls)\nfor url in urls.re('/pickup/\\\\d+$'):\n yield response.follow(url, self.parse_topics)",
"item = Headline()\nitem['title'] = response.css('title::text').get()\nitem['body'] = response.css('article p.sc-inlrYM').xpath('string()').get()\nyield... | <|body_start_0|>
urls = response.css('ul li a::attr("href")')
print('urls', urls)
for url in urls.re('/pickup/\\d+$'):
yield response.follow(url, self.parse_topics)
<|end_body_0|>
<|body_start_1|>
item = Headline()
item['title'] = response.css('title::text').get()
... | NewsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsSpider:
def parse(self, response):
"""トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]"""
<|body_0|>
def parse_topics(self, response):
"""トピックスのページからタイトルと本文を抜き出す Args: response ([type]): [description]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_026465 | 1,225 | no_license | [
{
"docstring": "トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "トピックスのページからタイトルと本文を抜き出す Args: response ([type]): [description]",
"name": "parse_topics",
"signature": "def parse_t... | 2 | stack_v2_sparse_classes_30k_train_020819 | Implement the Python class `NewsSpider` described below.
Class description:
Implement the NewsSpider class.
Method signatures and docstrings:
- def parse(self, response): トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]
- def parse_topics(self, response): トピックスのページからタイトルと本文を抜き出す Args: re... | Implement the Python class `NewsSpider` described below.
Class description:
Implement the NewsSpider class.
Method signatures and docstrings:
- def parse(self, response): トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]
- def parse_topics(self, response): トピックスのページからタイトルと本文を抜き出す Args: re... | f65681a6a1e478d0ac051d3bea8e7a354d2245d3 | <|skeleton|>
class NewsSpider:
def parse(self, response):
"""トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]"""
<|body_0|>
def parse_topics(self, response):
"""トピックスのページからタイトルと本文を抜き出す Args: response ([type]): [description]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewsSpider:
def parse(self, response):
"""トップページのトピックス一覧からここのトピックスへのリンクを抜き出して表示する Args: response ([type]): [description]"""
urls = response.css('ul li a::attr("href")')
print('urls', urls)
for url in urls.re('/pickup/\\d+$'):
yield response.follow(url, self.parse_to... | the_stack_v2_python_sparse | chapter6/myproject/myproject/spiders/news.py | OtsukaTomoaki/PythonCrawlingScraping | train | 0 | |
009690e6eade1a8eef0e3cc12513090b8353f0c7 | [
"profiles = RegistrationProfile.objects.filter(activated=False).order_by('user__date_joined')\nusers = []\nfor reg_prof in profiles:\n users.append(reg_prof.user)\nreturn users",
"context = super(UserListRegistration, self).get_context_data(**kwargs)\nexpired_registration = False\nprofiles = RegistrationProfil... | <|body_start_0|>
profiles = RegistrationProfile.objects.filter(activated=False).order_by('user__date_joined')
users = []
for reg_prof in profiles:
users.append(reg_prof.user)
return users
<|end_body_0|>
<|body_start_1|>
context = super(UserListRegistration, self).get... | The users that are have not completed registration, i.e. not confirmed their email. | UserListRegistration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListRegistration:
"""The users that are have not completed registration, i.e. not confirmed their email."""
def get_queryset(self):
"""registration profile activated = False"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Determine whether or not to sh... | stack_v2_sparse_classes_36k_train_026466 | 19,129 | permissive | [
{
"docstring": "registration profile activated = False",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Determine whether or not to show the delete button.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005745 | Implement the Python class `UserListRegistration` described below.
Class description:
The users that are have not completed registration, i.e. not confirmed their email.
Method signatures and docstrings:
- def get_queryset(self): registration profile activated = False
- def get_context_data(self, **kwargs): Determine... | Implement the Python class `UserListRegistration` described below.
Class description:
The users that are have not completed registration, i.e. not confirmed their email.
Method signatures and docstrings:
- def get_queryset(self): registration profile activated = False
- def get_context_data(self, **kwargs): Determine... | 598b3bc10b72b7b277510cf40e1a4bc56b07452a | <|skeleton|>
class UserListRegistration:
"""The users that are have not completed registration, i.e. not confirmed their email."""
def get_queryset(self):
"""registration profile activated = False"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Determine whether or not to sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListRegistration:
"""The users that are have not completed registration, i.e. not confirmed their email."""
def get_queryset(self):
"""registration profile activated = False"""
profiles = RegistrationProfile.objects.filter(activated=False).order_by('user__date_joined')
users =... | the_stack_v2_python_sparse | jenkins_auth/staff/views.py | antony-wilson/jenkins_auth | train | 0 |
514627b3b78dbf4a626cea05caaa58a984ea2601 | [
"super().__init__(coordinates)\nself.animationFrames = self.spriteSheet.getStripImages(0, 168, 68, 68, 2)\nself.rect = self.image.get_rect()",
"self.frameCount += 1\nif self.frameCount == 28:\n playSound('shoot_wave.wav')\nif 28 < self.frameCount:\n self.coordinates = (self.coordinates[0] - 8, self.coordina... | <|body_start_0|>
super().__init__(coordinates)
self.animationFrames = self.spriteSheet.getStripImages(0, 168, 68, 68, 2)
self.rect = self.image.get_rect()
<|end_body_0|>
<|body_start_1|>
self.frameCount += 1
if self.frameCount == 28:
playSound('shoot_wave.wav')
... | Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen. | DemoWaveSprite | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DemoWaveSprite:
"""Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen."""
def __init__(self, coordinates=(0, 0)):
"""Init DemoWaveSprite using the tuple coordinates. Instance variables: animationFrames: A... | stack_v2_sparse_classes_36k_train_026467 | 38,283 | permissive | [
{
"docstring": "Init DemoWaveSprite using the tuple coordinates. Instance variables: animationFrames: A list of 11 Surface objects from the SpriteSheet object. rect: A rect object for the sprite.",
"name": "__init__",
"signature": "def __init__(self, coordinates=(0, 0))"
},
{
"docstring": "Incre... | 2 | stack_v2_sparse_classes_30k_train_010880 | Implement the Python class `DemoWaveSprite` described below.
Class description:
Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen.
Method signatures and docstrings:
- def __init__(self, coordinates=(0, 0)): Init DemoWaveSprite using the ... | Implement the Python class `DemoWaveSprite` described below.
Class description:
Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen.
Method signatures and docstrings:
- def __init__(self, coordinates=(0, 0)): Init DemoWaveSprite using the ... | 090f3749e102c5331136298356d543c8b4e8a9a5 | <|skeleton|>
class DemoWaveSprite:
"""Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen."""
def __init__(self, coordinates=(0, 0)):
"""Init DemoWaveSprite using the tuple coordinates. Instance variables: animationFrames: A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DemoWaveSprite:
"""Create an instance of a sonic wave sprite for the demo. Attributes: coordinates: A tuple location to blit the sprite on the screen."""
def __init__(self, coordinates=(0, 0)):
"""Init DemoWaveSprite using the tuple coordinates. Instance variables: animationFrames: A list of 11 S... | the_stack_v2_python_sparse | game/demo/demo_sprites.py | leoua7/clu-clu-game | train | 0 |
8979a224955ca36050d932ffd8dabb80d64560ee | [
"this_recprocess_key = list()\nfor idx, fragment_key in enumerate(fragment_keys):\n this_recprocess_key.append(dict())\n this_recprocess_key[idx]['recording_id'] = fragment_key['recording_id']\n this_recprocess_key[idx]['fragment_number'] = fragment_key[fragment_fieldname]\n this_recprocess_key[idx]['st... | <|body_start_0|>
this_recprocess_key = list()
for idx, fragment_key in enumerate(fragment_keys):
this_recprocess_key.append(dict())
this_recprocess_key[idx]['recording_id'] = fragment_key['recording_id']
this_recprocess_key[idx]['fragment_number'] = fragment_key[fragm... | Processing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processing:
def insert_recording_process(self, fragment_keys, fragment_fieldname):
"""# Insert RecordingTask(s) from recording. # For each processing "unit" of a recording add a new RecordingTask (imaging ->field of view, electrophysiology->probe) Input: recording_key (dict) = Dictionary... | stack_v2_sparse_classes_36k_train_026468 | 5,329 | no_license | [
{
"docstring": "# Insert RecordingTask(s) from recording. # For each processing \"unit\" of a recording add a new RecordingTask (imaging ->field of view, electrophysiology->probe) Input: recording_key (dict) = Dictionary with recording record rec_unit (dict) = Dictionary of recording \"unit\" to be processed un... | 2 | stack_v2_sparse_classes_30k_train_004355 | Implement the Python class `Processing` described below.
Class description:
Implement the Processing class.
Method signatures and docstrings:
- def insert_recording_process(self, fragment_keys, fragment_fieldname): # Insert RecordingTask(s) from recording. # For each processing "unit" of a recording add a new Recordi... | Implement the Python class `Processing` described below.
Class description:
Implement the Processing class.
Method signatures and docstrings:
- def insert_recording_process(self, fragment_keys, fragment_fieldname): # Insert RecordingTask(s) from recording. # For each processing "unit" of a recording add a new Recordi... | 7bc81be171fe4b68bc3e59e1f57f2148651d9772 | <|skeleton|>
class Processing:
def insert_recording_process(self, fragment_keys, fragment_fieldname):
"""# Insert RecordingTask(s) from recording. # For each processing "unit" of a recording add a new RecordingTask (imaging ->field of view, electrophysiology->probe) Input: recording_key (dict) = Dictionary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Processing:
def insert_recording_process(self, fragment_keys, fragment_fieldname):
"""# Insert RecordingTask(s) from recording. # For each processing "unit" of a recording add a new RecordingTask (imaging ->field of view, electrophysiology->probe) Input: recording_key (dict) = Dictionary with recordin... | the_stack_v2_python_sparse | u19_pipeline/recording_process.py | BrainCOGS/U19-pipeline_python | train | 2 | |
81211fd83abd479e819a2c568e9b9b97dd48cfb0 | [
"self.agency = agency\nself.base_url = base_url\nself.client_certificate_password = client_certificate_password\nself.mission = mission\nself.role = role",
"if dictionary is None:\n return None\nagency = dictionary.get('agency')\nbase_url = dictionary.get('baseUrl')\nclient_certificate_password = dictionary.ge... | <|body_start_0|>
self.agency = agency
self.base_url = base_url
self.client_certificate_password = client_certificate_password
self.mission = mission
self.role = role
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
agency = dictionar... | Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. base_url (string): The base url of C2S CAP server. client_certificate_password (str... | C2SAccessPortal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class C2SAccessPortal:
"""Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. base_url (string): The base url of C2S C... | stack_v2_sparse_classes_36k_train_026469 | 2,391 | permissive | [
{
"docstring": "Constructor for the C2SAccessPortal class",
"name": "__init__",
"signature": "def __init__(self, agency=None, base_url=None, client_certificate_password=None, mission=None, role=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_val_001042 | Implement the Python class `C2SAccessPortal` described below.
Class description:
Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. b... | Implement the Python class `C2SAccessPortal` described below.
Class description:
Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. b... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class C2SAccessPortal:
"""Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. base_url (string): The base url of C2S C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class C2SAccessPortal:
"""Implementation of the 'C2SAccessPortal' model. Specifies information required to connect to CAP to get AWS credentials. C2SAccessPortal(CAP) is AWS commercial cloud service access portal. Attributes: agency (string): Name of the agency. base_url (string): The base url of C2S CAP server. cl... | the_stack_v2_python_sparse | cohesity_management_sdk/models/c2s_access_portal.py | cohesity/management-sdk-python | train | 24 |
85f8b6f12139c5264b73dae9a60fec86414ea00e | [
"ca = [0] + [float('inf')] * amount\nfor c in coins:\n for a in range(c, amount + 1):\n ca[a] = min(ca[a], 1 + ca[a - c])\nreturn ca[-1] if ca[-1] != float('inf') else -1",
"n = len(coins)\nca = [[0] * (amount + 1) for _ in range(n + 1)]\nfor i in range(1, amount + 1):\n ca[0][i] = float('inf')\nfor ... | <|body_start_0|>
ca = [0] + [float('inf')] * amount
for c in coins:
for a in range(c, amount + 1):
ca[a] = min(ca[a], 1 + ca[a - c])
return ca[-1] if ca[-1] != float('inf') else -1
<|end_body_0|>
<|body_start_1|>
n = len(coins)
ca = [[0] * (amount + 1... | Coin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coin:
def minimum_change(self, coins: List[int], amount: int) -> int:
"""Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:"""
<|body_0|>
def minimum_change_(self, coins: List[int], amount: int) -> int:
"""Ap... | stack_v2_sparse_classes_36k_train_026470 | 1,745 | no_license | [
{
"docstring": "Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:",
"name": "minimum_change",
"signature": "def minimum_change(self, coins: List[int], amount: int) -> int"
},
{
"docstring": "Approach: DP (2 D array) Time Complexity: O(C... | 2 | null | Implement the Python class `Coin` described below.
Class description:
Implement the Coin class.
Method signatures and docstrings:
- def minimum_change(self, coins: List[int], amount: int) -> int: Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:
- def minimu... | Implement the Python class `Coin` described below.
Class description:
Implement the Coin class.
Method signatures and docstrings:
- def minimum_change(self, coins: List[int], amount: int) -> int: Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:
- def minimu... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Coin:
def minimum_change(self, coins: List[int], amount: int) -> int:
"""Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:"""
<|body_0|>
def minimum_change_(self, coins: List[int], amount: int) -> int:
"""Ap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Coin:
def minimum_change(self, coins: List[int], amount: int) -> int:
"""Approach: DP (1 D array) Time Complexity: O(C*A) Space Complexity: O(A) :param coins: :param amount: :return:"""
ca = [0] + [float('inf')] * amount
for c in coins:
for a in range(c, amount + 1):
... | the_stack_v2_python_sparse | revisited_2021/dp/coin_change.py | Shiv2157k/leet_code | train | 1 | |
6e66765b1e0bfc4812a4a564db8501bdcb18810d | [
"meetup = get_meetup(meetup_id)\nif not meetup:\n error_response['message'] = 'Meetup not found'\n return (error_response, 404)\nrequest_data = request.get_json()\nRsvpValidators.rsvp_validator(request_data)\nrequest_data = request_data_strip(request_data)\nrequest_data.update({'user_id': request.decoded_toke... | <|body_start_0|>
meetup = get_meetup(meetup_id)
if not meetup:
error_response['message'] = 'Meetup not found'
return (error_response, 404)
request_data = request.get_json()
RsvpValidators.rsvp_validator(request_data)
request_data = request_data_strip(reque... | RsvpResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RsvpResource:
def post(self, meetup_id):
"""Endpoint to create an rsvp"""
<|body_0|>
def get(self, meetup_id):
""""Endpoint to get all rsvps"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
meetup = get_meetup(meetup_id)
if not meetup:
... | stack_v2_sparse_classes_36k_train_026471 | 2,356 | no_license | [
{
"docstring": "Endpoint to create an rsvp",
"name": "post",
"signature": "def post(self, meetup_id)"
},
{
"docstring": "\"Endpoint to get all rsvps",
"name": "get",
"signature": "def get(self, meetup_id)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000524 | Implement the Python class `RsvpResource` described below.
Class description:
Implement the RsvpResource class.
Method signatures and docstrings:
- def post(self, meetup_id): Endpoint to create an rsvp
- def get(self, meetup_id): "Endpoint to get all rsvps | Implement the Python class `RsvpResource` described below.
Class description:
Implement the RsvpResource class.
Method signatures and docstrings:
- def post(self, meetup_id): Endpoint to create an rsvp
- def get(self, meetup_id): "Endpoint to get all rsvps
<|skeleton|>
class RsvpResource:
def post(self, meetup_... | aa62556731fdc5b83c3819b0d94df34a28e98dcd | <|skeleton|>
class RsvpResource:
def post(self, meetup_id):
"""Endpoint to create an rsvp"""
<|body_0|>
def get(self, meetup_id):
""""Endpoint to get all rsvps"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RsvpResource:
def post(self, meetup_id):
"""Endpoint to create an rsvp"""
meetup = get_meetup(meetup_id)
if not meetup:
error_response['message'] = 'Meetup not found'
return (error_response, 404)
request_data = request.get_json()
RsvpValidators.r... | the_stack_v2_python_sparse | resources/rsvp.py | Paccy10/Questioner-python | train | 0 | |
e8c33b338d28408766bf49f47f6ccf72f4acebf5 | [
"cache_key = str(calendar_year)\nif cache_key not in UtilityFactorMethods._cache:\n start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])\n if len(start_years[start_years <= calendar_year]) > 0:\n calendar_year = max(start_years[start_years <= calendar_year])\n method = UtilityFa... | <|body_start_0|>
cache_key = str(calendar_year)
if cache_key not in UtilityFactorMethods._cache:
start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])
if len(start_years[start_years <= calendar_year]) > 0:
calendar_year = max(start_years[start_year... | **Loads and provides access to upstream calculation methods by start year.** | UtilityFactorMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_36k_train_026472 | 11,165 | no_license | [
{
"docstring": "Calculate \"city\" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled in charge-depleting driving, scalar or pandas Series Returns: A callable python function used to calculate upstream cert emissions for the given calendar ye... | 3 | stack_v2_sparse_classes_30k_train_012732 | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled... | the_stack_v2_python_sparse | omega_model/policy/utility_factors.py | USEPA/EPA_OMEGA_Model | train | 17 |
b17467cc56c41cdef6042279e0c5fc85f345573b | [
"if not root:\n return True\nall_layer = self.levelOrderTraversal(root)\nfor i in all_layer:\n if i != i[::-1]:\n return False\nreturn True",
"result, layer = ([], [root])\nwhile layer:\n valid_node_found = False\n next_layer, node_vals = ([], [])\n for node in layer:\n if not node:\n... | <|body_start_0|>
if not root:
return True
all_layer = self.levelOrderTraversal(root)
for i in all_layer:
if i != i[::-1]:
return False
return True
<|end_body_0|>
<|body_start_1|>
result, layer = ([], [root])
while layer:
... | Solution_A1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_A1:
def isSymmetric(self, root: TreeNode) -> bool:
"""Verify if all layers are symmetric"""
<|body_0|>
def levelOrderTraversal(self, root) -> List[List[int]]:
"""Helper: show all layers in a tree, refer to LC102 levelOrder Modification: track all None nodes ... | stack_v2_sparse_classes_36k_train_026473 | 6,692 | permissive | [
{
"docstring": "Verify if all layers are symmetric",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root: TreeNode) -> bool"
},
{
"docstring": "Helper: show all layers in a tree, refer to LC102 levelOrder Modification: track all None nodes Show the tree layer by layer from top to bot... | 2 | null | Implement the Python class `Solution_A1` described below.
Class description:
Implement the Solution_A1 class.
Method signatures and docstrings:
- def isSymmetric(self, root: TreeNode) -> bool: Verify if all layers are symmetric
- def levelOrderTraversal(self, root) -> List[List[int]]: Helper: show all layers in a tre... | Implement the Python class `Solution_A1` described below.
Class description:
Implement the Solution_A1 class.
Method signatures and docstrings:
- def isSymmetric(self, root: TreeNode) -> bool: Verify if all layers are symmetric
- def levelOrderTraversal(self, root) -> List[List[int]]: Helper: show all layers in a tre... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_A1:
def isSymmetric(self, root: TreeNode) -> bool:
"""Verify if all layers are symmetric"""
<|body_0|>
def levelOrderTraversal(self, root) -> List[List[int]]:
"""Helper: show all layers in a tree, refer to LC102 levelOrder Modification: track all None nodes ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_A1:
def isSymmetric(self, root: TreeNode) -> bool:
"""Verify if all layers are symmetric"""
if not root:
return True
all_layer = self.levelOrderTraversal(root)
for i in all_layer:
if i != i[::-1]:
return False
return True... | the_stack_v2_python_sparse | LeetCode/LC101_symmetric_tree.py | jxie0755/Learning_Python | train | 0 | |
cdcf088e8b985d64fefc3cb3e2f823bc3f11c140 | [
"self.left_eye_percentage = left_eye_percentage\nself.desired_face_width = desired_face_width\nself.desired_face_height = desired_face_height\nself.predictor = LandmarkPredictor(predictor_type)\nif self.desired_face_height is None:\n self.desired_face_height = self.desired_face_width",
"shape = self.predictor.... | <|body_start_0|>
self.left_eye_percentage = left_eye_percentage
self.desired_face_width = desired_face_width
self.desired_face_height = desired_face_height
self.predictor = LandmarkPredictor(predictor_type)
if self.desired_face_height is None:
self.desired_face_height... | FaceAligner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye ... | stack_v2_sparse_classes_36k_train_026474 | 4,971 | no_license | [
{
"docstring": "Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye position. For this variable, it is common to see percentages within the range of 20-40%. These percentages control how much of the face is visible af... | 2 | stack_v2_sparse_classes_30k_train_020672 | Implement the Python class `FaceAligner` described below.
Class description:
Implement the FaceAligner class.
Method signatures and docstrings:
- def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'): Define aligner for all images. :param left_eye_... | Implement the Python class `FaceAligner` described below.
Class description:
Implement the FaceAligner class.
Method signatures and docstrings:
- def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'): Define aligner for all images. :param left_eye_... | 3d80158f3261ddff2bd455ce883f57d6fc9ede43 | <|skeleton|>
class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceAligner:
def __init__(self, left_eye_percentage=(0.4, 0.4), desired_face_width=256, desired_face_height=None, predictor_type='dlib'):
"""Define aligner for all images. :param left_eye_percentage: An optional (x, y) tuple with the default shown, specifying the desired output left eye position. For ... | the_stack_v2_python_sparse | image_alterations_detector/face_transform/face_alignment/face_aligner.py | Giulianini/image-alterations-detector | train | 1 | |
309484e02826b23cacb08b5c3980cb537a43ec0d | [
"self.provider_id = provider_id\nself.driver_id = driver_id\nself.comment = comment\nself.date_time = date_time",
"if dictionary is None:\n return None\nprovider_id = dictionary.get('providerId')\ndriver_id = dictionary.get('driverId')\ncomment = dictionary.get('comment')\ndate_time = dictionary.get('dateTime'... | <|body_start_0|>
self.provider_id = provider_id
self.driver_id = driver_id
self.comment = comment
self.date_time = date_time
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
provider_id = dictionary.get('providerId')
driver_id = dict... | Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The annotation text associated with the log. date_time (string): Date and time for this... | AnnotationLog | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationLog:
"""Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The annotation text associated with the log. d... | stack_v2_sparse_classes_36k_train_026475 | 2,114 | permissive | [
{
"docstring": "Constructor for the AnnotationLog class",
"name": "__init__",
"signature": "def __init__(self, provider_id=None, driver_id=None, comment=None, date_time=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repre... | 2 | stack_v2_sparse_classes_30k_train_010628 | Implement the Python class `AnnotationLog` described below.
Class description:
Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The ann... | Implement the Python class `AnnotationLog` described below.
Class description:
Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The ann... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class AnnotationLog:
"""Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The annotation text associated with the log. d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnotationLog:
"""Implementation of the 'Annotation Log' model. TODO: type model description here. Attributes: provider_id (string): The unique 'Provider ID' of the TSP. driver_id (string): The id of the driver who created this log. comment (string): The annotation text associated with the log. date_time (str... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/annotation_log.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
cf223f2937e86fe317e5b3706026fddc724017fd | [
"logging.Handler.__init__(self)\nif not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):\n raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))\nself.database_name = database.database_name\nself.write_log_buffer =... | <|body_start_0|>
logging.Handler.__init__(self)
if not isinstance(database, LogMaster) and (not isinstance(database, LogReadWrite)):
raise TypeError('A LogMaster or LogReadWrite object must be specified. A {:} was specified instead'.format(type(database)))
self.database_name = databa... | A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package. | MongoLogBufferHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster... | stack_v2_sparse_classes_36k_train_026476 | 47,472 | no_license | [
{
"docstring": "A LogMaster or LogReadWrite object must be specified. The resulting handler object will have a 'database_name' attribute that can be used to identify the handler's destination.",
"name": "__init__",
"signature": "def __init__(self, database)"
},
{
"docstring": "If a formatter is ... | 2 | stack_v2_sparse_classes_30k_train_019656 | Implement the Python class `MongoLogBufferHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures an... | Implement the Python class `MongoLogBufferHandler` described below.
Class description:
A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package.
Method signatures an... | aab8f9789cb6d9b824836ffa4613b4b17d7d4df6 | <|skeleton|>
class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoLogBufferHandler:
"""A handler class which writes logging records, appropriately formatted, to the a specified database's log buffer. This is used to simplify the log generation process with the use of the python "logging" package."""
def __init__(self, database):
"""A LogMaster or LogReadWr... | the_stack_v2_python_sparse | Drivers/Database/MongoDB.py | cdfredrick/AstroComb_HPF | train | 1 |
4be65aa02f78256219340f5afe187caec6ccd69d | [
"dict.__init__(self)\nself.translation_dict = translation_dict if translation_list != None else {}\nself.translation_list = translation_list if translation_list != None else []\nself.separator = separator\nself.freshen()",
"self.clear()\nself.update(self.translation_dict)\nfirstline = True\nfor linenum, linetext ... | <|body_start_0|>
dict.__init__(self)
self.translation_dict = translation_dict if translation_list != None else {}
self.translation_list = translation_list if translation_list != None else []
self.separator = separator
self.freshen()
<|end_body_0|>
<|body_start_1|>
self.c... | Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments | FDictionaryTranslator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FDictionaryTranslator:
"""Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments"""
def __init__(self, translation_list=None, separator... | stack_v2_sparse_classes_36k_train_026477 | 5,018 | no_license | [
{
"docstring": "Initialize FDictionaryTranslator instance Arguments: translation_list -- list of strings containing containing original_word <separator> translated_word pairs separator -- separator used in file translation_dict -- dictionary containing original_word:translated_word pairs",
"name": "__init__... | 2 | null | Implement the Python class `FDictionaryTranslator` described below.
Class description:
Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments
Method signatures a... | Implement the Python class `FDictionaryTranslator` described below.
Class description:
Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments
Method signatures a... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class FDictionaryTranslator:
"""Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments"""
def __init__(self, translation_list=None, separator... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FDictionaryTranslator:
"""Generate translation dictionary from file and/or arguments File format: Acceptable line forms: 1. original_word --> translated_word (note --> can be changed in constructor ) 2. lines starting with # are comments"""
def __init__(self, translation_list=None, separator='-->', trans... | the_stack_v2_python_sparse | Extensions/Reporting/FPythonCode/FDictionaryTranslator.py | webclinic017/fa-absa-py3 | train | 0 |
556a7bbeb7f661d24b39e4901a5fbe82e6aeb109 | [
"try:\n models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)\n meet = models.Meet.objects.get(id=int(pk))\n meet.is_current_meet = True\n meet.save()\nexcept Exception:\n request.session['meet'] = {}\n return Response({'status': 'active meet cleared'}, ... | <|body_start_0|>
try:
models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)
meet = models.Meet.objects.get(id=int(pk))
meet.is_current_meet = True
meet.save()
except Exception:
request.session['meet']... | Retrieve a meet by its id | MeetViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
<|body_0|>
def toggle_ranking(self, request, pk=None):
"""Changes the enable_ranking flag ... | stack_v2_sparse_classes_36k_train_026478 | 7,293 | no_license | [
{
"docstring": "Sets a meet as active, storing it in the user's session --- omit_serializer: true",
"name": "set_active",
"signature": "def set_active(self, request, pk=None)"
},
{
"docstring": "Changes the enable_ranking flag to its opposite --- omit_serializer: true",
"name": "toggle_ranki... | 2 | stack_v2_sparse_classes_30k_train_008255 | Implement the Python class `MeetViewSet` described below.
Class description:
Retrieve a meet by its id
Method signatures and docstrings:
- def set_active(self, request, pk=None): Sets a meet as active, storing it in the user's session --- omit_serializer: true
- def toggle_ranking(self, request, pk=None): Changes the... | Implement the Python class `MeetViewSet` described below.
Class description:
Retrieve a meet by its id
Method signatures and docstrings:
- def set_active(self, request, pk=None): Sets a meet as active, storing it in the user's session --- omit_serializer: true
- def toggle_ranking(self, request, pk=None): Changes the... | 0c3280050e1caa34f42d350dfab00fd3b1dbe5ad | <|skeleton|>
class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
<|body_0|>
def toggle_ranking(self, request, pk=None):
"""Changes the enable_ranking flag ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeetViewSet:
"""Retrieve a meet by its id"""
def set_active(self, request, pk=None):
"""Sets a meet as active, storing it in the user's session --- omit_serializer: true"""
try:
models.Meet.objects.all().exclude(id=int(pk)).update(is_current_meet=False, enable_ranking=False)
... | the_stack_v2_python_sparse | fairplay/meet/views.py | Greymalkin/fairplay | train | 0 |
bbeac40f058d522b15a6dfbf1b0c0bc5b877df51 | [
"def wrapper(t_cls):\n \"\"\"Register class with wrapper function.\n\n :param t_cls: class need to register\n :return: wrapper of t_cls\n \"\"\"\n t_cls_name = alias if alias is not None else t_cls.__name__\n if type_name not in cls.__registry__:\n cls.__registry__[t... | <|body_start_0|>
def wrapper(t_cls):
"""Register class with wrapper function.
:param t_cls: class need to register
:return: wrapper of t_cls
"""
t_cls_name = alias if alias is not None else t_cls.__name__
if type_na... | A Factory Class to manage all class need to register with config. | ClassFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassFactory:
"""A Factory Class to manage all class need to register with config."""
def register(cls, type_name=ClassType.GENERAL, alias=None):
"""Register class into registry. :param type_name: type_name: type name of class registry :param alias: alias of class name :return: wrapp... | stack_v2_sparse_classes_36k_train_026479 | 6,906 | permissive | [
{
"docstring": "Register class into registry. :param type_name: type_name: type name of class registry :param alias: alias of class name :return: wrapper",
"name": "register",
"signature": "def register(cls, type_name=ClassType.GENERAL, alias=None)"
},
{
"docstring": "Register class with type na... | 6 | stack_v2_sparse_classes_30k_train_005618 | Implement the Python class `ClassFactory` described below.
Class description:
A Factory Class to manage all class need to register with config.
Method signatures and docstrings:
- def register(cls, type_name=ClassType.GENERAL, alias=None): Register class into registry. :param type_name: type_name: type name of class ... | Implement the Python class `ClassFactory` described below.
Class description:
A Factory Class to manage all class need to register with config.
Method signatures and docstrings:
- def register(cls, type_name=ClassType.GENERAL, alias=None): Register class into registry. :param type_name: type_name: type name of class ... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class ClassFactory:
"""A Factory Class to manage all class need to register with config."""
def register(cls, type_name=ClassType.GENERAL, alias=None):
"""Register class into registry. :param type_name: type_name: type name of class registry :param alias: alias of class name :return: wrapp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassFactory:
"""A Factory Class to manage all class need to register with config."""
def register(cls, type_name=ClassType.GENERAL, alias=None):
"""Register class into registry. :param type_name: type_name: type name of class registry :param alias: alias of class name :return: wrapper"""
... | the_stack_v2_python_sparse | zeus/common/class_factory.py | huawei-noah/xingtian | train | 308 |
9207d67bd4a478680b8a05393bb46b933b85ea77 | [
"if created:\n amount = random.randint(1, 7)\n tags = LimitedTagFactory.create_batch(amount, **kwargs)\n obj.tags.add(*tags)",
"if created:\n amount = random.randint(3, 7)\n authors = LimitedAuthorFactory.create_batch(amount, **kwargs)\n obj.authors.add(*authors)",
"if created:\n amount = r... | <|body_start_0|>
if created:
amount = random.randint(1, 7)
tags = LimitedTagFactory.create_batch(amount, **kwargs)
obj.tags.add(*tags)
<|end_body_0|>
<|body_start_1|>
if created:
amount = random.randint(3, 7)
authors = LimitedAuthorFactory.cre... | Base book factory. | BaseBookFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseBookFactory:
"""Base book factory."""
def tags(obj, created, extracted, **kwargs):
"""Create Tag objects for the created Book instance."""
<|body_0|>
def authors(obj, created, extracted, **kwargs):
"""Create `Author` objects for the created `Book` instance.""... | stack_v2_sparse_classes_36k_train_026480 | 4,296 | permissive | [
{
"docstring": "Create Tag objects for the created Book instance.",
"name": "tags",
"signature": "def tags(obj, created, extracted, **kwargs)"
},
{
"docstring": "Create `Author` objects for the created `Book` instance.",
"name": "authors",
"signature": "def authors(obj, created, extracte... | 3 | stack_v2_sparse_classes_30k_train_018651 | Implement the Python class `BaseBookFactory` described below.
Class description:
Base book factory.
Method signatures and docstrings:
- def tags(obj, created, extracted, **kwargs): Create Tag objects for the created Book instance.
- def authors(obj, created, extracted, **kwargs): Create `Author` objects for the creat... | Implement the Python class `BaseBookFactory` described below.
Class description:
Base book factory.
Method signatures and docstrings:
- def tags(obj, created, extracted, **kwargs): Create Tag objects for the created Book instance.
- def authors(obj, created, extracted, **kwargs): Create `Author` objects for the creat... | 933ef372fa7847d943206d72bfb03c201dbafbd6 | <|skeleton|>
class BaseBookFactory:
"""Base book factory."""
def tags(obj, created, extracted, **kwargs):
"""Create Tag objects for the created Book instance."""
<|body_0|>
def authors(obj, created, extracted, **kwargs):
"""Create `Author` objects for the created `Book` instance.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseBookFactory:
"""Base book factory."""
def tags(obj, created, extracted, **kwargs):
"""Create Tag objects for the created Book instance."""
if created:
amount = random.randint(1, 7)
tags = LimitedTagFactory.create_batch(amount, **kwargs)
obj.tags.add... | the_stack_v2_python_sparse | implementation/server/factories/books_book.py | Aincient/cleo | train | 0 |
6e6ce69515f4775cdbaba7a265014796cd6ddce6 | [
"super().__init__()\nself.control_dim = control_dim\nself.shared_control_proj = xavier_uniform_linear(self.control_dim, self.control_dim)\nself.position_aware = nn.ModuleList()\nfor i in range(length):\n self.position_aware.append(xavier_uniform_linear(self.control_dim, self.control_dim))\nself.control_question ... | <|body_start_0|>
super().__init__()
self.control_dim = control_dim
self.shared_control_proj = xavier_uniform_linear(self.control_dim, self.control_dim)
self.position_aware = nn.ModuleList()
for i in range(length):
self.position_aware.append(xavier_uniform_linear(self.... | A MAC recurrent cell control unit. | ControlUnit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlUnit:
"""A MAC recurrent cell control unit."""
def __init__(self, control_dim: int=512, length: int=12) -> None:
"""Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The length of the overall MAC network, i.e. the max number of ... | stack_v2_sparse_classes_36k_train_026481 | 3,090 | no_license | [
{
"docstring": "Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The length of the overall MAC network, i.e. the max number of reasoning steps the network intends to perform. Returns: -------- `None`",
"name": "__init__",
"signature": "def __init__(self,... | 2 | null | Implement the Python class `ControlUnit` described below.
Class description:
A MAC recurrent cell control unit.
Method signatures and docstrings:
- def __init__(self, control_dim: int=512, length: int=12) -> None: Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The l... | Implement the Python class `ControlUnit` described below.
Class description:
A MAC recurrent cell control unit.
Method signatures and docstrings:
- def __init__(self, control_dim: int=512, length: int=12) -> None: Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The l... | 78c479f8d0b3209ece9f9ccbbf63810802293f61 | <|skeleton|>
class ControlUnit:
"""A MAC recurrent cell control unit."""
def __init__(self, control_dim: int=512, length: int=12) -> None:
"""Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The length of the overall MAC network, i.e. the max number of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControlUnit:
"""A MAC recurrent cell control unit."""
def __init__(self, control_dim: int=512, length: int=12) -> None:
"""Initialise the control unit. Params: ------- `dim`: The dimension of the control vector. `length`: The length of the overall MAC network, i.e. the max number of reasoning ste... | the_stack_v2_python_sparse | gat_vqa/modules/reasoning/mac/control.py | alexmirrington/gat-vqa | train | 4 |
5de40c7d8d371ca4df46c8fd1a9c061eb997c4d6 | [
"rtn = []\n\ndef dfs(node):\n if node:\n rtn.append(str(node.val))\n for c in node.children:\n dfs(c)\n rtn.append('#')\n else:\n rtn.append('#')\ndfs(root)\nreturn ' '.join(rtn)",
"def dfs():\n val = next(vals)\n if val == '#':\n return None\n else:\n ... | <|body_start_0|>
rtn = []
def dfs(node):
if node:
rtn.append(str(node.val))
for c in node.children:
dfs(c)
rtn.append('#')
else:
rtn.append('#')
dfs(root)
return ' '.join(rtn)
<|e... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_026482 | 1,325 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_017569 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | a00a57e1b36433648d1cace331e15ff276cef189 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
rtn = []
def dfs(node):
if node:
rtn.append(str(node.val))
for c in node.children:
dfs(c)
... | the_stack_v2_python_sparse | leet/trees/encodenary.py | stacykutyepov/python-cp-cheatsheet | train | 2 | |
56372b6003ecaffc555fca403c207cf95e64cf51 | [
"super().__init__()\nself.name = 'PFNLayer'\nself.last_vfe = last_layer\nif not self.last_vfe:\n out_channels = out_channels // 2\nself.units = out_channels\nself.h = height\nself.w = width\nself.z = depth\nif use_norm:\n Linear = change_default_args(bias=False)(nn.Linear)\nelse:\n Linear = change_default_... | <|body_start_0|>
super().__init__()
self.name = 'PFNLayer'
self.last_vfe = last_layer
if not self.last_vfe:
out_channels = out_channels // 2
self.units = out_channels
self.h = height
self.w = width
self.z = depth
if use_norm:
... | PFNLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. Thi... | stack_v2_sparse_classes_36k_train_026483 | 7,758 | no_license | [
{
"docstring": "Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. This layer performs a similar role as second.pytorch.voxelnet.VFELayer. :param in_channels: <int>. Number of input channels. :param out_... | 2 | null | Implement the Python class `PFNLayer` described below.
Class description:
Implement the PFNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False): Pillar Feature Net Layer. The Pillar Feature Net could be composed... | Implement the Python class `PFNLayer` described below.
Class description:
Implement the PFNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False): Pillar Feature Net Layer. The Pillar Feature Net could be composed... | 43388efd911feecde588b27a753de353b8e28265 | <|skeleton|>
class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. Thi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PFNLayer:
def __init__(self, in_channels, out_channels, use_norm=True, height=480, width=480, depth=2, last_layer=False):
"""Pillar Feature Net Layer. The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only used a single PFNLayer. This layer perfor... | the_stack_v2_python_sparse | models/backbones/pointpillars_voxel.py | dragonlong/haoi-pose | train | 0 | |
df367dfb93aa634c158ce29148361f3d8f2aa1f7 | [
"len_nums = len(nums)\nif len_nums == 0:\n return None\nself.sum_nums = [0] * len_nums\nself.sum_nums[0] = nums[0]\nif len_nums > 1:\n for index in range(1, len_nums):\n self.sum_nums[index] = self.sum_nums[index - 1] + nums[index]",
"if i == 0:\n return self.sum_nums[j]\nreturn self.sum_nums[j] -... | <|body_start_0|>
len_nums = len(nums)
if len_nums == 0:
return None
self.sum_nums = [0] * len_nums
self.sum_nums[0] = nums[0]
if len_nums > 1:
for index in range(1, len_nums):
self.sum_nums[index] = self.sum_nums[index - 1] + nums[index]
<|... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
len_nums = len(nums)
if len_nums == 0:
... | stack_v2_sparse_classes_36k_train_026484 | 1,296 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | e80489923c60ed716d54c1bdeaaf52133d4e1209 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
len_nums = len(nums)
if len_nums == 0:
return None
self.sum_nums = [0] * len_nums
self.sum_nums[0] = nums[0]
if len_nums > 1:
for index in range(1, len_nums):
... | the_stack_v2_python_sparse | 303区域和检索_数组不可变.py | XinZhaoFu/leetcode_moyu | train | 0 | |
ff97b4f78d97d2ef13d21f60b8704045c1f5755c | [
"comment_query = self.sess.query(Comment).get(comment_id)\nif not comment_query:\n self.send_error(status_code=404, message='Not Found')\nresponse = {'id': comment_query.id, 'content': comment_query.content, 'problem_id': comment_query.problem_id, 'user_id': comment_query.user_id, 'created_date': iso_datetime(co... | <|body_start_0|>
comment_query = self.sess.query(Comment).get(comment_id)
if not comment_query:
self.send_error(status_code=404, message='Not Found')
response = {'id': comment_query.id, 'content': comment_query.content, 'problem_id': comment_query.problem_id, 'user_id': comment_query... | CommentHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id... | stack_v2_sparse_classes_36k_train_026485 | 4,646 | no_license | [
{
"docstring": "Returns comment by its id. Answer format: .. code-block: json { \"modified_date\": \"2015-06-25T22:30:49.000Z\", \"modified_user_id\": 1, \"user_id\": 2, \"problem_id\": 1, \"content\": \"comment_0_content\", \"created_date\": \"2015-06-25T22:30:49.000Z\", \"id\": 1 }",
"name": "get",
"s... | 3 | stack_v2_sparse_classes_30k_train_016370 | Implement the Python class `CommentHandler` described below.
Class description:
Implement the CommentHandler class.
Method signatures and docstrings:
- def get(self, comment_id): Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_i... | Implement the Python class `CommentHandler` described below.
Class description:
Implement the CommentHandler class.
Method signatures and docstrings:
- def get(self, comment_id): Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_i... | e911ce6bcaa73e15248586d40c95beeb1a05da47 | <|skeleton|>
class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentHandler:
def get(self, comment_id):
"""Returns comment by its id. Answer format: .. code-block: json { "modified_date": "2015-06-25T22:30:49.000Z", "modified_user_id": 1, "user_id": 2, "problem_id": 1, "content": "comment_0_content", "created_date": "2015-06-25T22:30:49.000Z", "id": 1 }"""
... | the_stack_v2_python_sparse | ecomap/api/v1_0/handlers/comments.py | ITsvetkoFF/Kv-008 | train | 3 | |
08e2adc41ef8482c92f6fe2c2c6e43e591e0754a | [
"while len(Solution.F) <= n:\n i = len(Solution.F)\n Solution.F.append(sys.maxint)\n j = 1\n while i - j * j >= 0:\n Solution.F[i] = min(Solution.F[i], Solution.F[i - j * j] + 1)\n j += 1\nreturn Solution.F[n]",
"q = [0]\nvisited = [False for _ in xrange(n + 1)]\nlevel = 0\nwhile q:\n ... | <|body_start_0|>
while len(Solution.F) <= n:
i = len(Solution.F)
Solution.F.append(sys.maxint)
j = 1
while i - j * j >= 0:
Solution.F[i] = min(Solution.F[i], Solution.F[i - j * j] + 1)
j += 1
return Solution.F[n]
<|end_body_... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
"""static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward"""
<|body_0|>
def numSquares_bfs(self, n):
"""bfs the q stores the intermediate result of sum of s... | stack_v2_sparse_classes_36k_train_026486 | 2,074 | permissive | [
{
"docstring": "static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": "bfs the q stores the intermediate result of sum of squares :type n:... | 3 | stack_v2_sparse_classes_30k_train_019623 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward
- def numSquares_bfs(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward
- def numSquares_bfs(s... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def numSquares(self, n):
"""static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward"""
<|body_0|>
def numSquares_bfs(self, n):
"""bfs the q stores the intermediate result of sum of s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n):
"""static dp F_i = min(F_{i - j^2}+1, orall j) O(n), think it as a tree, cache tree O(m+n) = O(2n); rather than O(n sqrt(n)) backward"""
while len(Solution.F) <= n:
i = len(Solution.F)
Solution.F.append(sys.maxint)
j = 1
... | the_stack_v2_python_sparse | 279 Perfect Squares.py | Aminaba123/LeetCode | train | 1 | |
e3224eec60d4161ee553dc6a6a8d5e4399bd5740 | [
"testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',)\nwith capture_stdio() as out:\n extracted = next(extract_from_files(testfile, method_map=METHODS))\nself.assertTupleEqual(extracted, (testfile[0], 9, 'Mark it 8 Dude.', []))\nself.assertEqual(out[0], ' %s' % testfile)",
"base... | <|body_start_0|>
testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',)
with capture_stdio() as out:
extracted = next(extract_from_files(testfile, method_map=METHODS))
self.assertTupleEqual(extracted, (testfile[0], 9, 'Mark it 8 Dude.', []))
self.... | TestL10nExtract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestL10nExtract:
def test_extract_from_files(self):
"""Should be able to extract strings from a specific file."""
<|body_0|>
def test_extract_from_multiple_files(self):
"""Should be able to extract strings from specific files."""
<|body_1|>
def test_extr... | stack_v2_sparse_classes_36k_train_026487 | 14,956 | no_license | [
{
"docstring": "Should be able to extract strings from a specific file.",
"name": "test_extract_from_files",
"signature": "def test_extract_from_files(self)"
},
{
"docstring": "Should be able to extract strings from specific files.",
"name": "test_extract_from_multiple_files",
"signature... | 6 | null | Implement the Python class `TestL10nExtract` described below.
Class description:
Implement the TestL10nExtract class.
Method signatures and docstrings:
- def test_extract_from_files(self): Should be able to extract strings from a specific file.
- def test_extract_from_multiple_files(self): Should be able to extract s... | Implement the Python class `TestL10nExtract` described below.
Class description:
Implement the TestL10nExtract class.
Method signatures and docstrings:
- def test_extract_from_files(self): Should be able to extract strings from a specific file.
- def test_extract_from_multiple_files(self): Should be able to extract s... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class TestL10nExtract:
def test_extract_from_files(self):
"""Should be able to extract strings from a specific file."""
<|body_0|>
def test_extract_from_multiple_files(self):
"""Should be able to extract strings from specific files."""
<|body_1|>
def test_extr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestL10nExtract:
def test_extract_from_files(self):
"""Should be able to extract strings from a specific file."""
testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',)
with capture_stdio() as out:
extracted = next(extract_from_files(testfile, m... | the_stack_v2_python_sparse | ExtractFeatures/Data/thesantosh/test_commands.py | vivekaxl/LexisNexis | train | 9 | |
973a40652e5c5e3aea325fde003b2126279b6121 | [
"if x == 0:\n return 0\nif n == 0:\n return 1\nflag = 1 if n > 0 else 0\nn = abs(n)\nres = 1\ncurr = x\nwhile n:\n if n % 2 == 0:\n n = n // 2\n curr *= curr\n else:\n res *= curr\n n -= 1\nreturn res if flag else 1 / res",
"res = 1\ntemp = x\nflag = True if n > 0 else Fals... | <|body_start_0|>
if x == 0:
return 0
if n == 0:
return 1
flag = 1 if n > 0 else 0
n = abs(n)
res = 1
curr = x
while n:
if n % 2 == 0:
n = n // 2
curr *= curr
else:
res ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x, n):
"""循环实现快速幂"""
<|body_0|>
def myPow1(self, x, n):
"""位运算实现 例如 n = 13,则 n 的二进制表示为 1101, 那么 m 的 13 次方可以拆解为: m^1101 = m^0001 * m^0100 * m^1000。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x == 0:
retur... | stack_v2_sparse_classes_36k_train_026488 | 2,626 | no_license | [
{
"docstring": "循环实现快速幂",
"name": "myPow",
"signature": "def myPow(self, x, n)"
},
{
"docstring": "位运算实现 例如 n = 13,则 n 的二进制表示为 1101, 那么 m 的 13 次方可以拆解为: m^1101 = m^0001 * m^0100 * m^1000。",
"name": "myPow1",
"signature": "def myPow1(self, x, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): 循环实现快速幂
- def myPow1(self, x, n): 位运算实现 例如 n = 13,则 n 的二进制表示为 1101, 那么 m 的 13 次方可以拆解为: m^1101 = m^0001 * m^0100 * m^1000。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): 循环实现快速幂
- def myPow1(self, x, n): 位运算实现 例如 n = 13,则 n 的二进制表示为 1101, 那么 m 的 13 次方可以拆解为: m^1101 = m^0001 * m^0100 * m^1000。
<|skeleton|>
class Solution:
... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def myPow(self, x, n):
"""循环实现快速幂"""
<|body_0|>
def myPow1(self, x, n):
"""位运算实现 例如 n = 13,则 n 的二进制表示为 1101, 那么 m 的 13 次方可以拆解为: m^1101 = m^0001 * m^0100 * m^1000。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow(self, x, n):
"""循环实现快速幂"""
if x == 0:
return 0
if n == 0:
return 1
flag = 1 if n > 0 else 0
n = abs(n)
res = 1
curr = x
while n:
if n % 2 == 0:
n = n // 2
cur... | the_stack_v2_python_sparse | MathProblem/myPow.py | Philex5/codingPractice | train | 0 | |
62cc86a22190aff5e7b491f71e74a899453262d7 | [
"if treeNode is None:\n return\nself.postorderTraversalRecursion(treeNode.leftChild)\nself.postorderTraversalRecursion(treeNode.rightChild)\nprint(treeNode.data.data)",
"stack = []\nresult = []\nr = None\nwhile treeNode or stack:\n if treeNode:\n stack.append(treeNode)\n treeNode = treeNode.le... | <|body_start_0|>
if treeNode is None:
return
self.postorderTraversalRecursion(treeNode.leftChild)
self.postorderTraversalRecursion(treeNode.rightChild)
print(treeNode.data.data)
<|end_body_0|>
<|body_start_1|>
stack = []
result = []
r = None
w... | PostorderTraversal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostorderTraversal:
def postorderTraversalRecursion(self, treeNode):
"""后序遍历的递归实现 :param treeNode: :return:"""
<|body_0|>
def postorderTraversalNotRecursion(self, treeNode):
"""后序遍历的非递归实现 :param treeNode: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_026489 | 2,490 | no_license | [
{
"docstring": "后序遍历的递归实现 :param treeNode: :return:",
"name": "postorderTraversalRecursion",
"signature": "def postorderTraversalRecursion(self, treeNode)"
},
{
"docstring": "后序遍历的非递归实现 :param treeNode: :return:",
"name": "postorderTraversalNotRecursion",
"signature": "def postorderTrave... | 2 | null | Implement the Python class `PostorderTraversal` described below.
Class description:
Implement the PostorderTraversal class.
Method signatures and docstrings:
- def postorderTraversalRecursion(self, treeNode): 后序遍历的递归实现 :param treeNode: :return:
- def postorderTraversalNotRecursion(self, treeNode): 后序遍历的非递归实现 :param t... | Implement the Python class `PostorderTraversal` described below.
Class description:
Implement the PostorderTraversal class.
Method signatures and docstrings:
- def postorderTraversalRecursion(self, treeNode): 后序遍历的递归实现 :param treeNode: :return:
- def postorderTraversalNotRecursion(self, treeNode): 后序遍历的非递归实现 :param t... | cded97a52c422f98b55f2b3527a054d23541d5a4 | <|skeleton|>
class PostorderTraversal:
def postorderTraversalRecursion(self, treeNode):
"""后序遍历的递归实现 :param treeNode: :return:"""
<|body_0|>
def postorderTraversalNotRecursion(self, treeNode):
"""后序遍历的非递归实现 :param treeNode: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostorderTraversal:
def postorderTraversalRecursion(self, treeNode):
"""后序遍历的递归实现 :param treeNode: :return:"""
if treeNode is None:
return
self.postorderTraversalRecursion(treeNode.leftChild)
self.postorderTraversalRecursion(treeNode.rightChild)
print(treeNo... | the_stack_v2_python_sparse | chapter5/后序遍历.py | AnJian2020/Leetcode | train | 1 | |
9e7a89fecbe50bd2a53db7bdb11fd820767eb79e | [
"gdb = os.path.dirname(transit_fd)\nself.line_variant_elements = os.path.join(transit_fd, 'LineVariantElements')\nself.line_variants = os.path.join(gdb, 'LineVariants')\nself.lines = os.path.join(gdb, 'Lines')\nself.calendars = os.path.join(gdb, 'Calendars')\nself.calendar_exceptions = os.path.join(gdb, 'CalendarEx... | <|body_start_0|>
gdb = os.path.dirname(transit_fd)
self.line_variant_elements = os.path.join(transit_fd, 'LineVariantElements')
self.line_variants = os.path.join(gdb, 'LineVariants')
self.lines = os.path.join(gdb, 'Lines')
self.calendars = os.path.join(gdb, 'Calendars')
s... | Defines and validates the public transit data model as relevant to this tool. | TransitDataModel | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransitDataModel:
"""Defines and validates the public transit data model as relevant to this tool."""
def __init__(self, transit_fd: str):
"""Define the public transit data model as relevant to this tool."""
<|body_0|>
def validate_tables_exist(self):
"""Validate... | stack_v2_sparse_classes_36k_train_026490 | 41,059 | permissive | [
{
"docstring": "Define the public transit data model as relevant to this tool.",
"name": "__init__",
"signature": "def __init__(self, transit_fd: str)"
},
{
"docstring": "Validate that the required public transit data model feature classes and tables exist. Raises: TransitNetworkAnalysisToolsErr... | 3 | null | Implement the Python class `TransitDataModel` described below.
Class description:
Defines and validates the public transit data model as relevant to this tool.
Method signatures and docstrings:
- def __init__(self, transit_fd: str): Define the public transit data model as relevant to this tool.
- def validate_tables_... | Implement the Python class `TransitDataModel` described below.
Class description:
Defines and validates the public transit data model as relevant to this tool.
Method signatures and docstrings:
- def __init__(self, transit_fd: str): Define the public transit data model as relevant to this tool.
- def validate_tables_... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class TransitDataModel:
"""Defines and validates the public transit data model as relevant to this tool."""
def __init__(self, transit_fd: str):
"""Define the public transit data model as relevant to this tool."""
<|body_0|>
def validate_tables_exist(self):
"""Validate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransitDataModel:
"""Defines and validates the public transit data model as relevant to this tool."""
def __init__(self, transit_fd: str):
"""Define the public transit data model as relevant to this tool."""
gdb = os.path.dirname(transit_fd)
self.line_variant_elements = os.path.jo... | the_stack_v2_python_sparse | transit-network-analysis-tools/TransitTraversal.py | Esri/public-transit-tools | train | 155 |
3573dfda0110b4ce5554f97eee881b5b87387e2d | [
"workflow = cls()\nworkflow = cls._add_component(name=name, outline=outline, workflow=workflow)\nfor component in outline.components[name]:\n workflow = cls._add_component(name=component, outline=outline, workflow=workflow)\nreturn workflow",
"if any((k in workflow.components.keys() for k in self.components.ke... | <|body_start_0|>
workflow = cls()
workflow = cls._add_component(name=name, outline=outline, workflow=workflow)
for component in outline.components[name]:
workflow = cls._add_component(name=component, outline=outline, workflow=workflow)
return workflow
<|end_body_0|>
<|body_s... | Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. default (Any): default value to use when a key is missing and a new one is ... | Workflow | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workflow:
"""Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. default (Any): default value to use whe... | stack_v2_sparse_classes_36k_train_026491 | 14,889 | permissive | [
{
"docstring": "Creates a Workflow from an Outline. Args: outline (Outline): [description] name (str): [description] Returns: Workflow: [description]",
"name": "from_outline",
"signature": "def from_outline(cls, outline: Outline, name: str) -> Workflow"
},
{
"docstring": "Adds 'other' Workflow t... | 5 | stack_v2_sparse_classes_30k_train_002206 | Implement the Python class `Workflow` described below.
Class description:
Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. ... | Implement the Python class `Workflow` described below.
Class description:
Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. ... | 5302da8bf4944ac518d22cc37c181e5a09baaabe | <|skeleton|>
class Workflow:
"""Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. default (Any): default value to use whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Workflow:
"""Stores lightweight workflow and corresponding components. Args: contents (Dict[str, List[str]]): an adjacency list where the keys are the names of nodes and the values are names of nodes which the key is connected to. Defaults to an empty dict. default (Any): default value to use when a key is mi... | the_stack_v2_python_sparse | simplify/core/stages.py | WithPrecedent/simplify | train | 1 |
7f24f3721008d3199fa00097a9552a42b7291822 | [
"self.local_script_dir = local_script_dir(script_sdir)\nself.local_module_dir = local_module_dir(module_sdir)\nif debug_print_var is None:\n debug_print_var = '{0}_DEBUG_PRINT'.format(module_sdir.upper())\nself.debug_print = os.environ.get(debug_print_var, False)\nself.output_processor = output_processor",
"if... | <|body_start_0|>
self.local_script_dir = local_script_dir(script_sdir)
self.local_module_dir = local_module_dir(module_sdir)
if debug_print_var is None:
debug_print_var = '{0}_DEBUG_PRINT'.format(module_sdir.upper())
self.debug_print = os.environ.get(debug_print_var, False)
... | Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules. | ScriptRunner | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptRunner:
"""Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules."""
def __init__(self, script_sdir='scripts', module_sdir=MY_PACKAGE, debug_print_var=None, output_processor=lambd... | stack_v2_sparse_classes_36k_train_026492 | 10,021 | permissive | [
{
"docstring": "Init ScriptRunner instance Parameters ---------- script_sdir : str, optional Name of subdirectory in top-level directory (directory containing setup.py), to find scripts in development tree. Typically 'scripts', but might be 'bin'. module_sdir : str, optional Name of subdirectory in top-level di... | 2 | stack_v2_sparse_classes_30k_train_001439 | Implement the Python class `ScriptRunner` described below.
Class description:
Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules.
Method signatures and docstrings:
- def __init__(self, script_sdir='scripts', ... | Implement the Python class `ScriptRunner` described below.
Class description:
Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules.
Method signatures and docstrings:
- def __init__(self, script_sdir='scripts', ... | 763e0fccb23f3b3d1fe7812a50f5b3feda165307 | <|skeleton|>
class ScriptRunner:
"""Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules."""
def __init__(self, script_sdir='scripts', module_sdir=MY_PACKAGE, debug_print_var=None, output_processor=lambd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScriptRunner:
"""Class to run scripts and return output Finds local scripts and local modules if running in the development directory, otherwise finds system scripts and modules."""
def __init__(self, script_sdir='scripts', module_sdir=MY_PACKAGE, debug_print_var=None, output_processor=lambda x: x):
... | the_stack_v2_python_sparse | AFQ/utils/testing.py | yeatmanlab/pyAFQ | train | 49 |
e27f524b287f45bdacf68e26fc8e63fceee91e06 | [
"n = len(init_val)\nself.segfunc = segfunc\nself.ide_ele = ide_ele\nself.num = 1 << (n - 1).bit_length()\nself.tree = [ide_ele] * 2 * self.num\nfor i in range(n):\n self.tree[self.num + i] = init_val[i]\nfor i in range(self.num - 1, 0, -1):\n self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])... | <|body_start_0|>
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
... | init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN) | SegTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"... | stack_v2_sparse_classes_36k_train_026493 | 2,945 | no_license | [
{
"docstring": "init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)",
"name": "__init__",
"signature": "def __init__(self, init_val, segfunc, ide_ele)"
},
{
"docstring": "k番目の値をxに更新 k: index(0-index) x: update value",
"name": "update",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_012090 | Implement the Python class `SegTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide... | Implement the Python class `SegTree` described below.
Class description:
init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
Method signatures and docstrings:
- def __init__(self, init_val, segfunc, ide_ele): init_val: 配列の初期値 segfunc: 区間にしたい操作 ide... | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | <|skeleton|>
class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegTree:
"""init(init_val, ide_ele): 配列init_valで初期化 O(N) update(k, x): k番目の値をxに更新 O(logN) query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)"""
def __init__(self, init_val, segfunc, ide_ele):
"""init_val: 配列の初期値 segfunc: 区間にしたい操作 ide_ele: 単位元 n: 要素数 num: n以上の最小の2のべき乗 tree: セグメント木(1-index)"""
n ... | the_stack_v2_python_sparse | Python_codes/p03061/s654525017.py | Aasthaengg/IBMdataset | train | 0 |
600072b89775bb0d34f188522fd11dfb980e30ad | [
"assert pay_type in mc.PayType, f'pay_type: {pay_type}'\ninst = self.create(usrid=usrid, openid=openid, amount=amount, status=mc.PayStatus.Init.value, pay_type=pay_type, body=body, instid=instid)\ninst.init_trade_no()\ninst.launch_unified()\nreturn inst",
"pay_type = mc.PayType.Charge.value\ninst = self.add_unifi... | <|body_start_0|>
assert pay_type in mc.PayType, f'pay_type: {pay_type}'
inst = self.create(usrid=usrid, openid=openid, amount=amount, status=mc.PayStatus.Init.value, pay_type=pay_type, body=body, instid=instid)
inst.init_trade_no()
inst.launch_unified()
return inst
<|end_body_0|>... | WXPayManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WXPayManager:
def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0):
"""微信支付,统一下单"""
<|body_0|>
def add_charge_unifiedorder(self, usrid, openid, amount):
"""充值,统一下单"""
<|body_1|>
def add_paycall_unifiedorder(self, usrid, openid, ... | stack_v2_sparse_classes_36k_train_026494 | 7,338 | no_license | [
{
"docstring": "微信支付,统一下单",
"name": "add_unifiedorder",
"signature": "def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0)"
},
{
"docstring": "充值,统一下单",
"name": "add_charge_unifiedorder",
"signature": "def add_charge_unifiedorder(self, usrid, openid, amount)"
... | 4 | null | Implement the Python class `WXPayManager` described below.
Class description:
Implement the WXPayManager class.
Method signatures and docstrings:
- def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0): 微信支付,统一下单
- def add_charge_unifiedorder(self, usrid, openid, amount): 充值,统一下单
- def add_pa... | Implement the Python class `WXPayManager` described below.
Class description:
Implement the WXPayManager class.
Method signatures and docstrings:
- def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0): 微信支付,统一下单
- def add_charge_unifiedorder(self, usrid, openid, amount): 充值,统一下单
- def add_pa... | b7ed6588e13d2916a4162d56509d2794742a1eb1 | <|skeleton|>
class WXPayManager:
def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0):
"""微信支付,统一下单"""
<|body_0|>
def add_charge_unifiedorder(self, usrid, openid, amount):
"""充值,统一下单"""
<|body_1|>
def add_paycall_unifiedorder(self, usrid, openid, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WXPayManager:
def add_unifiedorder(self, usrid, openid, amount, pay_type, body='', instid=0):
"""微信支付,统一下单"""
assert pay_type in mc.PayType, f'pay_type: {pay_type}'
inst = self.create(usrid=usrid, openid=openid, amount=amount, status=mc.PayStatus.Init.value, pay_type=pay_type, body=bod... | the_stack_v2_python_sparse | server/applibs/billing/models/payment.py | fanshuai/kubrick | train | 0 | |
2e37d343c5800581dd8a087cdd226bb4f894b995 | [
"if not os.path.exists(directory):\n os.makedirs(directory)\ntry:\n with open(directory + '/' + filename, 'rb') as index_file:\n self._index = pickle.load(index_file)\nexcept:\n self._index = dict()\nself._filename = filename\nself._directory = directory",
"t_64bit_arr = np.vstack((t.times(), t.va... | <|body_start_0|>
if not os.path.exists(directory):
os.makedirs(directory)
try:
with open(directory + '/' + filename, 'rb') as index_file:
self._index = pickle.load(index_file)
except:
self._index = dict()
self._filename = filename
... | A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index.pkl'. directory: string (optional) Path to directory to which index file and time se... | FileStorageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileStorageManager:
"""A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index.pkl'. directory: string (optional) Pat... | stack_v2_sparse_classes_36k_train_026495 | 6,548 | no_license | [
{
"docstring": "Constructor for FileStorageManager. Initializes FileStorageManager with a pointer to a filename that stores the id and length of each time series, and to a directory containing the aforesaid file as well as data files of stored time series Parameters ---------- filename: string (optional) Name o... | 5 | stack_v2_sparse_classes_30k_train_021297 | Implement the Python class `FileStorageManager` described below.
Class description:
A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index... | Implement the Python class `FileStorageManager` described below.
Class description:
A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index... | 2b2bd35bc62942f5ea53fe8788e279b071e32c9f | <|skeleton|>
class FileStorageManager:
"""A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index.pkl'. directory: string (optional) Pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileStorageManager:
"""A file storage manager class that manages the persistent storage of our individual time series. Parameters ---------- filename: string (optional) Name of pickle file to stores the id and length of each time series. Default is 'ts_index.pkl'. directory: string (optional) Path to director... | the_stack_v2_python_sparse | timeseries/FileStorageManager.py | chinhuic/cs207project | train | 0 |
fb3c5a0fb33abafa27232d21560009704962d6e4 | [
"self.connected = False\nself.tmPacketData = None\nself.sendCyclic = False\nself.cyclicPeriodMs = int(UTIL.SYS.s_configuration.TM_CYCLIC_PERIOD_MS)\nself.obcAck1 = ENABLE_ACK\nself.obcAck2 = ENABLE_ACK\nself.obcAck3 = ENABLE_ACK\nself.obcAck4 = ENABLE_ACK\nself.obqAck1 = ENABLE_ACK\nself.obqAck2 = ENABLE_ACK\nself.... | <|body_start_0|>
self.connected = False
self.tmPacketData = None
self.sendCyclic = False
self.cyclicPeriodMs = int(UTIL.SYS.s_configuration.TM_CYCLIC_PERIOD_MS)
self.obcAck1 = ENABLE_ACK
self.obcAck2 = ENABLE_ACK
self.obcAck3 = ENABLE_ACK
self.obcAck4 = EN... | Configuration | Configuration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.conn... | stack_v2_sparse_classes_36k_train_026496 | 36,057 | permissive | [
{
"docstring": "Initialise the connection relevant informations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dumps the status of the configuration attributes",
"name": "dump",
"signature": "def dump(self)"
}
] | 2 | null | Implement the Python class `Configuration` described below.
Class description:
Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes | Implement the Python class `Configuration` described below.
Class description:
Configuration
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the configuration attributes
<|skeleton|>
class Configuration:
"""Configuratio... | c94415e9d85519f345fc56938198ac2537c0c6d0 | <|skeleton|>
class Configuration:
"""Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the configuration attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configuration:
"""Configuration"""
def __init__(self):
"""Initialise the connection relevant informations"""
self.connected = False
self.tmPacketData = None
self.sendCyclic = False
self.cyclicPeriodMs = int(UTIL.SYS.s_configuration.TM_CYCLIC_PERIOD_MS)
self... | the_stack_v2_python_sparse | SPACE/IF.py | khawatkom/SpacePyLibrary | train | 1 |
92baa7a659351e7b65a740d822cbfd51ae1a6e03 | [
"object = get_object_or_404(CallRegister, pk=id)\nform = CallRegisterForm(instance=object)\ncontext = {'object': object, 'form': form}\nreturn render(request, self.template_name, context)",
"form = CallRegisterForm(request.POST or None)\nif form.is_valid():\n object = get_object_or_404(CallRegister, pk=id)\n ... | <|body_start_0|>
object = get_object_or_404(CallRegister, pk=id)
form = CallRegisterForm(instance=object)
context = {'object': object, 'form': form}
return render(request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
form = CallRegisterForm(request.POST or None)
... | CallEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallEditView:
def get(self, request, id):
"""Returns single call data from db, appointment_date is passed into form to display as form only."""
<|body_0|>
def post(self, request, id):
"""Overrides all existing details of specific call, similar to call register."""
... | stack_v2_sparse_classes_36k_train_026497 | 8,699 | no_license | [
{
"docstring": "Returns single call data from db, appointment_date is passed into form to display as form only.",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "Overrides all existing details of specific call, similar to call register.",
"name": "post",
"sign... | 2 | stack_v2_sparse_classes_30k_train_021560 | Implement the Python class `CallEditView` described below.
Class description:
Implement the CallEditView class.
Method signatures and docstrings:
- def get(self, request, id): Returns single call data from db, appointment_date is passed into form to display as form only.
- def post(self, request, id): Overrides all e... | Implement the Python class `CallEditView` described below.
Class description:
Implement the CallEditView class.
Method signatures and docstrings:
- def get(self, request, id): Returns single call data from db, appointment_date is passed into form to display as form only.
- def post(self, request, id): Overrides all e... | bdd7c5ca9f00ce33be31609e5be9c2ccfcd8743a | <|skeleton|>
class CallEditView:
def get(self, request, id):
"""Returns single call data from db, appointment_date is passed into form to display as form only."""
<|body_0|>
def post(self, request, id):
"""Overrides all existing details of specific call, similar to call register."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallEditView:
def get(self, request, id):
"""Returns single call data from db, appointment_date is passed into form to display as form only."""
object = get_object_or_404(CallRegister, pk=id)
form = CallRegisterForm(instance=object)
context = {'object': object, 'form': form}
... | the_stack_v2_python_sparse | calls/views.py | mrmaheshrajput/htscrm | train | 0 | |
a4704e7c68fc14882c59a66a444b6bf88b988269 | [
"assert icon_style in IconFactory._convert_styles\nself._view = view\nself._icon_style = icon_style\nself._icon_factory = icon_factory\nself._name = name\nself._debug = debug",
"region, color = value\nicon_path = self._icon_factory.get_icon_path(self._icon_style, color)\nregion_key = GutterIconsColorHighlighter.r... | <|body_start_0|>
assert icon_style in IconFactory._convert_styles
self._view = view
self._icon_style = icon_style
self._icon_factory = icon_factory
self._name = name
self._debug = debug
<|end_body_0|>
<|body_start_1|>
region, color = value
icon_path = sel... | A color highlighter that uses gutter icons to highlight colors. | GutterIconsColorHighlighter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_36k_train_026498 | 7,583 | no_license | [
{
"docstring": "Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_factory - the icon factory to create icons with. - name - the name of the color highlighter. - debug - whether to enable debug mode.",
"name": "__init__",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_002163 | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | 83d469af3fc11d1aedb5193976ef84c59b595d6c | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_facto... | the_stack_v2_python_sparse | .config/sublime-text-2/Packages/Color Highlighter/gutter_icons_color_highlighter.py | Wallkerock/X-setup | train | 10 |
7c8a700d4083022e063b99d147673750f4bbba2e | [
"self.bot = bot\nself.permissions = Permissions()\nself.mod = Mod(bot)",
"warn_model = await WarningsModel.filter(guild_id=ctx.guild.id, member_id=member.id)\nif len(warn_model) in range(5, 8):\n await self.mod.mute_handler(ctx, [member], 600, f'Warning Count : {len(warn_model)}')\nif len(warn_model) in range(... | <|body_start_0|>
self.bot = bot
self.permissions = Permissions()
self.mod = Mod(bot)
<|end_body_0|>
<|body_start_1|>
warn_model = await WarningsModel.filter(guild_id=ctx.guild.id, member_id=member.id)
if len(warn_model) in range(5, 8):
await self.mod.mute_handler(ctx... | Warnings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Warnings:
def __init__(self, bot: Bot) -> None:
"""Init Function for the Cog"""
<|body_0|>
async def warning_count(self, ctx: commands.Context, member: Member) -> None:
"""Function that checks for amount of warnings"""
<|body_1|>
async def warn_command(s... | stack_v2_sparse_classes_36k_train_026499 | 5,995 | no_license | [
{
"docstring": "Init Function for the Cog",
"name": "__init__",
"signature": "def __init__(self, bot: Bot) -> None"
},
{
"docstring": "Function that checks for amount of warnings",
"name": "warning_count",
"signature": "async def warning_count(self, ctx: commands.Context, member: Member)... | 6 | stack_v2_sparse_classes_30k_train_007212 | Implement the Python class `Warnings` described below.
Class description:
Implement the Warnings class.
Method signatures and docstrings:
- def __init__(self, bot: Bot) -> None: Init Function for the Cog
- async def warning_count(self, ctx: commands.Context, member: Member) -> None: Function that checks for amount of... | Implement the Python class `Warnings` described below.
Class description:
Implement the Warnings class.
Method signatures and docstrings:
- def __init__(self, bot: Bot) -> None: Init Function for the Cog
- async def warning_count(self, ctx: commands.Context, member: Member) -> None: Function that checks for amount of... | 606b637cf953724fe94a1e71dc83bc7b92761a54 | <|skeleton|>
class Warnings:
def __init__(self, bot: Bot) -> None:
"""Init Function for the Cog"""
<|body_0|>
async def warning_count(self, ctx: commands.Context, member: Member) -> None:
"""Function that checks for amount of warnings"""
<|body_1|>
async def warn_command(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Warnings:
def __init__(self, bot: Bot) -> None:
"""Init Function for the Cog"""
self.bot = bot
self.permissions = Permissions()
self.mod = Mod(bot)
async def warning_count(self, ctx: commands.Context, member: Member) -> None:
"""Function that checks for amount of w... | the_stack_v2_python_sparse | zorander/cogs/warnings.py | thenishantsapkota/General-Purpose-Bot | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.