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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a919fa087cc7a8377d40e36aec7e5b51128711f5 | [
"self._num_or_size_splits = num_or_size_splits\nself._axis = axis\nsuper(Split, self).__init__()",
"ret = ListWrapper(tf.split(input, num_or_size_splits=self._num_or_size_splits, axis=self._axis))\nret._keras_mask = None\nreturn ret",
"if isinstance(self._num_or_size_splits, six.integer_types):\n shape = inp... | <|body_start_0|>
self._num_or_size_splits = num_or_size_splits
self._axis = axis
super(Split, self).__init__()
<|end_body_0|>
<|body_start_1|>
ret = ListWrapper(tf.split(input, num_or_size_splits=self._num_or_size_splits, axis=self._axis))
ret._keras_mask = None
return r... | Splits a tensor into sub tensors. | Split | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Split:
"""Splits a tensor into sub tensors."""
def __init__(self, num_or_size_splits, axis):
"""Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller tensors. This requires that `num_split` evenly divides `v... | stack_v2_sparse_classes_36k_train_001600 | 4,139 | permissive | [
{
"docstring": "Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller tensors. This requires that `num_split` evenly divides `value.shape[axis]`. If `num_or_size_splits` is a 1-D Tensor (or list), we call it `size_splits` and `input` i... | 4 | null | Implement the Python class `Split` described below.
Class description:
Splits a tensor into sub tensors.
Method signatures and docstrings:
- def __init__(self, num_or_size_splits, axis): Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller ... | Implement the Python class `Split` described below.
Class description:
Splits a tensor into sub tensors.
Method signatures and docstrings:
- def __init__(self, num_or_size_splits, axis): Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller ... | 38a3621337a030f74bb3944d7695e7642e777e10 | <|skeleton|>
class Split:
"""Splits a tensor into sub tensors."""
def __init__(self, num_or_size_splits, axis):
"""Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller tensors. This requires that `num_split` evenly divides `v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Split:
"""Splits a tensor into sub tensors."""
def __init__(self, num_or_size_splits, axis):
"""Create a Split layer. If `num_or_size_splits` is an integer, then `input` is split along dimension `axis` into `num_split` smaller tensors. This requires that `num_split` evenly divides `value.shape[ax... | the_stack_v2_python_sparse | alf/layers.py | Haichao-Zhang/alf | train | 1 |
c46cd6f88ac1ad3ab1d1c8a4d31b658af62a615e | [
"if len(nums) == 0:\n return None\nreturn self.helper(nums, 0, len(nums) - 1)",
"if start == end or end == -1:\n return TreeNode(nums[start])\nif start + 1 == end:\n node = TreeNode(nums[end])\n node.left = TreeNode(nums[start])\n return node\nmid = (start + end) / 2\nleft = self.helper(nums, start... | <|body_start_0|>
if len(nums) == 0:
return None
return self.helper(nums, 0, len(nums) - 1)
<|end_body_0|>
<|body_start_1|>
if start == end or end == -1:
return TreeNode(nums[start])
if start + 1 == end:
node = TreeNode(nums[end])
node.left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums):
""":type nums: List[int] :rtype: TreeNode"""
<|body_0|>
def helper(self, nums, start, end):
"""Convert nums[start ... end] to BST Base Case: start == end return TreeNode(nums[start]) start + 1 == end"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001601 | 1,152 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: TreeNode",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums)"
},
{
"docstring": "Convert nums[start ... end] to BST Base Case: start == end return TreeNode(nums[start]) start + 1 == end",
"name": "helper",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_003512 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode
- def helper(self, nums, start, end): Convert nums[start ... end] to BST Base Case: start == end return T... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode
- def helper(self, nums, start, end): Convert nums[start ... end] to BST Base Case: start == end return T... | 516b28a3df505b942098d91a4891e414f1c75c08 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums):
""":type nums: List[int] :rtype: TreeNode"""
<|body_0|>
def helper(self, nums, start, end):
"""Convert nums[start ... end] to BST Base Case: start == end return TreeNode(nums[start]) start + 1 == end"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedArrayToBST(self, nums):
""":type nums: List[int] :rtype: TreeNode"""
if len(nums) == 0:
return None
return self.helper(nums, 0, len(nums) - 1)
def helper(self, nums, start, end):
"""Convert nums[start ... end] to BST Base Case: start == end ... | the_stack_v2_python_sparse | Tree/108_sortedArr2BST.py | terylll/LeetCode | train | 0 | |
22913abe236b5415e625a0bfa6484ad9b965b5f6 | [
"args = self.path[1:].split('?')\nif self.path != '/' and args[0] not in self.server.dispatcher.methods.keys():\n self.send_error(404, 'Method not found: %s' % args[0])\nelse:\n if self.path == '/':\n response = self.server.dispatcher.wsdl()\n else:\n req, res, doc = self.server.dispatcher.he... | <|body_start_0|>
args = self.path[1:].split('?')
if self.path != '/' and args[0] not in self.server.dispatcher.methods.keys():
self.send_error(404, 'Method not found: %s' % args[0])
else:
if self.path == '/':
response = self.server.dispatcher.wsdl()
... | SOAPHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SOAPHandler:
def do_GET(self):
"""User viewable help information and wsdl"""
<|body_0|>
def do_POST(self):
"""SOAP POST gateway"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = self.path[1:].split('?')
if self.path != '/' and args[0] n... | stack_v2_sparse_classes_36k_train_001602 | 24,064 | permissive | [
{
"docstring": "User viewable help information and wsdl",
"name": "do_GET",
"signature": "def do_GET(self)"
},
{
"docstring": "SOAP POST gateway",
"name": "do_POST",
"signature": "def do_POST(self)"
}
] | 2 | null | Implement the Python class `SOAPHandler` described below.
Class description:
Implement the SOAPHandler class.
Method signatures and docstrings:
- def do_GET(self): User viewable help information and wsdl
- def do_POST(self): SOAP POST gateway | Implement the Python class `SOAPHandler` described below.
Class description:
Implement the SOAPHandler class.
Method signatures and docstrings:
- def do_GET(self): User viewable help information and wsdl
- def do_POST(self): SOAP POST gateway
<|skeleton|>
class SOAPHandler:
def do_GET(self):
"""User vie... | 018c82af46845315795c67c36801e2a128f515d5 | <|skeleton|>
class SOAPHandler:
def do_GET(self):
"""User viewable help information and wsdl"""
<|body_0|>
def do_POST(self):
"""SOAP POST gateway"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SOAPHandler:
def do_GET(self):
"""User viewable help information and wsdl"""
args = self.path[1:].split('?')
if self.path != '/' and args[0] not in self.server.dispatcher.methods.keys():
self.send_error(404, 'Method not found: %s' % args[0])
else:
if sel... | the_stack_v2_python_sparse | libs/gluon/contrib/pysimplesoap/server.py | operepo/ope | train | 12 | |
ca48c98bee86a9b6c18cb1660d720a6f7a2a7b2c | [
"if not matrix or not matrix[0]:\n return\nself.matrix = matrix\nself.colsums = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix) + 1)]\nfor i in range(1, len(matrix) + 1):\n for j in range(len(matrix[0])):\n self.colsums[i][j] = self.colsums[i - 1][j] + self.matrix[i - 1][j]",
"diff = v... | <|body_start_0|>
if not matrix or not matrix[0]:
return
self.matrix = matrix
self.colsums = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix) + 1)]
for i in range(1, len(matrix) + 1):
for j in range(len(matrix[0])):
self.colsums[i][j] ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k_train_001603 | 1,381 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | 14dcf9029486283b5e4685d95ebfe9979ade03c3 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix or not matrix[0]:
return
self.matrix = matrix
self.colsums = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix) + 1)]
for i in range(1, len(matrix) + 1):
... | the_stack_v2_python_sparse | 308-RangeSumQuery2D-Mutable.py | dq-code/leetcode | train | 0 | |
bb4ff44961b1f4f7f8c0acd86a4c99f12f4b84c9 | [
"if isinstance(exc, NotImplementedError):\n return self._make_error_response(400, str(exc))\nif isinstance(exc, ItemNotFoundError):\n return self._make_error_response(400, str(exc))\nreturn super().handle_exception(exc)",
"course_key = CourseKey.from_string(course_id)\nif not has_studio_write_access(request... | <|body_start_0|>
if isinstance(exc, NotImplementedError):
return self._make_error_response(400, str(exc))
if isinstance(exc, ItemNotFoundError):
return self._make_error_response(400, str(exc))
return super().handle_exception(exc)
<|end_body_0|>
<|body_start_1|>
c... | API view for course tabs settings. | CourseTabSettingsView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseTabSettingsView:
"""API view for course tabs settings."""
def handle_exception(self, exc):
"""Handle NotImplementedError and return a proper response for it."""
<|body_0|>
def post(self, request: Request, course_id: str) -> Response:
"""Change visibility of... | stack_v2_sparse_classes_36k_train_001604 | 8,341 | permissive | [
{
"docstring": "Handle NotImplementedError and return a proper response for it.",
"name": "handle_exception",
"signature": "def handle_exception(self, exc)"
},
{
"docstring": "Change visibility of tabs in a course. **Example Requests** You can provide either a tab_id or a tab_location. Hide a co... | 2 | null | Implement the Python class `CourseTabSettingsView` described below.
Class description:
API view for course tabs settings.
Method signatures and docstrings:
- def handle_exception(self, exc): Handle NotImplementedError and return a proper response for it.
- def post(self, request: Request, course_id: str) -> Response:... | Implement the Python class `CourseTabSettingsView` described below.
Class description:
API view for course tabs settings.
Method signatures and docstrings:
- def handle_exception(self, exc): Handle NotImplementedError and return a proper response for it.
- def post(self, request: Request, course_id: str) -> Response:... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CourseTabSettingsView:
"""API view for course tabs settings."""
def handle_exception(self, exc):
"""Handle NotImplementedError and return a proper response for it."""
<|body_0|>
def post(self, request: Request, course_id: str) -> Response:
"""Change visibility of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseTabSettingsView:
"""API view for course tabs settings."""
def handle_exception(self, exc):
"""Handle NotImplementedError and return a proper response for it."""
if isinstance(exc, NotImplementedError):
return self._make_error_response(400, str(exc))
if isinstance... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/djangoapps/contentstore/rest_api/v0/views/tabs.py | luque/better-ways-of-thinking-about-software | train | 3 |
9adc96bd7b6fdb25b973a79394ce1289b5c0300d | [
"super(SimGNN, self).__init__()\nself.args = args\nself.number_labels = number_of_labels\nself.setup_layers()",
"if self.args.histogram == True:\n self.feature_count = self.args.tensor_neurons + self.args.bins\nelse:\n self.feature_count = self.args.tensor_neurons",
"self.calculate_bottleneck_features()\n... | <|body_start_0|>
super(SimGNN, self).__init__()
self.args = args
self.number_labels = number_of_labels
self.setup_layers()
<|end_body_0|>
<|body_start_1|>
if self.args.histogram == True:
self.feature_count = self.args.tensor_neurons + self.args.bins
else:
... | SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689 | SimGNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
<|body_0|>
def calculate... | stack_v2_sparse_classes_36k_train_001605 | 8,576 | no_license | [
{
"docstring": ":param args: Arguments object. :param number_of_labels: Number of node labels.",
"name": "__init__",
"signature": "def __init__(self, args, number_of_labels)"
},
{
"docstring": "Deciding the shape of the bottleneck layer.",
"name": "calculate_bottleneck_features",
"signat... | 6 | stack_v2_sparse_classes_30k_train_002375 | Implement the Python class `SimGNN` described below.
Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689
Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number... | Implement the Python class `SimGNN` described below.
Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689
Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
<|body_0|>
def calculate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimGNN:
"""SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""
def __init__(self, args, number_of_labels):
""":param args: Arguments object. :param number_of_labels: Number of node labels."""
super(SimGNN, self).__init__()
sel... | the_stack_v2_python_sparse | generated/test_benedekrozemberczki_SimGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
de2941373c627b0f71a510aad1ee3b2e8adf99c3 | [
"super(Decoder, self).__init__()\nself.input_size = input_size\nself.latent_size = latent_size\nself.class_size = class_size\nself.hidden_dim = 51200\nself.enc_cfg = enc_cfg\nself.fc1 = nn.Sequential(nn.Linear(self.latent_dim, self.hidden_dim), nn.ReLU(), Reshape())\nself.cnn1 = nn.Sequential(nn.ConvTranspose2d(sel... | <|body_start_0|>
super(Decoder, self).__init__()
self.input_size = input_size
self.latent_size = latent_size
self.class_size = class_size
self.hidden_dim = 51200
self.enc_cfg = enc_cfg
self.fc1 = nn.Sequential(nn.Linear(self.latent_dim, self.hidden_dim), nn.ReLU()... | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
def __init__(self, input_size, latent_size, class_size, dec_cfg):
"""Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config class"""
<|body_0|>
def forward(self, z):
"""forward pass for the decoder N... | stack_v2_sparse_classes_36k_train_001606 | 4,969 | no_license | [
{
"docstring": "Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config class",
"name": "__init__",
"signature": "def __init__(self, input_size, latent_size, class_size, dec_cfg)"
},
{
"docstring": "forward pass for the decoder Note : the... | 2 | stack_v2_sparse_classes_30k_train_003599 | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, input_size, latent_size, class_size, dec_cfg): Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config ... | Implement the Python class `Decoder` described below.
Class description:
Implement the Decoder class.
Method signatures and docstrings:
- def __init__(self, input_size, latent_size, class_size, dec_cfg): Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config ... | b134e4e6b1e6c110fad8cb38b033c92c34d3c8ce | <|skeleton|>
class Decoder:
def __init__(self, input_size, latent_size, class_size, dec_cfg):
"""Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config class"""
<|body_0|>
def forward(self, z):
"""forward pass for the decoder N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
def __init__(self, input_size, latent_size, class_size, dec_cfg):
"""Calculates p(x|x) from the latent representation input size : latent_dim dec_cfg : Class object of Encoder Config class"""
super(Decoder, self).__init__()
self.input_size = input_size
self.latent_size... | the_stack_v2_python_sparse | architectures_networks/Adversarial_Autoencoders/model.py | shubham14/Machine_learning_research | train | 3 | |
eb640963f9ed25f83d8df1698d6f0f5713419449 | [
"if 'modifier' in kwargs:\n self.modifier = kwargs['modifier']\nelif len(args) > 2:\n self.modifier = args[2]\n args = args[:2]\nelse:\n self.modifier = lambda x: x\nif not six.callable(self.modifier):\n raise TypeError('itermod(o, modifier): modifier must be callable')\nsuper(itermod, self).__init__... | <|body_start_0|>
if 'modifier' in kwargs:
self.modifier = kwargs['modifier']
elif len(args) > 2:
self.modifier = args[2]
args = args[:2]
else:
self.modifier = lambda x: x
if not six.callable(self.modifier):
raise TypeError('iter... | An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a, modifier=modifier): ... print('"%s"' % s) "A list" "of strings" "without... | itermod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class itermod:
"""An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a, modifier=modifier): ... print('"%s"' ... | stack_v2_sparse_classes_36k_train_001607 | 8,468 | permissive | [
{
"docstring": "__init__(o, sentinel=None, modifier=lambda x: x)",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Cache `n` modified items. If `n` is 0 or None, 1 item is cached. Each item returned by the iterator is passed through the `itermod.modified... | 2 | stack_v2_sparse_classes_30k_train_012454 | Implement the Python class `itermod` described below.
Class description:
An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a... | Implement the Python class `itermod` described below.
Class description:
An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a... | 05dbd4575d01a213f3f4d69aa4968473f2536142 | <|skeleton|>
class itermod:
"""An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a, modifier=modifier): ... print('"%s"' ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class itermod:
"""An iterator object that supports modifying items as they are returned. >>> a = [" A list ", ... " of strings ", ... " with ", ... " extra ", ... " whitespace. "] >>> modifier = lambda s: s.strip().replace('with', 'without') >>> for s in itermod(a, modifier=modifier): ... print('"%s"' % s) "A list"... | the_stack_v2_python_sparse | python/helpers/pockets/iterators.py | JetBrains/intellij-community | train | 16,288 |
befc15d5b868844c8667330a7cc64f7966c65520 | [
"self.program = []\nfor line in self.lines:\n stripped_line = line.strip()\n if stripped_line.startswith('#ip '):\n self.ip_reg = int(stripped_line[len('#ip '):])\n elif stripped_line:\n tokens = stripped_line.split(' ')\n instruction = [tokens[0]] + [int(token) for token in tokens[1:]... | <|body_start_0|>
self.program = []
for line in self.lines:
stripped_line = line.strip()
if stripped_line.startswith('#ip '):
self.ip_reg = int(stripped_line[len('#ip '):])
elif stripped_line:
tokens = stripped_line.split(' ')
... | Day 16 challenges | Challenge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
<|body_0|>
def execute_program(self, emulator, callback=None, ip=0):
"""Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to ... | stack_v2_sparse_classes_36k_train_001608 | 4,881 | permissive | [
{
"docstring": "Parse input lines",
"name": "parse_input",
"signature": "def parse_input(self)"
},
{
"docstring": "Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to call after each instruction with the current IP ip: initial instruction ... | 4 | stack_v2_sparse_classes_30k_train_019675 | Implement the Python class `Challenge` described below.
Class description:
Day 16 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input lines
- def execute_program(self, emulator, callback=None, ip=0): Execute the program on the given emulator emulator: The emulator to run the program on c... | Implement the Python class `Challenge` described below.
Class description:
Day 16 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input lines
- def execute_program(self, emulator, callback=None, ip=0): Execute the program on the given emulator emulator: The emulator to run the program on c... | 6671ef8c16a837f697bb3fb91004d1bd892814ba | <|skeleton|>
class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
<|body_0|>
def execute_program(self, emulator, callback=None, ip=0):
"""Execute the program on the given emulator emulator: The emulator to run the program on callback: Function to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Challenge:
"""Day 16 challenges"""
def parse_input(self):
"""Parse input lines"""
self.program = []
for line in self.lines:
stripped_line = line.strip()
if stripped_line.startswith('#ip '):
self.ip_reg = int(stripped_line[len('#ip '):])
... | the_stack_v2_python_sparse | 2018/day19/challenge.py | ericgreveson/adventofcode | train | 0 |
df319308ea8675edbed5650bdf45b3daa3e6e77a | [
"if os.path.exists(Path):\n try:\n self.data = xlrd.open_workbook(Path)\n self.tabale_list = self.data.sheet_names()\n except:\n raise print('这个地址不是一个excle文件!!!\\n')\nelse:\n raise print('地址不存在!!!\\n')",
"if way == 1:\n try:\n self.table = self.data.sheet_by_name(IndexOrNam... | <|body_start_0|>
if os.path.exists(Path):
try:
self.data = xlrd.open_workbook(Path)
self.tabale_list = self.data.sheet_names()
except:
raise print('这个地址不是一个excle文件!!!\n')
else:
raise print('地址不存在!!!\n')
<|end_body_0|>
<... | Excel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Excel:
def __init__(self, Path):
"""传入文件地址,判断文件地址是否存在"""
<|body_0|>
def GetTable(self, IndexOrName, way=1):
"""传入下标索引index或者表格名字name返回表格数据,默认按照名字传入"""
<|body_1|>
def ReadRowsTable(self, IndexOrName, way=1):
"""按照表index和name一行一行读取返回读取列表Value_list"... | stack_v2_sparse_classes_36k_train_001609 | 1,851 | no_license | [
{
"docstring": "传入文件地址,判断文件地址是否存在",
"name": "__init__",
"signature": "def __init__(self, Path)"
},
{
"docstring": "传入下标索引index或者表格名字name返回表格数据,默认按照名字传入",
"name": "GetTable",
"signature": "def GetTable(self, IndexOrName, way=1)"
},
{
"docstring": "按照表index和name一行一行读取返回读取列表Value_li... | 4 | stack_v2_sparse_classes_30k_train_013032 | Implement the Python class `Excel` described below.
Class description:
Implement the Excel class.
Method signatures and docstrings:
- def __init__(self, Path): 传入文件地址,判断文件地址是否存在
- def GetTable(self, IndexOrName, way=1): 传入下标索引index或者表格名字name返回表格数据,默认按照名字传入
- def ReadRowsTable(self, IndexOrName, way=1): 按照表index和name一... | Implement the Python class `Excel` described below.
Class description:
Implement the Excel class.
Method signatures and docstrings:
- def __init__(self, Path): 传入文件地址,判断文件地址是否存在
- def GetTable(self, IndexOrName, way=1): 传入下标索引index或者表格名字name返回表格数据,默认按照名字传入
- def ReadRowsTable(self, IndexOrName, way=1): 按照表index和name一... | 365b490615f44de9e4eb317942404b0367ddb158 | <|skeleton|>
class Excel:
def __init__(self, Path):
"""传入文件地址,判断文件地址是否存在"""
<|body_0|>
def GetTable(self, IndexOrName, way=1):
"""传入下标索引index或者表格名字name返回表格数据,默认按照名字传入"""
<|body_1|>
def ReadRowsTable(self, IndexOrName, way=1):
"""按照表index和name一行一行读取返回读取列表Value_list"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Excel:
def __init__(self, Path):
"""传入文件地址,判断文件地址是否存在"""
if os.path.exists(Path):
try:
self.data = xlrd.open_workbook(Path)
self.tabale_list = self.data.sheet_names()
except:
raise print('这个地址不是一个excle文件!!!\n')
els... | the_stack_v2_python_sparse | TestRobotFrameworkApp/Auto_testing_comm_platform/Comm/DateDriver.py | wanhouchao/CloudsReconstruction | train | 0 | |
392ea7b270c0c0b18eddcf6d29a3368ea18ea472 | [
"self.auto_lock_duration_usecs = auto_lock_duration_usecs\nself.default_retention_duration_usecs = default_retention_duration_usecs\nself.hold_timestamp_usecs = hold_timestamp_usecs\nself.max_retention_duration_usecs = max_retention_duration_usecs\nself.min_retention_duration_usecs = min_retention_duration_usecs\ns... | <|body_start_0|>
self.auto_lock_duration_usecs = auto_lock_duration_usecs
self.default_retention_duration_usecs = default_retention_duration_usecs
self.hold_timestamp_usecs = hold_timestamp_usecs
self.max_retention_duration_usecs = max_retention_duration_usecs
self.min_retention_... | Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in the filesystem if they have not been modified for an administrator-specified period of time. When the auto-l... | ViewIdMappingProto_FileLevelDataLockConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewIdMappingProto_FileLevelDataLockConfig:
"""Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in the filesystem if they have not been m... | stack_v2_sparse_classes_36k_train_001610 | 5,456 | permissive | [
{
"docstring": "Constructor for the ViewIdMappingProto_FileLevelDataLockConfig class",
"name": "__init__",
"signature": "def __init__(self, auto_lock_duration_usecs=None, default_retention_duration_usecs=None, hold_timestamp_usecs=None, max_retention_duration_usecs=None, min_retention_duration_usecs=Non... | 2 | stack_v2_sparse_classes_30k_train_004618 | Implement the Python class `ViewIdMappingProto_FileLevelDataLockConfig` described below.
Class description:
Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in... | Implement the Python class `ViewIdMappingProto_FileLevelDataLockConfig` described below.
Class description:
Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class ViewIdMappingProto_FileLevelDataLockConfig:
"""Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in the filesystem if they have not been m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewIdMappingProto_FileLevelDataLockConfig:
"""Implementation of the 'ViewIdMappingProto_FileLevelDataLockConfig' model. TODO: Type model description here. Attributes: auto_lock_duration_usecs (long|int): Auto-lock automatically commit files to WORM state in the filesystem if they have not been modified for a... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_id_mapping_proto_file_level_data_lock_config.py | hsantoyo2/management-sdk-python | train | 0 |
b21d60fd3ada9c1d02c15c2d11bb5f6e34ce807b | [
"cont_features = [tf.contrib.layers.real_valued_column('feature', dimension=4)]\nclassifier = tf.contrib.learn.DNNClassifier(n_classes=3, feature_columns=cont_features, hidden_units=[3, 3])\nclassifier.fit(input_fn=_iris_input_fn, steps=1000)\nclassifier.evaluate(input_fn=_iris_input_fn, steps=100)\nself.assertTrue... | <|body_start_0|>
cont_features = [tf.contrib.layers.real_valued_column('feature', dimension=4)]
classifier = tf.contrib.learn.DNNClassifier(n_classes=3, feature_columns=cont_features, hidden_units=[3, 3])
classifier.fit(input_fn=_iris_input_fn, steps=1000)
classifier.evaluate(input_fn=_i... | DNNClassifierTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNNClassifierTest:
def testMultiClass(self):
"""Tests multi-class classification using matrix data as input."""
<|body_0|>
def testDisableCenteredBias(self):
"""Tests that we can disable centered bias."""
<|body_1|>
def testSklearnCompatibility(self):
... | stack_v2_sparse_classes_36k_train_001611 | 4,619 | permissive | [
{
"docstring": "Tests multi-class classification using matrix data as input.",
"name": "testMultiClass",
"signature": "def testMultiClass(self)"
},
{
"docstring": "Tests that we can disable centered bias.",
"name": "testDisableCenteredBias",
"signature": "def testDisableCenteredBias(self... | 3 | null | Implement the Python class `DNNClassifierTest` described below.
Class description:
Implement the DNNClassifierTest class.
Method signatures and docstrings:
- def testMultiClass(self): Tests multi-class classification using matrix data as input.
- def testDisableCenteredBias(self): Tests that we can disable centered b... | Implement the Python class `DNNClassifierTest` described below.
Class description:
Implement the DNNClassifierTest class.
Method signatures and docstrings:
- def testMultiClass(self): Tests multi-class classification using matrix data as input.
- def testDisableCenteredBias(self): Tests that we can disable centered b... | 6d39eeb66c63a6f0f7895befc588c9eb1dd105f9 | <|skeleton|>
class DNNClassifierTest:
def testMultiClass(self):
"""Tests multi-class classification using matrix data as input."""
<|body_0|>
def testDisableCenteredBias(self):
"""Tests that we can disable centered bias."""
<|body_1|>
def testSklearnCompatibility(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DNNClassifierTest:
def testMultiClass(self):
"""Tests multi-class classification using matrix data as input."""
cont_features = [tf.contrib.layers.real_valued_column('feature', dimension=4)]
classifier = tf.contrib.learn.DNNClassifier(n_classes=3, feature_columns=cont_features, hidden_... | the_stack_v2_python_sparse | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn_test.py | Lab603/PicEncyclopedias | train | 6 | |
952e448aff6e98000cc42eb7a9cfe4bd7e912942 | [
"project = Project.query.get(pid)\nuser = helpers.abort_if_unauthorized(project)\nhelpers.abort_if_project_member(user, pid)\nmembership = Membership.join_project(user.id, pid)\nreturn custom_response(200, data=ProjectMember().dump(membership))",
"project = Project.query.get(pid)\nuser = helpers.abort_if_unauthor... | <|body_start_0|>
project = Project.query.get(pid)
user = helpers.abort_if_unauthorized(project)
helpers.abort_if_project_member(user, pid)
membership = Membership.join_project(user.id, pid)
return custom_response(200, data=ProjectMember().dump(membership))
<|end_body_0|>
<|body_... | Mapped to: /api/project/<int:id>/membership/ | ProjectMembership | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
<|body_0|>
def delete(self, pid):
"""Leaves a project for a given user (determined through JWT ... | stack_v2_sparse_classes_36k_train_001612 | 8,130 | no_license | [
{
"docstring": "Joins a public project for a given user (determined through JWT token)",
"name": "post",
"signature": "def post(self, pid)"
},
{
"docstring": "Leaves a project for a given user (determined through JWT token)",
"name": "delete",
"signature": "def delete(self, pid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000022 | Implement the Python class `ProjectMembership` described below.
Class description:
Mapped to: /api/project/<int:id>/membership/
Method signatures and docstrings:
- def post(self, pid): Joins a public project for a given user (determined through JWT token)
- def delete(self, pid): Leaves a project for a given user (de... | Implement the Python class `ProjectMembership` described below.
Class description:
Mapped to: /api/project/<int:id>/membership/
Method signatures and docstrings:
- def post(self, pid): Joins a public project for a given user (determined through JWT token)
- def delete(self, pid): Leaves a project for a given user (de... | 716fa5a6e905380cb206c57868e87556805f2b7f | <|skeleton|>
class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
<|body_0|>
def delete(self, pid):
"""Leaves a project for a given user (determined through JWT ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
project = Project.query.get(pid)
user = helpers.abort_if_unauthorized(project)
helpers.abort_if_project_m... | the_stack_v2_python_sparse | gabber/api/membership.py | joseplj/GabberAPI | train | 0 |
1a98cc9ab99016897fb2d2a97ac2904ffffa5978 | [
"filename = 'rented_items.csv'\nfile = open(filename, 'a')\nfile.close()\nwith open('test_items.csv', 'a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(['LR04', 'Leather Sofa', 25.0])\n writer.writerow(['KT78', 'Kitchen Tablee', 10.0])\n writer.writerow(['BR02', 'Queen Mattress', 1... | <|body_start_0|>
filename = 'rented_items.csv'
file = open(filename, 'a')
file.close()
with open('test_items.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['LR04', 'Leather Sofa', 25.0])
writer.writerow(['KT78', 'Kitchen Tab... | Tests the inventory functionalities | TestInventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
<|body_0|>
def tearDown(self):
"""Tears down all creations for testing"""
<|body_1|>
def test_add_furniture(self):
"""test to ... | stack_v2_sparse_classes_36k_train_001613 | 2,415 | no_license | [
{
"docstring": "Sets up the environment for testing",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tears down all creations for testing",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "test to make sure an entry is added to the file... | 4 | stack_v2_sparse_classes_30k_train_010252 | Implement the Python class `TestInventory` described below.
Class description:
Tests the inventory functionalities
Method signatures and docstrings:
- def setUp(self): Sets up the environment for testing
- def tearDown(self): Tears down all creations for testing
- def test_add_furniture(self): test to make sure an en... | Implement the Python class `TestInventory` described below.
Class description:
Tests the inventory functionalities
Method signatures and docstrings:
- def setUp(self): Sets up the environment for testing
- def tearDown(self): Tears down all creations for testing
- def test_add_furniture(self): test to make sure an en... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
<|body_0|>
def tearDown(self):
"""Tears down all creations for testing"""
<|body_1|>
def test_add_furniture(self):
"""test to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestInventory:
"""Tests the inventory functionalities"""
def setUp(self):
"""Sets up the environment for testing"""
filename = 'rented_items.csv'
file = open(filename, 'a')
file.close()
with open('test_items.csv', 'a', newline='') as file:
writer = csv.... | the_stack_v2_python_sparse | students/humberto_gonzalez/lesson08/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
85979dcc8010de3f92d584613cbbf7816d814dd1 | [
"n = len(dp)\ncur_len = max(dp)\nans = []\nfor i in range(n - 1, -1, -1):\n if dp[i] == cur_len:\n ans.append(nums[i])\n cur_len -= 1\n if cur_len == 0:\n break\nreturn ans[::-1]",
"n = len(nums)\nif n == 0:\n return 0\ndp = [1] * n\nfor i in range(1, n):\n for j in range(... | <|body_start_0|>
n = len(dp)
cur_len = max(dp)
ans = []
for i in range(n - 1, -1, -1):
if dp[i] == cur_len:
ans.append(nums[i])
cur_len -= 1
if cur_len == 0:
break
return ans[::-1]
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j])... | stack_v2_sparse_classes_36k_train_001614 | 1,538 | no_license | [
{
"docstring": "获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去",
"name": "get_one_LIS",
"signature": "def get_one_LIS(self, dp)"
},
{
"docstring": "最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j]) +1, 如果 nums[j] < nums[i] 严格上升",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_one_LIS(self, dp): 获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去
- def lengthOfLIS(self, nums: List[int]) -> int: 最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_one_LIS(self, dp): 获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去
- def lengthOfLIS(self, nums: List[int]) -> int: 最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指... | 4ca0ec2ab9510b12b7e8c65af52dee719f099ea6 | <|skeleton|>
class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""最长上升子序列, 不要求连续 dp[i]: 以 nums[i] 结尾的 LIS 长度 注意:指的是 nums[i] 作为最大元素的情况,因为 状态转移 状态转移: 0<=j < i dp[i] = max(d[j])... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_one_LIS(self, dp):
"""获得任意一个 LIS dp[i] 其实记录了 每个元素 在 LIS 序列中的位置,可以按照值的大小反向找回去"""
n = len(dp)
cur_len = max(dp)
ans = []
for i in range(n - 1, -1, -1):
if dp[i] == cur_len:
ans.append(nums[i])
cur_len -= 1
... | the_stack_v2_python_sparse | case/dp/最长上升子序列.py | JDer-liuodngkai/LeetCode | train | 0 | |
209ce48efef287bfb845792fc3b3b11d966944b3 | [
"last, now = (0, 0)\nfor i in nums:\n last, now = (now, max(last + i, now))\nreturn now",
"from __builtin__ import xrange\neven_sum = odd_sum = 0\nfor i in xrange(0, len(nums), 2):\n even_sum += nums[i]\nfor i in xrange(1, len(nums), 2):\n odd_sum += nums[i]\nreturn max(even_sum, odd_sum)",
"prev = cur... | <|body_start_0|>
last, now = (0, 0)
for i in nums:
last, now = (now, max(last + i, now))
return now
<|end_body_0|>
<|body_start_1|>
from __builtin__ import xrange
even_sum = odd_sum = 0
for i in xrange(0, len(nums), 2):
even_sum += nums[i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )"""
<|body_0|>
def wrong(self, nums):
""":type nums: List[int] :rtype: int O(n) 不是算奇數偶數和..."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_001615 | 2,079 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int O(n) 不是算奇數偶數和...",
"name": "wrong",
"signature": "de... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )
- def wrong(self, nums): :type nums: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )
- def wrong(self, nums): :type nums: List[... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )"""
<|body_0|>
def wrong(self, nums):
""":type nums: List[int] :rtype: int O(n) 不是算奇數偶數和..."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max( f(k-2) + nums[k], f(k-1) )"""
last, now = (0, 0)
for i in nums:
last, now = (now, max(last + i, now))
return now
def wrong(self, nums):
... | the_stack_v2_python_sparse | co_ms/198_House_Robber.py | vsdrun/lc_public | train | 6 | |
5a1159fa16184c1d4523c5400782b40a1a23eef0 | [
"if not data:\n app_log.info('data is null')\n return\nif 'destination' not in river_config:\n app_log.warning(\"The test_river doesn't have destination, river_config={0}\".format(river_config))\n return\ndestination_config_list = river_config['destination']\nfor destination_config in destination_config... | <|body_start_0|>
if not data:
app_log.info('data is null')
return
if 'destination' not in river_config:
app_log.warning("The test_river doesn't have destination, river_config={0}".format(river_config))
return
destination_config_list = river_config[... | DestinationHelp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestinationHelp:
def push(self, river_config, data):
"""将数据推到目的地 :param river_config: :param data: :return:"""
<|body_0|>
def clear(self, river_config, data):
"""清除掉所有数据 :param river_config: :param data: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_001616 | 12,159 | permissive | [
{
"docstring": "将数据推到目的地 :param river_config: :param data: :return:",
"name": "push",
"signature": "def push(self, river_config, data)"
},
{
"docstring": "清除掉所有数据 :param river_config: :param data: :return:",
"name": "clear",
"signature": "def clear(self, river_config, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017276 | Implement the Python class `DestinationHelp` described below.
Class description:
Implement the DestinationHelp class.
Method signatures and docstrings:
- def push(self, river_config, data): 将数据推到目的地 :param river_config: :param data: :return:
- def clear(self, river_config, data): 清除掉所有数据 :param river_config: :param d... | Implement the Python class `DestinationHelp` described below.
Class description:
Implement the DestinationHelp class.
Method signatures and docstrings:
- def push(self, river_config, data): 将数据推到目的地 :param river_config: :param data: :return:
- def clear(self, river_config, data): 清除掉所有数据 :param river_config: :param d... | a72b4e4d78b4375f69887e75abcc1e6a6782c551 | <|skeleton|>
class DestinationHelp:
def push(self, river_config, data):
"""将数据推到目的地 :param river_config: :param data: :return:"""
<|body_0|>
def clear(self, river_config, data):
"""清除掉所有数据 :param river_config: :param data: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DestinationHelp:
def push(self, river_config, data):
"""将数据推到目的地 :param river_config: :param data: :return:"""
if not data:
app_log.info('data is null')
return
if 'destination' not in river_config:
app_log.warning("The test_river doesn't have destina... | the_stack_v2_python_sparse | suggest/destinations.py | RitterHou/search_platform | train | 0 | |
d5b807a3a7122fb54658b4a180be703ef8b52f96 | [
"if hparams.num_cells % 3 != 0:\n raise ValueError('num_cells must be a multiple of 3.')\nself._hparams = hparams\nself._builder_fn = functools.partial(Builder, feature_columns=feature_columns, optimizer_fn=optimizer_fn, checkpoint_dir=checkpoint_dir, seed=seed)",
"num_cells = self._hparams.num_cells\nnum_conv... | <|body_start_0|>
if hparams.num_cells % 3 != 0:
raise ValueError('num_cells must be a multiple of 3.')
self._hparams = hparams
self._builder_fn = functools.partial(Builder, feature_columns=feature_columns, optimizer_fn=optimizer_fn, checkpoint_dir=checkpoint_dir, seed=seed)
<|end_bod... | Generates a list of `Builders`. | DynamicGenerator | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicGenerator:
"""Generates a list of `Builders`."""
def __init__(self, feature_columns, optimizer_fn, iteration_steps, checkpoint_dir, hparams, seed=None):
"""Generator that gradually grows the architecture. In each iteration, we generate one deeper candidate and one wider candid... | stack_v2_sparse_classes_36k_train_001617 | 11,982 | permissive | [
{
"docstring": "Generator that gradually grows the architecture. In each iteration, we generate one deeper candidate and one wider candidate. Args: feature_columns: The input feature columns of the problem. optimizer_fn: Function that accepts a float 'learning_rate' argument and returns an `Optimizer` instance ... | 2 | stack_v2_sparse_classes_30k_train_009601 | Implement the Python class `DynamicGenerator` described below.
Class description:
Generates a list of `Builders`.
Method signatures and docstrings:
- def __init__(self, feature_columns, optimizer_fn, iteration_steps, checkpoint_dir, hparams, seed=None): Generator that gradually grows the architecture. In each iterati... | Implement the Python class `DynamicGenerator` described below.
Class description:
Generates a list of `Builders`.
Method signatures and docstrings:
- def __init__(self, feature_columns, optimizer_fn, iteration_steps, checkpoint_dir, hparams, seed=None): Generator that gradually grows the architecture. In each iterati... | 74106c51e0602bdd62b643f4d6c42a00142947bc | <|skeleton|>
class DynamicGenerator:
"""Generates a list of `Builders`."""
def __init__(self, feature_columns, optimizer_fn, iteration_steps, checkpoint_dir, hparams, seed=None):
"""Generator that gradually grows the architecture. In each iteration, we generate one deeper candidate and one wider candid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicGenerator:
"""Generates a list of `Builders`."""
def __init__(self, feature_columns, optimizer_fn, iteration_steps, checkpoint_dir, hparams, seed=None):
"""Generator that gradually grows the architecture. In each iteration, we generate one deeper candidate and one wider candidate. Args: fe... | the_stack_v2_python_sparse | research/improve_nas/trainer/improve_nas.py | todun/adanet | train | 1 |
22eafb5d7373c1ea659a20e3eae4ff199227a267 | [
"if not head:\n return head\nf_node, s_node = (head, head.next)\ndone_end_node = None\nwhile f_node and s_node:\n f_node.next = s_node.next\n s_node.next = f_node\n if done_end_node:\n done_end_node.next = s_node\n else:\n head = s_node\n done_end_node = f_node\n f_node = f_node.n... | <|body_start_0|>
if not head:
return head
f_node, s_node = (head, head.next)
done_end_node = None
while f_node and s_node:
f_node.next = s_node.next
s_node.next = f_node
if done_end_node:
done_end_node.next = s_node
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsRecursive(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return ... | stack_v2_sparse_classes_36k_train_001618 | 1,319 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairsRecursive",
"signature": "def swapPairsRecursive(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011304 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairsRecursive(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairsRecursive(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
de... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairsRecursive(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return head
f_node, s_node = (head, head.next)
done_end_node = None
while f_node and s_node:
f_node.next = s_node.next
s_node.next = f_node
... | the_stack_v2_python_sparse | cs_notes/data_structure/linked_list/swap_nodes_in_pairs.py | hwc1824/LeetCodeSolution | train | 0 | |
46cccd1719b72d748bd46616fe821bb94a116f3f | [
"rospy.Service('wouse_run_stop', WouseRunStop, self.service_cb)\nself.run_stop = RunStop()\nif DEAD_MAN_CONFIGURATION:\n self.sound_client = SoundClient()\n self.timeout = rospy.Duration(rospy.get_param('wouse_timeout', 1.5))\n self.tone_period = rospy.Duration(10)\n self.last_active_time = rospy.Time.n... | <|body_start_0|>
rospy.Service('wouse_run_stop', WouseRunStop, self.service_cb)
self.run_stop = RunStop()
if DEAD_MAN_CONFIGURATION:
self.sound_client = SoundClient()
self.timeout = rospy.Duration(rospy.get_param('wouse_timeout', 1.5))
self.tone_period = rospy... | RunStopServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunStopServer:
def __init__(self):
"""Provide dead-man-switch like server for handling wouse run-stops."""
<|body_0|>
def check_receiving(self, event):
"""After timeout, check to ensure that activity is seen from wouse."""
<|body_1|>
def service_cb(self,... | stack_v2_sparse_classes_36k_train_001619 | 4,841 | no_license | [
{
"docstring": "Provide dead-man-switch like server for handling wouse run-stops.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "After timeout, check to ensure that activity is seen from wouse.",
"name": "check_receiving",
"signature": "def check_receiving(sel... | 3 | null | Implement the Python class `RunStopServer` described below.
Class description:
Implement the RunStopServer class.
Method signatures and docstrings:
- def __init__(self): Provide dead-man-switch like server for handling wouse run-stops.
- def check_receiving(self, event): After timeout, check to ensure that activity i... | Implement the Python class `RunStopServer` described below.
Class description:
Implement the RunStopServer class.
Method signatures and docstrings:
- def __init__(self): Provide dead-man-switch like server for handling wouse run-stops.
- def check_receiving(self, event): After timeout, check to ensure that activity i... | b2cc6fc19c143ac6dc7f83af02a94c3833820b6e | <|skeleton|>
class RunStopServer:
def __init__(self):
"""Provide dead-man-switch like server for handling wouse run-stops."""
<|body_0|>
def check_receiving(self, event):
"""After timeout, check to ensure that activity is seen from wouse."""
<|body_1|>
def service_cb(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunStopServer:
def __init__(self):
"""Provide dead-man-switch like server for handling wouse run-stops."""
rospy.Service('wouse_run_stop', WouseRunStop, self.service_cb)
self.run_stop = RunStop()
if DEAD_MAN_CONFIGURATION:
self.sound_client = SoundClient()
... | the_stack_v2_python_sparse | wouse/src/wouse/run_stop_server.py | wklharry/hrl | train | 0 | |
6614603460b8fd51230e57809d6de1dbd62674fb | [
"super(Bottleneck, self).__init__()\nassert style in ['pytorch', 'caffe']\nself.inplanes = inplanes\nself.planes = planes\nself.stride = stride\nself.dilation = dilation\nself.style = style\nself.with_cp = with_cp\nself.norm1 = ops.BatchNorm2d(planes)\nself.norm2 = ops.BatchNorm2d(planes)\nself.norm3 = ops.BatchNor... | <|body_start_0|>
super(Bottleneck, self).__init__()
assert style in ['pytorch', 'caffe']
self.inplanes = inplanes
self.planes = planes
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.norm1 = ops.BatchNor... | This is the class of Bottleneck block for ResNet. | Bottleneck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bottleneck:
"""This is the class of Bottleneck block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init Bottleneck."""
<|body_0|>
def call(self, x):
"""Forward compute. :param x: inp... | stack_v2_sparse_classes_36k_train_001620 | 12,928 | permissive | [
{
"docstring": "Init Bottleneck.",
"name": "__init__",
"signature": "def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False)"
},
{
"docstring": "Forward compute. :param x: input feature map :type x: torch.Tensor :return: out feature map :rtype:... | 2 | null | Implement the Python class `Bottleneck` described below.
Class description:
This is the class of Bottleneck block for ResNet.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): Init Bottleneck.
- def call(self, x): Forward c... | Implement the Python class `Bottleneck` described below.
Class description:
This is the class of Bottleneck block for ResNet.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): Init Bottleneck.
- def call(self, x): Forward c... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Bottleneck:
"""This is the class of Bottleneck block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init Bottleneck."""
<|body_0|>
def call(self, x):
"""Forward compute. :param x: inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bottleneck:
"""This is the class of Bottleneck block for ResNet."""
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False):
"""Init Bottleneck."""
super(Bottleneck, self).__init__()
assert style in ['pytorch', 'caffe']
s... | the_stack_v2_python_sparse | zeus/networks/necks.py | huawei-noah/xingtian | train | 308 |
77fb6134344395737c317b0100cbcb34a171757a | [
"self.hass = hass\nself._devices = config.get(CONF_DEVICES, None)\nself._access_token_payload = {'username': config.get(CONF_USERNAME), 'password': config.get(CONF_PASSWORD), 'client_id': config.get(CONF_CLIENT_ID), 'client_secret': config.get(CONF_SECRET), 'grant_type': 'password', 'scope': SCOPE}\nself._headers =... | <|body_start_0|>
self.hass = hass
self._devices = config.get(CONF_DEVICES, None)
self._access_token_payload = {'username': config.get(CONF_USERNAME), 'password': config.get(CONF_PASSWORD), 'client_id': config.get(CONF_CLIENT_ID), 'client_secret': config.get(CONF_SECRET), 'grant_type': 'password'... | A class representing an Automatic device. | AutomaticDeviceScanner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
<|body_0|>
def _update_headers(self):
"""Get the access token from automatic."""
<|... | stack_v2_sparse_classes_36k_train_001621 | 5,190 | permissive | [
{
"docstring": "Initialize the automatic device scanner.",
"name": "__init__",
"signature": "def __init__(self, hass, config: dict, see) -> None"
},
{
"docstring": "Get the access token from automatic.",
"name": "_update_headers",
"signature": "def _update_headers(self)"
},
{
"do... | 3 | null | Implement the Python class `AutomaticDeviceScanner` described below.
Class description:
A class representing an Automatic device.
Method signatures and docstrings:
- def __init__(self, hass, config: dict, see) -> None: Initialize the automatic device scanner.
- def _update_headers(self): Get the access token from aut... | Implement the Python class `AutomaticDeviceScanner` described below.
Class description:
A class representing an Automatic device.
Method signatures and docstrings:
- def __init__(self, hass, config: dict, see) -> None: Initialize the automatic device scanner.
- def _update_headers(self): Get the access token from aut... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
<|body_0|>
def _update_headers(self):
"""Get the access token from automatic."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
self.hass = hass
self._devices = config.get(CONF_DEVICES, None)
self._access_token_payload = {'userna... | the_stack_v2_python_sparse | homeassistant/components/device_tracker/automatic.py | Smart-Torvy/torvy-home-assistant | train | 2 |
eeaaa9286db141ab3bf0d07b9e5da591c81cd90e | [
"Canvas.__init__(self)\nself.configure(width=larg, height=haut)\nself.larg, self.haut = (larg, haut)\npas = (larg - 25) / 8.0\nfor t in range(1, 9):\n stx = 10 + t * pas\n self.create_line(stx, haut / 10, stx, haut * 9 / 10, fill='grey')\npas = haut * 2 / 25.0\nfor t in range(-5, 6):\n sty = haut / 2 - t *... | <|body_start_0|>
Canvas.__init__(self)
self.configure(width=larg, height=haut)
self.larg, self.haut = (larg, haut)
pas = (larg - 25) / 8.0
for t in range(1, 9):
stx = 10 + t * pas
self.create_line(stx, haut / 10, stx, haut * 9 / 10, fill='grey')
pa... | Canevas spcialis, pour dessiner des courbes longation/temps | OscilloGraphe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OscilloGraphe:
"""Canevas spcialis, pour dessiner des courbes longation/temps"""
def __init__(self, master=None, larg=200, haut=150):
"""Constructeur du graphique : axes et chelle horiz."""
<|body_0|>
def traceCourbe(self, freq=1, phase=0, ampl=10, coul='red'):
"... | stack_v2_sparse_classes_36k_train_001622 | 2,920 | no_license | [
{
"docstring": "Constructeur du graphique : axes et chelle horiz.",
"name": "__init__",
"signature": "def __init__(self, master=None, larg=200, haut=150)"
},
{
"docstring": "trac d'un graphique longation/temps sur 1 seconde",
"name": "traceCourbe",
"signature": "def traceCourbe(self, fre... | 2 | null | Implement the Python class `OscilloGraphe` described below.
Class description:
Canevas spcialis, pour dessiner des courbes longation/temps
Method signatures and docstrings:
- def __init__(self, master=None, larg=200, haut=150): Constructeur du graphique : axes et chelle horiz.
- def traceCourbe(self, freq=1, phase=0,... | Implement the Python class `OscilloGraphe` described below.
Class description:
Canevas spcialis, pour dessiner des courbes longation/temps
Method signatures and docstrings:
- def __init__(self, master=None, larg=200, haut=150): Constructeur du graphique : axes et chelle horiz.
- def traceCourbe(self, freq=1, phase=0,... | 67bdb548574f4feecb99b60995238f12f4ef26da | <|skeleton|>
class OscilloGraphe:
"""Canevas spcialis, pour dessiner des courbes longation/temps"""
def __init__(self, master=None, larg=200, haut=150):
"""Constructeur du graphique : axes et chelle horiz."""
<|body_0|>
def traceCourbe(self, freq=1, phase=0, ampl=10, coul='red'):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OscilloGraphe:
"""Canevas spcialis, pour dessiner des courbes longation/temps"""
def __init__(self, master=None, larg=200, haut=150):
"""Constructeur du graphique : axes et chelle horiz."""
Canvas.__init__(self)
self.configure(width=larg, height=haut)
self.larg, self.haut ... | the_stack_v2_python_sparse | python/oreilly/cours_python/solutions/exercice_13_10.py | scls19fr/openphysic | train | 1 |
f72b942970e8d27d1939c7d400d412bad7831328 | [
"for vals in vals_list:\n if vals.get('origin', False) and vals['origin'][0] == ':':\n vals.update({'origin': vals['origin'][1:]})\n if vals.get('origin', False) and vals['origin'][-1] == ':':\n vals.update({'origin': vals['origin'][:-1]})\n return super(StockPicking, self).create(vals)",
"... | <|body_start_0|>
for vals in vals_list:
if vals.get('origin', False) and vals['origin'][0] == ':':
vals.update({'origin': vals['origin'][1:]})
if vals.get('origin', False) and vals['origin'][-1] == ':':
vals.update({'origin': vals['origin'][:-1]})
... | Stock Picking. | StockPicking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockPicking:
"""Stock Picking."""
def create(self, vals_list):
"""Overridden create method."""
<|body_0|>
def write(self, vals):
"""Overridden write method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for vals in vals_list:
if v... | stack_v2_sparse_classes_36k_train_001623 | 49,476 | no_license | [
{
"docstring": "Overridden create method.",
"name": "create",
"signature": "def create(self, vals_list)"
},
{
"docstring": "Overridden write method.",
"name": "write",
"signature": "def write(self, vals)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002881 | Implement the Python class `StockPicking` described below.
Class description:
Stock Picking.
Method signatures and docstrings:
- def create(self, vals_list): Overridden create method.
- def write(self, vals): Overridden write method. | Implement the Python class `StockPicking` described below.
Class description:
Stock Picking.
Method signatures and docstrings:
- def create(self, vals_list): Overridden create method.
- def write(self, vals): Overridden write method.
<|skeleton|>
class StockPicking:
"""Stock Picking."""
def create(self, val... | 7618a365ac78c0f59390a3a6b5fcdd9f76a5ddec | <|skeleton|>
class StockPicking:
"""Stock Picking."""
def create(self, vals_list):
"""Overridden create method."""
<|body_0|>
def write(self, vals):
"""Overridden write method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockPicking:
"""Stock Picking."""
def create(self, vals_list):
"""Overridden create method."""
for vals in vals_list:
if vals.get('origin', False) and vals['origin'][0] == ':':
vals.update({'origin': vals['origin'][1:]})
if vals.get('origin', False... | the_stack_v2_python_sparse | fleet_operations/models/fleet_service.py | JayVora-SerpentCS/fleet_management | train | 29 |
8e15159a1d1f72f24f04bba85111ed10c5f38789 | [
"try:\n return KnowMind.objects.filter(knowledge=int(self.kwargs['pk']))\nexcept:\n return KnowMind.objects.all()",
"instance = self.get_queryset()\nserializer = self.get_serializer(instance, many=True)\nreturn Response(serializer.data)"
] | <|body_start_0|>
try:
return KnowMind.objects.filter(knowledge=int(self.kwargs['pk']))
except:
return KnowMind.objects.all()
<|end_body_0|>
<|body_start_1|>
instance = self.get_queryset()
serializer = self.get_serializer(instance, many=True)
return Respon... | 知识点导图 | KnowledgeMindViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnowledgeMindViewSet:
"""知识点导图"""
def get_queryset(self):
"""获取知识点导图 根据知识点id查询导图 :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""url请求 http://127.0.0.1:8000/know_mind/1/ 其中的1代表知识点的id号 返回该知识点对应的所有导图 :param request: :param args: :param kwarg... | stack_v2_sparse_classes_36k_train_001624 | 7,211 | no_license | [
{
"docstring": "获取知识点导图 根据知识点id查询导图 :return:",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "url请求 http://127.0.0.1:8000/know_mind/1/ 其中的1代表知识点的id号 返回该知识点对应的所有导图 :param request: :param args: :param kwargs: :return:",
"name": "retrieve",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_000847 | Implement the Python class `KnowledgeMindViewSet` described below.
Class description:
知识点导图
Method signatures and docstrings:
- def get_queryset(self): 获取知识点导图 根据知识点id查询导图 :return:
- def retrieve(self, request, *args, **kwargs): url请求 http://127.0.0.1:8000/know_mind/1/ 其中的1代表知识点的id号 返回该知识点对应的所有导图 :param request: :par... | Implement the Python class `KnowledgeMindViewSet` described below.
Class description:
知识点导图
Method signatures and docstrings:
- def get_queryset(self): 获取知识点导图 根据知识点id查询导图 :return:
- def retrieve(self, request, *args, **kwargs): url请求 http://127.0.0.1:8000/know_mind/1/ 其中的1代表知识点的id号 返回该知识点对应的所有导图 :param request: :par... | 9205dfd8dd0c822a9f5352db845fc12c319db3e3 | <|skeleton|>
class KnowledgeMindViewSet:
"""知识点导图"""
def get_queryset(self):
"""获取知识点导图 根据知识点id查询导图 :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""url请求 http://127.0.0.1:8000/know_mind/1/ 其中的1代表知识点的id号 返回该知识点对应的所有导图 :param request: :param args: :param kwarg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnowledgeMindViewSet:
"""知识点导图"""
def get_queryset(self):
"""获取知识点导图 根据知识点id查询导图 :return:"""
try:
return KnowMind.objects.filter(knowledge=int(self.kwargs['pk']))
except:
return KnowMind.objects.all()
def retrieve(self, request, *args, **kwargs):
... | the_stack_v2_python_sparse | apps/library/views.py | bbright3493/gz_v1.0.0 | train | 0 |
1f456ac1610c398b48d1fa74d4dcfe20b0b1f539 | [
"if a < b:\n a, b = (b, a)\nwhile True:\n c = a % b\n if c != 0:\n a, b = (b, c)\n else:\n break\nreturn b",
"if a < b:\n a, b = (b, a)\nif a % b == 0:\n return b\nelse:\n return self.divisor2(b, a % b)",
"if a < b:\n a, b = (b, a)\nif a - b == 0:\n return b\nelse:\n ... | <|body_start_0|>
if a < b:
a, b = (b, a)
while True:
c = a % b
if c != 0:
a, b = (b, c)
else:
break
return b
<|end_body_0|>
<|body_start_1|>
if a < b:
a, b = (b, a)
if a % b == 0:
... | 求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(log(max(a,b))) | GreatestCommonDivisor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreatestCommonDivisor:
"""求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(log(max(a,b)))"""
def divisor(a, b)... | stack_v2_sparse_classes_36k_train_001625 | 4,308 | no_license | [
{
"docstring": "辗转相除法(欧几里得算法)",
"name": "divisor",
"signature": "def divisor(a, b)"
},
{
"docstring": "辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数",
"name": "divisor2",
"signature": "def divisor2(self, a, b)"
},
{
"docstring": "更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b... | 4 | null | Implement the Python class `GreatestCommonDivisor` described below.
Class description:
求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(l... | Implement the Python class `GreatestCommonDivisor` described below.
Class description:
求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(l... | 0779cdbe3a8a7b828e47cfb8a830c56f72e015c7 | <|skeleton|>
class GreatestCommonDivisor:
"""求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(log(max(a,b)))"""
def divisor(a, b)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GreatestCommonDivisor:
"""求最大公约数 1、辗转相除法(欧几里得算法)基于一个定理。两个正整数a和b(a>b),它们的最大公约数等于a和b的余数c 与b之间的最大公约数 时间复杂度:近似为O(log(max(a, b))) 问题:当a和b过大时,取模运算性能变差 2、更相减损术 两个正整数a和b(a>b),它们的最大公约数等于a和b的差c 与b之间的最大公约数 时间复杂度:最差O(max(a,b)) 问题:当a和b相差太大,运算次数过多 3、辗转相除法与更相减损术结合 时间复杂度O(log(max(a,b)))"""
def divisor(a, b):
"""... | the_stack_v2_python_sparse | base_test/sort/exercise.py | huanmengmie/python_study | train | 0 |
579c0cb65a3dcd1918b6619303b51fe7f477f071 | [
"self._lock = LockTimeout()\nself._list = []\nself._delay = CommDelay()\nself._logger = logger\nif self._logger is None:\n self._logger = logging.getLogger(self.__class__.__name__)\nif timeout is not None:\n self._TIMEOUT = timeout",
"if not self._lock.acquire(blocking=True, timeout=self._TIMEOUT):\n rai... | <|body_start_0|>
self._lock = LockTimeout()
self._list = []
self._delay = CommDelay()
self._logger = logger
if self._logger is None:
self._logger = logging.getLogger(self.__class__.__name__)
if timeout is not None:
self._TIMEOUT = timeout
<|end_bod... | Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off the queue in by calling :py:meth:`pop()`. The method compares the object time... | DelayQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayQueue:
"""Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off the queue in by calling :py:meth:`pop()... | stack_v2_sparse_classes_36k_train_001626 | 5,264 | no_license | [
{
"docstring": "Initialize a DelayQueue object. Args: logger (logging.Logger): Logger object linked to parent class. If not provided, then get a logger based on the class name. timeout (int): Optional; Timeout in seconds for accessing lock for queue operations. If not provided, defaults to 0.1sec. Returns: bool... | 6 | stack_v2_sparse_classes_30k_train_007250 | Implement the Python class `DelayQueue` described below.
Class description:
Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off ... | Implement the Python class `DelayQueue` described below.
Class description:
Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off ... | ce17bf787add23e9b28bc91e8b79eaaf1d5f1a08 | <|skeleton|>
class DelayQueue:
"""Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off the queue in by calling :py:meth:`pop()... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelayQueue:
"""Thread-safe queue (first-in-first-out) with time delay pop operations. Objects are pushed into the queue by calling :meth:`push()`. The method also adds a timestamp, :math:`t_{obj}`, given by :py:func:`time.monotonic`. Objects are poppoed off the queue in by calling :py:meth:`pop()`. The method... | the_stack_v2_python_sparse | delay_server/delay_server/util/queue.py | dschor5/AnalogCommDelay | train | 0 |
97271746905bc2279b8bb3cb5d5cccbec4fa5093 | [
"def construct(start, end):\n if start > end:\n return None\n if start == end:\n return Node(None, None, start, start, end, nums[start])\n mid = (start + end) // 2\n l, r = (construct(start, mid), construct(mid + 1, end))\n return Node(l, r, start, mid, end, l.val + r.val)\nself.root = ... | <|body_start_0|>
def construct(start, end):
if start > end:
return None
if start == end:
return Node(None, None, start, start, end, nums[start])
mid = (start + end) // 2
l, r = (construct(start, mid), construct(mid + 1, end))
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_001627 | 4,459 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_015600 | 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 update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 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 update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 36d7f9e967a62db77622e0888f61999d7f37579a | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|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 NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
def construct(start, end):
if start > end:
return None
if start == end:
return Node(None, None, start, start, end, nums[start])
mid = (start + end) // 2
... | the_stack_v2_python_sparse | P0307.py | westgate458/LeetCode | train | 0 | |
f5cbfc8fe349b24e37e196bc428a05d50ce2f3c0 | [
"del Request_Handle.player[player]\ndel Request_Handle.pair[player]\nRequest_Handle.first.remove(player)\nRequest_Handle.waiting_list.remove(player)",
"data = pickle.loads(self.request.recv(2048))\nplayer = self.client_address[0]\nlogging.critical(f'{self.client_address[0]} wrote: {data}')\nlogging.debug(f'Reques... | <|body_start_0|>
del Request_Handle.player[player]
del Request_Handle.pair[player]
Request_Handle.first.remove(player)
Request_Handle.waiting_list.remove(player)
<|end_body_0|>
<|body_start_1|>
data = pickle.loads(self.request.recv(2048))
player = self.client_address[0]
... | Request_Handle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request_Handle:
def remove_from_all(player):
"""Remove player from all vars"""
<|body_0|>
def handle(self):
"""Method to handle the client"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
del Request_Handle.player[player]
del Request_Handle.p... | stack_v2_sparse_classes_36k_train_001628 | 3,192 | permissive | [
{
"docstring": "Remove player from all vars",
"name": "remove_from_all",
"signature": "def remove_from_all(player)"
},
{
"docstring": "Method to handle the client",
"name": "handle",
"signature": "def handle(self)"
}
] | 2 | null | Implement the Python class `Request_Handle` described below.
Class description:
Implement the Request_Handle class.
Method signatures and docstrings:
- def remove_from_all(player): Remove player from all vars
- def handle(self): Method to handle the client | Implement the Python class `Request_Handle` described below.
Class description:
Implement the Request_Handle class.
Method signatures and docstrings:
- def remove_from_all(player): Remove player from all vars
- def handle(self): Method to handle the client
<|skeleton|>
class Request_Handle:
def remove_from_all(... | 6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9 | <|skeleton|>
class Request_Handle:
def remove_from_all(player):
"""Remove player from all vars"""
<|body_0|>
def handle(self):
"""Method to handle the client"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Request_Handle:
def remove_from_all(player):
"""Remove player from all vars"""
del Request_Handle.player[player]
del Request_Handle.pair[player]
Request_Handle.first.remove(player)
Request_Handle.waiting_list.remove(player)
def handle(self):
"""Method to ha... | the_stack_v2_python_sparse | Space_invaders Server/server.py | Jh123x/Orbital | train | 4 | |
95ad40702480c8e4793ba8be143461ed32fddb4a | [
"self._name = name\nself._freevars = freevars\nself._extra_locals = extra_locals\nself._unbound_factory = None\nself.module = None\nself.source_map = None",
"if self._unbound_factory is not None:\n raise ValueError('double initialization; create a new object instead')\ninner_factory_name = namer.new_symbol(inn... | <|body_start_0|>
self._name = name
self._freevars = freevars
self._extra_locals = extra_locals
self._unbound_factory = None
self.module = None
self.source_map = None
<|end_body_0|>
<|body_start_1|>
if self._unbound_factory is not None:
raise ValueErro... | Helper object that wraps a Python function factory. | _PythonFnFactory | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PythonFnFactory:
"""Helper object that wraps a Python function factory."""
def __init__(self, name, freevars, extra_locals):
"""Creates a new factory for a Python function. Args: name: The function name. freevars: The list of non-global free variables for the function. extra_locals:... | stack_v2_sparse_classes_36k_train_001629 | 17,496 | permissive | [
{
"docstring": "Creates a new factory for a Python function. Args: name: The function name. freevars: The list of non-global free variables for the function. extra_locals: Dict[Text, Any], names and values for custom variables that are accessible to the generated code as local variables.",
"name": "__init__... | 3 | null | Implement the Python class `_PythonFnFactory` described below.
Class description:
Helper object that wraps a Python function factory.
Method signatures and docstrings:
- def __init__(self, name, freevars, extra_locals): Creates a new factory for a Python function. Args: name: The function name. freevars: The list of ... | Implement the Python class `_PythonFnFactory` described below.
Class description:
Helper object that wraps a Python function factory.
Method signatures and docstrings:
- def __init__(self, name, freevars, extra_locals): Creates a new factory for a Python function. Args: name: The function name. freevars: The list of ... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class _PythonFnFactory:
"""Helper object that wraps a Python function factory."""
def __init__(self, name, freevars, extra_locals):
"""Creates a new factory for a Python function. Args: name: The function name. freevars: The list of non-global free variables for the function. extra_locals:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _PythonFnFactory:
"""Helper object that wraps a Python function factory."""
def __init__(self, name, freevars, extra_locals):
"""Creates a new factory for a Python function. Args: name: The function name. freevars: The list of non-global free variables for the function. extra_locals: Dict[Text, A... | the_stack_v2_python_sparse | tensorflow/python/autograph/pyct/transpiler.py | tensorflow/tensorflow | train | 208,740 |
55d64fe317bd1244c5f485df7ba11465887ac780 | [
"session = None\nsession_store_class = get_session_class()\nif app_settings.COOKIE_NAME in request.COOKIES:\n session = session_store_class(key=request.COOKIES[app_settings.COOKIE_NAME].value, request=request)\nif not session:\n session = session_store_class(request=request)\nrequest.session = session",
"re... | <|body_start_0|>
session = None
session_store_class = get_session_class()
if app_settings.COOKIE_NAME in request.COOKIES:
session = session_store_class(key=request.COOKIES[app_settings.COOKIE_NAME].value, request=request)
if not session:
session = session_store_cl... | SessionMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionMiddleware:
def process_request(self, request):
"""Creates a session instance for the current user."""
<|body_0|>
def process_response(self, request, response):
"""Sets the session cookie with its key"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_001630 | 984 | no_license | [
{
"docstring": "Creates a session instance for the current user.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Sets the session cookie with its key",
"name": "process_response",
"signature": "def process_response(self, request, response... | 2 | null | Implement the Python class `SessionMiddleware` described below.
Class description:
Implement the SessionMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Creates a session instance for the current user.
- def process_response(self, request, response): Sets the session cookie wi... | Implement the Python class `SessionMiddleware` described below.
Class description:
Implement the SessionMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Creates a session instance for the current user.
- def process_response(self, request, response): Sets the session cookie wi... | 875ac157b207fee80be6841f9b17c41b7069e15d | <|skeleton|>
class SessionMiddleware:
def process_request(self, request):
"""Creates a session instance for the current user."""
<|body_0|>
def process_response(self, request, response):
"""Sets the session cookie with its key"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionMiddleware:
def process_request(self, request):
"""Creates a session instance for the current user."""
session = None
session_store_class = get_session_class()
if app_settings.COOKIE_NAME in request.COOKIES:
session = session_store_class(key=request.COOKIES[a... | the_stack_v2_python_sparse | london/apps/sessions/middleware.py | avelino/votacao_paredao_bbb | train | 0 | |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ncomment = request.data.get('comment', {})\nposted_comment = CommentAPIView.check_comment(id, article)\nserializer = self.serializer_class(data=comment)\nserializer.is_valid(raise_exception=True)\nstatus_ = status.HTTP_201_CREATED\ntry:\n CommentReply.objects.get(comment_to=pos... | <|body_start_0|>
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
posted_comment = CommentAPIView.check_comment(id, article)
serializer = self.serializer_class(data=comment)
serializer.is_valid(raise_exception=True)
status_ = status.HTTP_201_CRE... | Handles viweing of replies made to a comment and replying to an article comment | ReplyList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
<|body_0|>
def get(self, request, slug, id):
"""Retrieves all replies to a comment of matching ID"... | stack_v2_sparse_classes_36k_train_001631 | 10,918 | permissive | [
{
"docstring": "Posts a reply to a comment",
"name": "post",
"signature": "def post(self, request, slug, id)"
},
{
"docstring": "Retrieves all replies to a comment of matching ID",
"name": "get",
"signature": "def get(self, request, slug, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000460 | Implement the Python class `ReplyList` described below.
Class description:
Handles viweing of replies made to a comment and replying to an article comment
Method signatures and docstrings:
- def post(self, request, slug, id): Posts a reply to a comment
- def get(self, request, slug, id): Retrieves all replies to a co... | Implement the Python class `ReplyList` described below.
Class description:
Handles viweing of replies made to a comment and replying to an article comment
Method signatures and docstrings:
- def post(self, request, slug, id): Posts a reply to a comment
- def get(self, request, slug, id): Retrieves all replies to a co... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
<|body_0|>
def get(self, request, slug, id):
"""Retrieves all replies to a comment of matching ID"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplyList:
"""Handles viweing of replies made to a comment and replying to an article comment"""
def post(self, request, slug, id):
"""Posts a reply to a comment"""
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
posted_comment = CommentAPIView.... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
80b0226bff8885d1333d2e655166a39a9f45f324 | [
"admin = self.isAdmin()\ntry:\n current_user_id = self.get_current_user()['id']\nexcept Exception as e:\n self.serverError('unidentified user')\n return\npi_auth = []\nuser = (yield r.table('users').get(current_user_id).run(self.dbconnection))\npi_auth = user['pi_authorities']\ntry:\n secret = self.appl... | <|body_start_0|>
admin = self.isAdmin()
try:
current_user_id = self.get_current_user()['id']
except Exception as e:
self.serverError('unidentified user')
return
pi_auth = []
user = (yield r.table('users').get(current_user_id).run(self.dbconnect... | UserTokenHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTokenHandler:
def get(self):
"""GET /usertoken :return:"""
<|body_0|>
def post(self):
"""POST /usertoken :return: user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
admin = self.isAdmin()
try:
current_user_id = self.get_cur... | stack_v2_sparse_classes_36k_train_001632 | 30,583 | permissive | [
{
"docstring": "GET /usertoken :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "POST /usertoken :return: user",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `UserTokenHandler` described below.
Class description:
Implement the UserTokenHandler class.
Method signatures and docstrings:
- def get(self): GET /usertoken :return:
- def post(self): POST /usertoken :return: user | Implement the Python class `UserTokenHandler` described below.
Class description:
Implement the UserTokenHandler class.
Method signatures and docstrings:
- def get(self): GET /usertoken :return:
- def post(self): POST /usertoken :return: user
<|skeleton|>
class UserTokenHandler:
def get(self):
"""GET /u... | 32af9462cc9e5654a6e3036978ae74b0a03a2698 | <|skeleton|>
class UserTokenHandler:
def get(self):
"""GET /usertoken :return:"""
<|body_0|>
def post(self):
"""POST /usertoken :return: user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserTokenHandler:
def get(self):
"""GET /usertoken :return:"""
admin = self.isAdmin()
try:
current_user_id = self.get_current_user()['id']
except Exception as e:
self.serverError('unidentified user')
return
pi_auth = []
user =... | the_stack_v2_python_sparse | myslice/web/rest/users.py | loicbaron/myslice2 | train | 0 | |
03724c667175bcbfb72facb13582e5978b0b1b46 | [
"authenticated_user = request.user\nuser_id = kwargs['id']\nuser_profile = get_object_or_404(Profile, user_id=user_id)\nif authenticated_user.id == user_id:\n profile_form = ProfileForm(instance=user_profile)\n return render(request, self.template_name, {'profile_form': profile_form})\nunauthenticated_url = f... | <|body_start_0|>
authenticated_user = request.user
user_id = kwargs['id']
user_profile = get_object_or_404(Profile, user_id=user_id)
if authenticated_user.id == user_id:
profile_form = ProfileForm(instance=user_profile)
return render(request, self.template_name, {... | Handles the user profile view. Requires user to be logged in | ProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles profile fo... | stack_v2_sparse_classes_36k_train_001633 | 3,240 | no_license | [
{
"docstring": "Shows the user his own profile or redirects to the login page",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Handles profile form data and either updates profile or renders the form again with errors",
"name": "post",
"signature... | 2 | stack_v2_sparse_classes_30k_train_001909 | Implement the Python class `ProfileView` described below.
Class description:
Handles the user profile view. Requires user to be logged in
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Shows the user his own profile or redirects to the login page
- def post(self, request, *args, **kwargs... | Implement the Python class `ProfileView` described below.
Class description:
Handles the user profile view. Requires user to be logged in
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Shows the user his own profile or redirects to the login page
- def post(self, request, *args, **kwargs... | ce8a83cea5fe7232b6746ad9708688c23d486e99 | <|skeleton|>
class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles profile fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileView:
"""Handles the user profile view. Requires user to be logged in"""
def get(self, request, *args, **kwargs):
"""Shows the user his own profile or redirects to the login page"""
authenticated_user = request.user
user_id = kwargs['id']
user_profile = get_object_o... | the_stack_v2_python_sparse | users/views.py | johnjudeh/Rendez-Vous-Py | train | 0 |
4124c96e23e7b62944f93c83382e3889b63484a6 | [
"if not must_contain:\n return\nif isinstance(must_contain, str):\n must_contain = [must_contain]\nregexes = [re.compile(s) for s in must_contain]\nfor i, r in enumerate(regexes):\n match = r.search(output)\n if not match:\n self.fail(f\"Output of command: '{cmd}' contained no match for: '{must_c... | <|body_start_0|>
if not must_contain:
return
if isinstance(must_contain, str):
must_contain = [must_contain]
regexes = [re.compile(s) for s in must_contain]
for i, r in enumerate(regexes):
match = r.search(output)
if not match:
... | Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a test case in the normal way but inherit from test_util.SubProcessChecker instead of ... | SubProcessChecker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubProcessChecker:
"""Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a test case in the normal way but inherit... | stack_v2_sparse_classes_36k_train_001634 | 18,428 | permissive | [
{
"docstring": "Internal utility used by run_command(...) to check output (Should not need to call this directly from test cases).",
"name": "_check_output",
"signature": "def _check_output(self, cmd, output: str, must_contain: List[str])"
},
{
"docstring": "Run a command using subprocess, check... | 2 | stack_v2_sparse_classes_30k_train_006358 | Implement the Python class `SubProcessChecker` described below.
Class description:
Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a ... | Implement the Python class `SubProcessChecker` described below.
Class description:
Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a ... | e2f834dd60e7939672c1795b4ac62e89ad0bca49 | <|skeleton|>
class SubProcessChecker:
"""Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a test case in the normal way but inherit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubProcessChecker:
"""Utility Module for building tests that reliably check if a sub-process ran successfully. Commonly with an integration/system test you want to check a command can be run successfully and gives some expected output. How to use: 1. Make a test case in the normal way but inherit from test_ut... | the_stack_v2_python_sparse | utils/examples_tests/test_util.py | graphcore/examples | train | 311 |
74c73901c1860baa2edb39aea91f4fdff02ae810 | [
"if not root:\n return 0\nlevel_left_most = []\nlevel_right_most = []\nself.dfs(root, 0, 1, level_left_most, level_right_most)\nmax_width = 0\nfor level in range(len(level_left_most)):\n level_width = level_right_most[level] - level_left_most[level] + 1\n if level_width > max_width:\n max_width = le... | <|body_start_0|>
if not root:
return 0
level_left_most = []
level_right_most = []
self.dfs(root, 0, 1, level_left_most, level_right_most)
max_width = 0
for level in range(len(level_left_most)):
level_width = level_right_most[level] - level_left_mos... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def widthOfBinaryTree(self, root):
"""递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, root, level, cur_node_index, level_left_most, level_right_most):
""":param root: :param le... | stack_v2_sparse_classes_36k_train_001635 | 2,009 | no_license | [
{
"docstring": "递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int",
"name": "widthOfBinaryTree",
"signature": "def widthOfBinaryTree(self, root)"
},
{
"docstring": ":param root: :param level: 属于哪一层 :param cur_node_index: 当前层当前结点的下标 :param level_... | 2 | stack_v2_sparse_classes_30k_val_000324 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def widthOfBinaryTree(self, root): 递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int
- def dfs(self, root, level, cur_node_inde... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def widthOfBinaryTree(self, root): 递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int
- def dfs(self, root, level, cur_node_inde... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def widthOfBinaryTree(self, root):
"""递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, root, level, cur_node_index, level_left_most, level_right_most):
""":param root: :param le... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def widthOfBinaryTree(self, root):
"""递归找到每层最左边的下标和最右边的下标(leftmost node and rightmost node in each level) :type root: TreeNode :rtype: int"""
if not root:
return 0
level_left_most = []
level_right_most = []
self.dfs(root, 0, 1, level_left_most, lev... | the_stack_v2_python_sparse | 601-700/662. Maximum Width of Binary Tree.py | SunnyMarkLiu/LeetCode | train | 1 | |
cc6fe645a4065c6fc305b3c0898d6400183470fb | [
"super(BasicCompartmentCompound, self).__init__(unique_id=unique_id, **kw_args)\nself.compound = compound\nself.compartment = compartment\nif not self.compartment is None:\n self.compartment.register(self)",
"if 'compound' in self.__dict__:\n return self.compound.__getattribute__(attr)\nraise AttributeError... | <|body_start_0|>
super(BasicCompartmentCompound, self).__init__(unique_id=unique_id, **kw_args)
self.compound = compound
self.compartment = compartment
if not self.compartment is None:
self.compartment.register(self)
<|end_body_0|>
<|body_start_1|>
if 'compound' in s... | A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the compartment. | BasicCompartmentCompound | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicCompartmentCompound:
"""A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the compartment."""
def __init__(self... | stack_v2_sparse_classes_36k_train_001636 | 18,790 | permissive | [
{
"docstring": "Parameters ---------- unique_id: str (optional) A string uniquely identifying the compartmentalized compound among its class. compound: BasicCompound An instance of BasicCompound that is then attached to a compartment. compartment: BasicCompartment An instance of BasicCompartment in which the co... | 2 | null | Implement the Python class `BasicCompartmentCompound` described below.
Class description:
A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the... | Implement the Python class `BasicCompartmentCompound` described below.
Class description:
A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the... | 9459b51bb6f33c7d3c644cd95a9d72a0862470e6 | <|skeleton|>
class BasicCompartmentCompound:
"""A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the compartment."""
def __init__(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicCompartmentCompound:
"""A compartment specific compound. Often it is desirable to identify compounds on a per compartment basis, for example, in FBA experiments. This class is a simple container for both the compound instance that already exists and the compartment."""
def __init__(self, unique_id='... | the_stack_v2_python_sparse | pyorganism/metabolism/elements.py | Midnighter/pyorganism | train | 2 |
ceb8d0980c5ba00bd956b4737d89408705ef3e63 | [
"with open(cameras_file_path, 'r') as cameras_file:\n cameras = json.loads(cameras_file.read())\nviews = cameras['views']\nposes = cameras['poses']\nreturn (views, poses)",
"_poses = {}\nfor poses_dict in poses or []:\n pose_id, rotation, center = MeshroomParser.Pose.extract_from(poses_dict)\n _poses[pos... | <|body_start_0|>
with open(cameras_file_path, 'r') as cameras_file:
cameras = json.loads(cameras_file.read())
views = cameras['views']
poses = cameras['poses']
return (views, poses)
<|end_body_0|>
<|body_start_1|>
_poses = {}
for poses_dict in poses or []:
... | MeshroomParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeshroomParser:
def parse_cameras(cameras_file_path):
"""Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`."""
<|body_0|>
def extract_views_and_poses(views=None, poses=None):
"""Returns two dic... | stack_v2_sparse_classes_36k_train_001637 | 10,562 | no_license | [
{
"docstring": "Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`.",
"name": "parse_cameras",
"signature": "def parse_cameras(cameras_file_path)"
},
{
"docstring": "Returns two dictionaries, mapping: - `view_id` to `View` ... | 2 | stack_v2_sparse_classes_30k_train_003764 | Implement the Python class `MeshroomParser` described below.
Class description:
Implement the MeshroomParser class.
Method signatures and docstrings:
- def parse_cameras(cameras_file_path): Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`.
- d... | Implement the Python class `MeshroomParser` described below.
Class description:
Implement the MeshroomParser class.
Method signatures and docstrings:
- def parse_cameras(cameras_file_path): Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`.
- d... | bac774e1f7b3131f559ee3ff1662836c424ebaa5 | <|skeleton|>
class MeshroomParser:
def parse_cameras(cameras_file_path):
"""Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`."""
<|body_0|>
def extract_views_and_poses(views=None, poses=None):
"""Returns two dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeshroomParser:
def parse_cameras(cameras_file_path):
"""Parses `cameras.json`, converted from `StructureFromMotion > outputViewAndPoses`. Returns a tuple of lists `(views, poses)`."""
with open(cameras_file_path, 'r') as cameras_file:
cameras = json.loads(cameras_file.read())
... | the_stack_v2_python_sparse | src/ie/meshroomy.py | laurelkeys/ff | train | 1 | |
41a8740556569c404d258ad7acd7b39d974073d6 | [
"new_l = ListNode(0)\ndummy = new_l\nwhile True:\n if l1 is None and l2 is None:\n break\n if l1 is None:\n new_l.next = ListNode(l2.val)\n l2 = l2.next\n new_l = new_l.next\n continue\n if l2 is None:\n new_l.next = ListNode(l1.val)\n new_l = new_l.next\n ... | <|body_start_0|>
new_l = ListNode(0)
dummy = new_l
while True:
if l1 is None and l2 is None:
break
if l1 is None:
new_l.next = ListNode(l2.val)
l2 = l2.next
new_l = new_l.next
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def iter_node(self, head):
"""遍历链表 :param head: :return:"""
<|body_1|>
def add_nodes(self, value, n, pri_node):
"""批量增加新的节点 :param ... | stack_v2_sparse_classes_36k_train_001638 | 2,533 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": "遍历链表 :param head: :return:",
"name": "iter_node",
"signature": "def iter_node(self, head)"
},
{
"docstring": "批量增加新的... | 3 | stack_v2_sparse_classes_30k_test_001060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def iter_node(self, head): 遍历链表 :param head: :return:
- def add_nodes(self, value, n, pr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def iter_node(self, head): 遍历链表 :param head: :return:
- def add_nodes(self, value, n, pr... | 25c132cbc8dd710a07e64227b803d194cfe7fd9d | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def iter_node(self, head):
"""遍历链表 :param head: :return:"""
<|body_1|>
def add_nodes(self, value, n, pri_node):
"""批量增加新的节点 :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
new_l = ListNode(0)
dummy = new_l
while True:
if l1 is None and l2 is None:
break
if l1 is None:
new_l.next = ListNode... | the_stack_v2_python_sparse | HOT100/mergeTwoLists.py | shakesun/leetcode | train | 0 | |
3b57a4b14cd500d83d11002e183ff4e21af685dd | [
"super(TDRHF, self).__init__(mf, frozen=frozen)\nself.e = {}\nself.xy = {}",
"if k is None:\n k = numpy.arange(len(self._scf.kpts))\nif isinstance(k, int):\n k = [k]\nfor kk in k:\n self.e[kk], self.xy[kk] = self.__kernel__(k=kk)\nreturn (self.e, self.xy)"
] | <|body_start_0|>
super(TDRHF, self).__init__(mf, frozen=frozen)
self.e = {}
self.xy = {}
<|end_body_0|>
<|body_start_1|>
if k is None:
k = numpy.arange(len(self._scf.kpts))
if isinstance(k, int):
k = [k]
for kk in k:
self.e[kk], self.x... | TDRHF | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDRHF:
def __init__(self, mf, frozen=None):
"""Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen (int, Iterable): the number of frozen valence orbitals or the list of frozen orbitals for all... | stack_v2_sparse_classes_36k_train_001639 | 13,493 | permissive | [
{
"docstring": "Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen (int, Iterable): the number of frozen valence orbitals or the list of frozen orbitals for all k-points or multiple lists of frozen orbitals for each... | 2 | stack_v2_sparse_classes_30k_train_018096 | Implement the Python class `TDRHF` described below.
Class description:
Implement the TDRHF class.
Method signatures and docstrings:
- def __init__(self, mf, frozen=None): Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen... | Implement the Python class `TDRHF` described below.
Class description:
Implement the TDRHF class.
Method signatures and docstrings:
- def __init__(self, mf, frozen=None): Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen... | dd179a802f0a35e72d8522503172f16977c8d974 | <|skeleton|>
class TDRHF:
def __init__(self, mf, frozen=None):
"""Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen (int, Iterable): the number of frozen valence orbitals or the list of frozen orbitals for all... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TDRHF:
def __init__(self, mf, frozen=None):
"""Performs TDHF calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf (RHF): the base restricted Hartree-Fock model; frozen (int, Iterable): the number of frozen valence orbitals or the list of frozen orbitals for all k-points or m... | the_stack_v2_python_sparse | pyscf/pbc/tdscf/krhf_slow.py | sunqm/pyscf | train | 80 | |
e405d7988a62c1d40b8c40719db965e35556ad29 | [
"super(VGG16Classfier, self).__init__()\nself.flatten = P.Flatten()\nself.relu = nn.ReLU()\nself.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)\nself.fc2 = _fc(in_channels=4096, out_channels=4096)\nself.reshape = P.Reshape()\nself.dropout = nn.Dropout(p=0.5)",
"x = self.reshape(x, (-1, 7 * 7 * 512))\nx = s... | <|body_start_0|>
super(VGG16Classfier, self).__init__()
self.flatten = P.Flatten()
self.relu = nn.ReLU()
self.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)
self.fc2 = _fc(in_channels=4096, out_channels=4096)
self.reshape = P.Reshape()
self.dropout = nn.Dro... | VGG16Classfier | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
<|body_0|>
def construct(self, x):
""":param x: shape=(B, 512, 7, 7) :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(VGG16Classfier, self).__init__()
self.fla... | stack_v2_sparse_classes_36k_train_001640 | 5,998 | permissive | [
{
"docstring": "VGG16 classfier structure",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param x: shape=(B, 512, 7, 7) :return:",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005537 | Implement the Python class `VGG16Classfier` described below.
Class description:
Implement the VGG16Classfier class.
Method signatures and docstrings:
- def __init__(self): VGG16 classfier structure
- def construct(self, x): :param x: shape=(B, 512, 7, 7) :return: | Implement the Python class `VGG16Classfier` described below.
Class description:
Implement the VGG16Classfier class.
Method signatures and docstrings:
- def __init__(self): VGG16 classfier structure
- def construct(self, x): :param x: shape=(B, 512, 7, 7) :return:
<|skeleton|>
class VGG16Classfier:
def __init__(... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
<|body_0|>
def construct(self, x):
""":param x: shape=(B, 512, 7, 7) :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG16Classfier:
def __init__(self):
"""VGG16 classfier structure"""
super(VGG16Classfier, self).__init__()
self.flatten = P.Flatten()
self.relu = nn.ReLU()
self.fc1 = _fc(in_channels=7 * 7 * 512, out_channels=4096)
self.fc2 = _fc(in_channels=4096, out_channels=4... | the_stack_v2_python_sparse | official/cv/CTPN/src/CTPN/vgg16.py | mindspore-ai/models | train | 301 | |
5281f3cf435d9b7f4242ca803ef43d6855051831 | [
"seq_list = list(seq)\nif len(set(seq_list)) <= 2:\n print('The input string should have more than 2 different characters.')\n raise Exception(ValueError)\nchar_count = {}\nfor key in seq_list:\n char_count[key] = char_count.get(key, 0) + 1\nself.sorted_list = sorted(char_count.items(), key=lambda item: it... | <|body_start_0|>
seq_list = list(seq)
if len(set(seq_list)) <= 2:
print('The input string should have more than 2 different characters.')
raise Exception(ValueError)
char_count = {}
for key in seq_list:
char_count[key] = char_count.get(key, 0) + 1
... | Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree. | HuffmanTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HuffmanTree:
"""Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree."""
def __init__(self, seq: str):
"""Huffman tree encoding for a string sequence. Args: Input string with more than 2 different char... | stack_v2_sparse_classes_36k_train_001641 | 3,224 | permissive | [
{
"docstring": "Huffman tree encoding for a string sequence. Args: Input string with more than 2 different characters. Returns: Root node of the Huffman tree.",
"name": "__init__",
"signature": "def __init__(self, seq: str)"
},
{
"docstring": "Print out the Huffman encoding",
"name": "get_en... | 2 | stack_v2_sparse_classes_30k_train_020910 | Implement the Python class `HuffmanTree` described below.
Class description:
Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree.
Method signatures and docstrings:
- def __init__(self, seq: str): Huffman tree encoding for a string seq... | Implement the Python class `HuffmanTree` described below.
Class description:
Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree.
Method signatures and docstrings:
- def __init__(self, seq: str): Huffman tree encoding for a string seq... | 9adbe5fc2bce71f4c09ccf83079c44699c27fce4 | <|skeleton|>
class HuffmanTree:
"""Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree."""
def __init__(self, seq: str):
"""Huffman tree encoding for a string sequence. Args: Input string with more than 2 different char... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HuffmanTree:
"""Huffman tree object. Attributes: sorted_list: character and its frenquency in ascending order. root_node: Root node of the Huffman tree."""
def __init__(self, seq: str):
"""Huffman tree encoding for a string sequence. Args: Input string with more than 2 different characters. Retur... | the_stack_v2_python_sparse | data_structures/huffman_tree.py | 1lch2/PythonExercise | train | 1 |
c7482a4492bc592cc99600fee56a50122fb06b53 | [
"super().__init__(dev=dev, qubits=qubits, **kw)\nif len(qubits) > 1:\n raise ValueError('Currently only one qubit is allowed.')\nself.delta_f = np.Infinity\nself.iteration = 1\nself.final_init(**kw)",
"super().create_routine_template()\ntransition_name = self.get_param_value('transition_name', qubit=self.qubit... | <|body_start_0|>
super().__init__(dev=dev, qubits=qubits, **kw)
if len(qubits) > 1:
raise ValueError('Currently only one qubit is allowed.')
self.delta_f = np.Infinity
self.iteration = 1
self.final_init(**kw)
<|end_body_0|>
<|body_start_1|>
super().create_rou... | Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qubit found after the Ramsey experiment is within a specified threshold with respec... | FindFrequency | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindFrequency:
"""Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qubit found after the Ramsey experiment is... | stack_v2_sparse_classes_36k_train_001642 | 48,290 | permissive | [
{
"docstring": "Routine to find frequency of a given transmon transition. Args: dev (Device): The device which is currently measured. qubits (list): List of qubits to be calibrated. FIXME: currently only one qubit is supported. E.g., qubits = [qb1]. Keyword args: autorun (bool): Whether to run the routine autom... | 3 | stack_v2_sparse_classes_30k_train_014084 | Implement the Python class `FindFrequency` described below.
Class description:
Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qub... | Implement the Python class `FindFrequency` described below.
Class description:
Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qub... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class FindFrequency:
"""Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qubit found after the Ramsey experiment is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindFrequency:
"""Routine to find frequency of a given transmon transition. Routine steps: 1) Short (maximum 2 repetitions) :obj:`AdaptiveQubitSpectroscopy` 2) :obj:`PiPulseCalibration` (Rabi + Ramsey) 3) Decision: checks whether the new frequency of the qubit found after the Ramsey experiment is within a spe... | the_stack_v2_python_sparse | pycqed/measurement/calibration/automatic_calibration_routines/single_qubit_routines.py | QudevETH/PycQED_py3 | train | 8 |
711f41e07c4bb3e3d411357225c2232a88d00d5c | [
"self.input_features = input_features\nself.output_features = output_features\nself.max_processes = max_processes\nunique_id = uuid.uuid4().hex\nself.scratch_folder = os.path.join(arcpy.env.scratchFolder, 'CalcLocs_' + unique_id)\nLOGGER.info(f'Intermediate outputs will be written to {self.scratch_folder}.')\nos.mk... | <|body_start_0|>
self.input_features = input_features
self.output_features = output_features
self.max_processes = max_processes
unique_id = uuid.uuid4().hex
self.scratch_folder = os.path.join(arcpy.env.scratchFolder, 'CalcLocs_' + unique_id)
LOGGER.info(f'Intermediate out... | Calculate network locations for a large dataset by chunking the dataset and calculating in parallel. | ParallelLocationCalculator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelLocationCalculator:
"""Calculate network locations for a large dataset by chunking the dataset and calculating in parallel."""
def __init__(self, input_features, output_features, network_data_source, chunk_size, max_processes, travel_mode=None, search_tolerance=None, search_criteria=... | stack_v2_sparse_classes_36k_train_001643 | 17,175 | permissive | [
{
"docstring": "Calculate network locations for the input features in parallel. Run the Calculate Locations tool on chunks of the input dataset in parallel and and recombine the results. Refer to the Calculate Locations tool documentation for more information about the input parameters. https://pro.arcgis.com/e... | 3 | stack_v2_sparse_classes_30k_train_003723 | Implement the Python class `ParallelLocationCalculator` described below.
Class description:
Calculate network locations for a large dataset by chunking the dataset and calculating in parallel.
Method signatures and docstrings:
- def __init__(self, input_features, output_features, network_data_source, chunk_size, max_... | Implement the Python class `ParallelLocationCalculator` described below.
Class description:
Calculate network locations for a large dataset by chunking the dataset and calculating in parallel.
Method signatures and docstrings:
- def __init__(self, input_features, output_features, network_data_source, chunk_size, max_... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class ParallelLocationCalculator:
"""Calculate network locations for a large dataset by chunking the dataset and calculating in parallel."""
def __init__(self, input_features, output_features, network_data_source, chunk_size, max_processes, travel_mode=None, search_tolerance=None, search_criteria=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelLocationCalculator:
"""Calculate network locations for a large dataset by chunking the dataset and calculating in parallel."""
def __init__(self, input_features, output_features, network_data_source, chunk_size, max_processes, travel_mode=None, search_tolerance=None, search_criteria=None, search_... | the_stack_v2_python_sparse | transit-network-analysis-tools/parallel_calculate_locations.py | Esri/public-transit-tools | train | 155 |
9fe296b796dc72ff6d0bfdde50616a94aa97a121 | [
"version_info = {'scm_type': scm_type, 'status': False, 'error_msg': None, 'folder': a_path, 'url': ''}\ncmd_output, valid = SysUtils.get_command_output(a_cmd, arg_cwd=a_path)\nif not valid:\n version_info['error_msg'] = 'Command error: %s' % cmd_output\nelif not cmd_output:\n version_info['error_msg'] = 'Rev... | <|body_start_0|>
version_info = {'scm_type': scm_type, 'status': False, 'error_msg': None, 'folder': a_path, 'url': ''}
cmd_output, valid = SysUtils.get_command_output(a_cmd, arg_cwd=a_path)
if not valid:
version_info['error_msg'] = 'Command error: %s' % cmd_output
elif not c... | This class contains several methods used to interface with the various scm systems used by the project. | VersionCtrlUtils | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionCtrlUtils:
"""This class contains several methods used to interface with the various scm systems used by the project."""
def get_scm_data(cls, scm_type, a_path, a_cmd, a_cwd=None):
"""Returns an initialized data structure to hold SCM version data. :param str scm_type: 'svn' or... | stack_v2_sparse_classes_36k_train_001644 | 7,004 | permissive | [
{
"docstring": "Returns an initialized data structure to hold SCM version data. :param str scm_type: 'svn' or 'git' :param str a_path: Project base folder :param str a_cmd: Command to return scm status detail :param str a_cwd: :return: dict containing SCM data :rtype: dict",
"name": "get_scm_data",
"sig... | 6 | stack_v2_sparse_classes_30k_train_020338 | Implement the Python class `VersionCtrlUtils` described below.
Class description:
This class contains several methods used to interface with the various scm systems used by the project.
Method signatures and docstrings:
- def get_scm_data(cls, scm_type, a_path, a_cmd, a_cwd=None): Returns an initialized data structur... | Implement the Python class `VersionCtrlUtils` described below.
Class description:
This class contains several methods used to interface with the various scm systems used by the project.
Method signatures and docstrings:
- def get_scm_data(cls, scm_type, a_path, a_cmd, a_cwd=None): Returns an initialized data structur... | 144fb52a99cde89e73552f88c872c05d2e90b603 | <|skeleton|>
class VersionCtrlUtils:
"""This class contains several methods used to interface with the various scm systems used by the project."""
def get_scm_data(cls, scm_type, a_path, a_cmd, a_cwd=None):
"""Returns an initialized data structure to hold SCM version data. :param str scm_type: 'svn' or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionCtrlUtils:
"""This class contains several methods used to interface with the various scm systems used by the project."""
def get_scm_data(cls, scm_type, a_path, a_cmd, a_cwd=None):
"""Returns an initialized data structure to hold SCM version data. :param str scm_type: 'svn' or 'git' :param... | the_stack_v2_python_sparse | utils/regression/common/version_ctrl_utils.py | openhwgroup/force-riscv | train | 190 |
e757b08074273917b4577bf2ac8836a4f5dd14fd | [
"self.resultfile = Utils.config_Utils.resultfile\nself.datafile = Utils.config_Utils.datafile\nself.logsdir = Utils.config_Utils.logsdir\nself.filename = Utils.config_Utils.filename\nself.logfile = Utils.config_Utils.logfile\nself.map_function = {'INFO': print_info, 'DEBUG': print_debug, 'WARN': print_warning, 'ERR... | <|body_start_0|>
self.resultfile = Utils.config_Utils.resultfile
self.datafile = Utils.config_Utils.datafile
self.logsdir = Utils.config_Utils.logsdir
self.filename = Utils.config_Utils.filename
self.logfile = Utils.config_Utils.logfile
self.map_function = {'INFO': print_... | class LogActions having keywords that are used for logging within test | LogActions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
<|body_0|>
def log_message(self, message=None, type='INFO', list_message=None, dict_message=None):
"""Keyword to print the given message... | stack_v2_sparse_classes_36k_train_001645 | 3,290 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Keyword to print the given message. :Arguments: 1. type = message severity level INFO,WARN,DEBUG,ERROR are supported values 2. message = message to be printed, 3. list_message = list of message... | 2 | stack_v2_sparse_classes_30k_train_010798 | Implement the Python class `LogActions` described below.
Class description:
class LogActions having keywords that are used for logging within test
Method signatures and docstrings:
- def __init__(self): Constructor
- def log_message(self, message=None, type='INFO', list_message=None, dict_message=None): Keyword to pr... | Implement the Python class `LogActions` described below.
Class description:
class LogActions having keywords that are used for logging within test
Method signatures and docstrings:
- def __init__(self): Constructor
- def log_message(self, message=None, type='INFO', list_message=None, dict_message=None): Keyword to pr... | 685761cf044182ec88ce86a942d4be1e150a1256 | <|skeleton|>
class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
<|body_0|>
def log_message(self, message=None, type='INFO', list_message=None, dict_message=None):
"""Keyword to print the given message... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogActions:
"""class LogActions having keywords that are used for logging within test"""
def __init__(self):
"""Constructor"""
self.resultfile = Utils.config_Utils.resultfile
self.datafile = Utils.config_Utils.datafile
self.logsdir = Utils.config_Utils.logsdir
self... | the_stack_v2_python_sparse | warrior/Actions/LogActions/log_actions.py | warriorframework/warriorframework | train | 25 |
0cabe2dc7962dd2da8c1dbe0cd495ded4f730ba8 | [
"self.contents = contents\nself.source = source\nself.version = version\nself.templates = ConfigTemplates(template_paths)\nself.data: Union[dict, None] = None\nself.errors = []",
"if self.data is not None and (not self.errors):\n return\ntry:\n self.data = yaml.safe_load(self.contents)\nexcept Exception as ... | <|body_start_0|>
self.contents = contents
self.source = source
self.version = version
self.templates = ConfigTemplates(template_paths)
self.data: Union[dict, None] = None
self.errors = []
<|end_body_0|>
<|body_start_1|>
if self.data is not None and (not self.erro... | ConfigSpec | [
"BSD-3-Clause",
"MIT",
"BSD-3-Clause-Modification",
"Unlicense",
"Apache-2.0",
"LGPL-3.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigSpec:
def __init__(self, contents: str, template_paths: List[str]=None, source: str=None, version: str=None):
"""Parameters: contents: the raw text contents of a spec template_paths: a sequence of directories that will take precedence when looking for templates source: a textual re... | stack_v2_sparse_classes_36k_train_001646 | 1,764 | permissive | [
{
"docstring": "Parameters: contents: the raw text contents of a spec template_paths: a sequence of directories that will take precedence when looking for templates source: a textual representation of what the spec refers to, usually an integration name version: the version of the spec to default to if the spec... | 2 | null | Implement the Python class `ConfigSpec` described below.
Class description:
Implement the ConfigSpec class.
Method signatures and docstrings:
- def __init__(self, contents: str, template_paths: List[str]=None, source: str=None, version: str=None): Parameters: contents: the raw text contents of a spec template_paths: ... | Implement the Python class `ConfigSpec` described below.
Class description:
Implement the ConfigSpec class.
Method signatures and docstrings:
- def __init__(self, contents: str, template_paths: List[str]=None, source: str=None, version: str=None): Parameters: contents: the raw text contents of a spec template_paths: ... | 406072e4294edff5b46b513f0cdf7c2c00fac9d2 | <|skeleton|>
class ConfigSpec:
def __init__(self, contents: str, template_paths: List[str]=None, source: str=None, version: str=None):
"""Parameters: contents: the raw text contents of a spec template_paths: a sequence of directories that will take precedence when looking for templates source: a textual re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigSpec:
def __init__(self, contents: str, template_paths: List[str]=None, source: str=None, version: str=None):
"""Parameters: contents: the raw text contents of a spec template_paths: a sequence of directories that will take precedence when looking for templates source: a textual representation o... | the_stack_v2_python_sparse | datadog_checks_dev/datadog_checks/dev/tooling/configuration/core.py | DataDog/integrations-core | train | 852 | |
a6acebb61291716f567fc716a84334a0552fcf38 | [
"if not request.user.is_superuser:\n return HttpResponseForbidden()\nreturn super(ConfigureView, self).get(request)",
"if not request.user.is_superuser:\n return HttpResponseForbidden()\nextension = ReviewBotExtension.instance\nshould_save = False\nnew_user = request.POST.get('reviewbot_user')\nif new_user:... | <|body_start_0|>
if not request.user.is_superuser:
return HttpResponseForbidden()
return super(ConfigureView, self).get(request)
<|end_body_0|>
<|body_start_1|>
if not request.user.is_superuser:
return HttpResponseForbidden()
extension = ReviewBotExtension.instan... | The basic "Configure" page for Review Bot. | ConfigureView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_36k_train_001647 | 11,244 | permissive | [
{
"docstring": "Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save the extension configuration. Args: request (django.http.Htt... | 3 | null | Implement the Python class `ConfigureView` described below.
Class description:
The basic "Configure" page for Review Bot.
Method signatures and docstrings:
- def get(self, request): Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The resp... | Implement the Python class `ConfigureView` described below.
Class description:
The basic "Configure" page for Review Bot.
Method signatures and docstrings:
- def get(self, request): Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The resp... | b59b566e127b5ef1b08f3189f1aa0194b7437d94 | <|skeleton|>
class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigureView:
"""The basic "Configure" page for Review Bot."""
def get(self, request):
"""Render and return the admin page. Args: request (django.http.HttpRequest): The HTTP request. Returns: django.http.HttpResponse: The response."""
if not request.user.is_superuser:
return ... | the_stack_v2_python_sparse | extension/reviewbotext/views.py | reviewboard/ReviewBot | train | 110 |
aa388f465c2a3ee1b64a1361a0ef7b038d367547 | [
"value = proposal['value']\nif value is None:\n return value\nif self.min and self.min > value:\n value = max(value, self.min)\nif self.max and self.max < value:\n value = min(value, self.max)\nreturn value",
"min = proposal['value']\nif min is None:\n return min\nif self.max and min > self.max:\n ... | <|body_start_0|>
value = proposal['value']
if value is None:
return value
if self.min and self.min > value:
value = max(value, self.min)
if self.max and self.max < value:
value = min(value, self.max)
return value
<|end_body_0|>
<|body_start_1|... | Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The time step to use for the picker, in seco... | TimePicker | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The ti... | stack_v2_sparse_classes_36k_train_001648 | 2,779 | permissive | [
{
"docstring": "Cap and floor value",
"name": "_validate_value",
"signature": "def _validate_value(self, proposal)"
},
{
"docstring": "Enforce min <= value <= max",
"name": "_validate_min",
"signature": "def _validate_min(self, proposal)"
},
{
"docstring": "Enforce min <= value <... | 3 | stack_v2_sparse_classes_30k_train_016999 | Implement the Python class `TimePicker` described below.
Class description:
Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowe... | Implement the Python class `TimePicker` described below.
Class description:
Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowe... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimePicker:
"""Display a widget for picking times. Parameters ---------- value: datetime.time The current value of the widget. disabled: bool Whether to disable user changes. min: datetime.time The lower allowed time bound max: datetime.time The upper allowed time bound step: float | 'any' The time step to us... | the_stack_v2_python_sparse | contrib/python/ipywidgets/py3/ipywidgets/widgets/widget_time.py | catboost/catboost | train | 8,012 |
693ec41df5a0c9c2edb37ce54ae603f3ee599f6d | [
"self.W = W\nself.b = b\nself.x = None\nself.dW = None\nself.db = None",
"self.x = x\nout = np.dot(x, self.W) + self.b\nreturn out",
"dx = np.dot(dout, self.W.T)\nself.dW = np.dot(self.x.T, dout)\nself.db = np.sum(dout, axis=0)\nreturn dx"
] | <|body_start_0|>
self.W = W
self.b = b
self.x = None
self.dW = None
self.db = None
<|end_body_0|>
<|body_start_1|>
self.x = x
out = np.dot(x, self.W) + self.b
return out
<|end_body_1|>
<|body_start_2|>
dx = np.dot(dout, self.W.T)
self.dW ... | Affine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Affine:
def __init__(self, W, b):
"""Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス"""
<|body_0|>
def forward(self, x):
"""順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray: 出力"""
<|body_1|>
def backward(self, dout):
"""逆伝播 A... | stack_v2_sparse_classes_36k_train_001649 | 1,054 | no_license | [
{
"docstring": "Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス",
"name": "__init__",
"signature": "def __init__(self, W, b)"
},
{
"docstring": "順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray: 出力",
"name": "forward",
"signature": "def forward(self, x)"
},
{
... | 3 | null | Implement the Python class `Affine` described below.
Class description:
Implement the Affine class.
Method signatures and docstrings:
- def __init__(self, W, b): Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス
- def forward(self, x): 順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray: 出力
- def back... | Implement the Python class `Affine` described below.
Class description:
Implement the Affine class.
Method signatures and docstrings:
- def __init__(self, W, b): Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス
- def forward(self, x): 順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray: 出力
- def back... | 72b364ad4da8485a201ebdaaa430fd2e95681b0a | <|skeleton|>
class Affine:
def __init__(self, W, b):
"""Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス"""
<|body_0|>
def forward(self, x):
"""順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray: 出力"""
<|body_1|>
def backward(self, dout):
"""逆伝播 A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Affine:
def __init__(self, W, b):
"""Affineレイヤー Args: W (numpy.ndarray): 重み b (numpy.ndarray): バイアス"""
self.W = W
self.b = b
self.x = None
self.dW = None
self.db = None
def forward(self, x):
"""順伝播 Args: x (numpy.ndarray): 入力 Returns: numpy.ndarray:... | the_stack_v2_python_sparse | Dfz/Cp5/c5_4_affine.py | masa-k0101/Self-Study_python | train | 1 | |
97db9feb3ced8eef878fc21a1a09997603988f39 | [
"logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')\ntestfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')\nlog2xml.convert(logfile, testfile)\nminidom.parse(testfile)",
"logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_failure.log')\ntestfile = os.path.join(t... | <|body_start_0|>
logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')
testfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')
log2xml.convert(logfile, testfile)
minidom.parse(testfile)
<|end_body_0|>
<|body_start_1|>
logfile = os.path.join(os.en... | Acceptance tests for log2xml.py | Log2XMLTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
<|body_0|>
def test_log_utf16_conversion(self):
"""Convert a log into xml."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logfile = ... | stack_v2_sparse_classes_36k_train_001650 | 1,720 | no_license | [
{
"docstring": "Convert a log into xml.",
"name": "test_log_conversion",
"signature": "def test_log_conversion(self)"
},
{
"docstring": "Convert a log into xml.",
"name": "test_log_utf16_conversion",
"signature": "def test_log_utf16_conversion(self)"
}
] | 2 | null | Implement the Python class `Log2XMLTest` described below.
Class description:
Acceptance tests for log2xml.py
Method signatures and docstrings:
- def test_log_conversion(self): Convert a log into xml.
- def test_log_utf16_conversion(self): Convert a log into xml. | Implement the Python class `Log2XMLTest` described below.
Class description:
Acceptance tests for log2xml.py
Method signatures and docstrings:
- def test_log_conversion(self): Convert a log into xml.
- def test_log_utf16_conversion(self): Convert a log into xml.
<|skeleton|>
class Log2XMLTest:
"""Acceptance test... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
<|body_0|>
def test_log_utf16_conversion(self):
"""Convert a log into xml."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log2XMLTest:
"""Acceptance tests for log2xml.py"""
def test_log_conversion(self):
"""Convert a log into xml."""
logfile = os.path.join(os.environ['TEST_DATA'], 'data', 'log2xml_test.log')
testfile = os.path.join(tempfile.gettempdir(), 'log2xml_test.xml')
log2xml.convert(lo... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_log2xml.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
d005a681b544e2eb69e44eefbea590f9c6290906 | [
"schema = LoginSchema()\ndata, errors = schema.load(request.json)\nif errors:\n return (errors, 400)\ntry:\n session_token = auth.dataclient.login(data['email'], data['password'])\n SIG_LOGGED_IN.send(DataClient.query.filter_by(email=data['email']).first())\n return SessionSchema().dump({'session_token'... | <|body_start_0|>
schema = LoginSchema()
data, errors = schema.load(request.json)
if errors:
return (errors, 400)
try:
session_token = auth.dataclient.login(data['email'], data['password'])
SIG_LOGGED_IN.send(DataClient.query.filter_by(email=data['email... | SessionResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionResource:
def post(self):
"""Login route :return:"""
<|body_0|>
def delete(self):
"""Logout route :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
schema = LoginSchema()
data, errors = schema.load(request.json)
if erro... | stack_v2_sparse_classes_36k_train_001651 | 3,606 | no_license | [
{
"docstring": "Login route :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Logout route :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001037 | Implement the Python class `SessionResource` described below.
Class description:
Implement the SessionResource class.
Method signatures and docstrings:
- def post(self): Login route :return:
- def delete(self): Logout route :return: | Implement the Python class `SessionResource` described below.
Class description:
Implement the SessionResource class.
Method signatures and docstrings:
- def post(self): Login route :return:
- def delete(self): Logout route :return:
<|skeleton|>
class SessionResource:
def post(self):
"""Login route :ret... | e940e841a115bc7f3b9953ccb6815ae5470b29d2 | <|skeleton|>
class SessionResource:
def post(self):
"""Login route :return:"""
<|body_0|>
def delete(self):
"""Logout route :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionResource:
def post(self):
"""Login route :return:"""
schema = LoginSchema()
data, errors = schema.load(request.json)
if errors:
return (errors, 400)
try:
session_token = auth.dataclient.login(data['email'], data['password'])
SI... | the_stack_v2_python_sparse | backend/app/api/Session.py | yeldiRium/st3k101 | train | 1 | |
fe8e4d2b10cb644bb5e60d97d2a77470648f8818 | [
"if self.config.model_arch == ModelArchitecture.F_NET:\n self._init_fourier_transform()\nkey = random.PRNGKey(self.random_seed)\nencoder_blocks = []\nfor layer in range(self.config.num_layers):\n key, mixing_key = random.split(key)\n mixing_arch = ModelArchitecture.BERT if self._is_attention_layer(layer) e... | <|body_start_0|>
if self.config.model_arch == ModelArchitecture.F_NET:
self._init_fourier_transform()
key = random.PRNGKey(self.random_seed)
encoder_blocks = []
for layer in range(self.config.num_layers):
key, mixing_key = random.split(key)
mixing_arch... | Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture. | EncoderModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_36k_train_001652 | 15,842 | permissive | [
{
"docstring": "Initializes encoder with config-dependent mixing layer.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Applies model on the inputs. Args: input_ids: Tokenized inputs of shape <int>[BATCH_SIZE, MAX_SEQ_LENGTH]. input_mask: <bool>[BATCH_SIZE, MAX_SEQ_LENGTH] m... | 5 | stack_v2_sparse_classes_30k_train_020871 | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
if sel... | the_stack_v2_python_sparse | f_net/models.py | Jimmy-INL/google-research | train | 1 |
0183af59583db3d82a6217e47e0d5d71b1d0d880 | [
"predictor = DefaultPredictor(cfg)\nif n != 0:\n table_dicts = random.sample(table_dicts, n)\npredictions = {}\nfor table_dict in table_dicts:\n file_path = table_dict['file_name']\n print('file_path: ', file_path)\n img = cv2.imread(file_path)\n outputs = predictor(img)\n table_name = file_path.s... | <|body_start_0|>
predictor = DefaultPredictor(cfg)
if n != 0:
table_dicts = random.sample(table_dicts, n)
predictions = {}
for table_dict in table_dicts:
file_path = table_dict['file_name']
print('file_path: ', file_path)
img = cv2.imread(f... | Predict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predict:
def predict_boxes(self, cfg, table_dicts, table_metadata, pred_path, n=0):
"""Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary with annotations table_metadata: registered metadata pred_path: a path to save drawn prediction... | stack_v2_sparse_classes_36k_train_001653 | 2,446 | no_license | [
{
"docstring": "Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary with annotations table_metadata: registered metadata pred_path: a path to save drawn predictions, if \"\" - do not save n: number of randomly choosen tables, if 0 - all tables Returns: a dic... | 2 | stack_v2_sparse_classes_30k_train_010357 | Implement the Python class `Predict` described below.
Class description:
Implement the Predict class.
Method signatures and docstrings:
- def predict_boxes(self, cfg, table_dicts, table_metadata, pred_path, n=0): Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary... | Implement the Python class `Predict` described below.
Class description:
Implement the Predict class.
Method signatures and docstrings:
- def predict_boxes(self, cfg, table_dicts, table_metadata, pred_path, n=0): Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary... | 4c9970151294006fdafaba3c2ca84b7c04da97e7 | <|skeleton|>
class Predict:
def predict_boxes(self, cfg, table_dicts, table_metadata, pred_path, n=0):
"""Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary with annotations table_metadata: registered metadata pred_path: a path to save drawn prediction... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predict:
def predict_boxes(self, cfg, table_dicts, table_metadata, pred_path, n=0):
"""Build predtion boxes for columns/rows/cells Args: cfg: the trained model config table_dicts: a dictionary with annotations table_metadata: registered metadata pred_path: a path to save drawn predictions, if "" - do ... | the_stack_v2_python_sparse | detectron2_tables/detectron2_predict.py | akmaral-yes/table_structure_recognition_using_detectron2 | train | 4 | |
bf5216eb3650efbd05e3e6070c0d4ae45a12df34 | [
"super(LF_Multi_Res, self).__init__()\nself.layer1_multistream = layer1_multistream(filt_num, in_channels)\nself.layer2_merged = layer2_merged(int(4 * filt_num), conv_depth)\nself.layer3_last = layer3_last(int(4 * filt_num))",
"residual = train_data_0[:, 4:5, :, :]\n' 4-Stream layer : Conv - Relu'\nmid_0d = self.... | <|body_start_0|>
super(LF_Multi_Res, self).__init__()
self.layer1_multistream = layer1_multistream(filt_num, in_channels)
self.layer2_merged = layer2_merged(int(4 * filt_num), conv_depth)
self.layer3_last = layer3_last(int(4 * filt_num))
<|end_body_0|>
<|body_start_1|>
residual ... | LF_Multi_Res | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LF_Multi_Res:
def __init__(self, filt_num, in_channels, conv_depth):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, train_data_0, train_data_90, train_data_45, train_data_135):
"""In the... | stack_v2_sparse_classes_36k_train_001654 | 2,476 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, filt_num, in_channels, conv_depth)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a... | 2 | stack_v2_sparse_classes_30k_train_017007 | Implement the Python class `LF_Multi_Res` described below.
Class description:
Implement the LF_Multi_Res class.
Method signatures and docstrings:
- def __init__(self, filt_num, in_channels, conv_depth): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, tr... | Implement the Python class `LF_Multi_Res` described below.
Class description:
Implement the LF_Multi_Res class.
Method signatures and docstrings:
- def __init__(self, filt_num, in_channels, conv_depth): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, tr... | bd8fa2f8f598d189ba6c5145fd536e95e91b7ed3 | <|skeleton|>
class LF_Multi_Res:
def __init__(self, filt_num, in_channels, conv_depth):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, train_data_0, train_data_90, train_data_45, train_data_135):
"""In the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LF_Multi_Res:
def __init__(self, filt_num, in_channels, conv_depth):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(LF_Multi_Res, self).__init__()
self.layer1_multistream = layer1_multistream(filt_num, in_channels)
self.... | the_stack_v2_python_sparse | LF_Multi_Res.py | shuozh/PytorchLearn | train | 0 | |
86df5f8b13401771eef7316d913ac9570fc5e948 | [
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nmy_survey.store_responses('English')\nself.assertIn('English', my_survey.responses)",
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nresponses = ['English', 'Spanish... | <|body_start_0|>
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_responses('English')
self.assertIn('English', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'What language did you first learn to spe... | Tests for the class AnonymousSurvey | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly... | stack_v2_sparse_classes_36k_train_001655 | 850 | no_license | [
{
"docstring": "Test that a single response is stored properly.",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "Test that three individual responses are stored properly.",
"name": "test_store_three_responses",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_015678 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Tests for the class AnonymousSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Test that a single response is stored properly.
- def test_store_three_responses(self): Test that three individual response... | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Tests for the class AnonymousSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Test that a single response is stored properly.
- def test_store_three_responses(self): Test that three individual response... | cc8bf7577c69544e67bf1ddada6dd4f3165610cb | <|skeleton|>
class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_respons... | the_stack_v2_python_sparse | chapter11_tetsting/2_test_class/test_survey.py | yigitkarabiyik/python_crash_course_answers | train | 1 |
125c7e05993e638843671ed269afd2b3a8322c5d | [
"results = []\n\ndef preOrderTraversal(root):\n if not root:\n results.append('None')\n else:\n results.append(str(root.val))\n preOrderTraversal(root.left)\n preOrderTraversal(root.right)\npreOrderTraversal(root)\nreturn ','.join(results)",
"def rebuild(l):\n if l[0] == 'None... | <|body_start_0|>
results = []
def preOrderTraversal(root):
if not root:
results.append('None')
else:
results.append(str(root.val))
preOrderTraversal(root.left)
preOrderTraversal(root.right)
preOrderTraversal... | 层/先序遍历OK 但是None要补全 | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""层/先序遍历OK 但是None要补全"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1... | stack_v2_sparse_classes_36k_train_001656 | 3,147 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_004983 | Implement the Python class `Codec` described below.
Class description:
层/先序遍历OK 但是None要补全
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNod... | Implement the Python class `Codec` described below.
Class description:
层/先序遍历OK 但是None要补全
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNod... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class Codec:
"""层/先序遍历OK 但是None要补全"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""层/先序遍历OK 但是None要补全"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
results = []
def preOrderTraversal(root):
if not root:
results.append('None')
else:
results... | the_stack_v2_python_sparse | python/_0001_0500/0297_serialize-and-deserialize-binary-tree.py | Wang-Yann/LeetCodeMe | train | 0 |
9703a35cbd01ef99dfb052c4c2526f8ffe339728 | [
"store = {}\nfor i, row in enumerate(mat):\n count = sum(row)\n if count in store:\n current = store.get(count)\n store[count] = current + [i]\n else:\n store[count] = [i]\nans = []\nfor keys in sorted(store):\n for row in store[keys]:\n ans.append(row)\nreturn ans[:k]",
"m... | <|body_start_0|>
store = {}
for i, row in enumerate(mat):
count = sum(row)
if count in store:
current = store.get(count)
store[count] = current + [i]
else:
store[count] = [i]
ans = []
for keys in sorted(s... | Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online submissions for The K Weakest Rows in a Matrix. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online submissions for The K Weakest Rows in a M... | stack_v2_sparse_classes_36k_train_001657 | 1,864 | no_license | [
{
"docstring": ":type mat: List[List[int]] :type k: int :rtype: List[int]",
"name": "kWeakestRows",
"signature": "def kWeakestRows(self, mat, k)"
},
{
"docstring": ":type mat: List[List[int]] :type k: int :rtype: List[int]",
"name": "kWeakestRows",
"signature": "def kWeakestRows(self, ma... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online su... | Implement the Python class `Solution` described below.
Class description:
Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online su... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online submissions for The K Weakest Rows in a M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Scan of the matrix + sort dictionary runtime: O(n * m) + O(n lgn), where n = len(mat) Runtime: 96 ms, faster than 72.17% of Python online submissions for The K Weakest Rows in a Matrix. Memory Usage: 13.4 MB, less than 98.38% of Python online submissions for The K Weakest Rows in a Matrix."""
... | the_stack_v2_python_sparse | 1337-the_k_weakest_rows_in_a_matrix.py | stevestar888/leetcode-problems | train | 2 |
ad3e822a848fb09cb289c5f4a5df3359ac7a962e | [
"if self.request.method == 'GET':\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveRequest())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method in ('PUT', 'PATCH'):\n return (permissions.IsAuthenticated(), IsInActiveCommu... | <|body_start_0|>
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveRequest())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method in ('PUT', 'PATCH'):
... | Request view set | RequestViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestViewSet:
"""Request view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List requests"""
<|b... | stack_v2_sparse_classes_36k_train_001658 | 27,778 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List requests",
"name": "list",
... | 5 | stack_v2_sparse_classes_30k_train_003355 | Implement the Python class `RequestViewSet` described below.
Class description:
Request view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List requests
- def create(self, request, *... | Implement the Python class `RequestViewSet` described below.
Class description:
Request view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List requests
- def create(self, request, *... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class RequestViewSet:
"""Request view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List requests"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestViewSet:
"""Request view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsAbleToRetrieveRequest())
elif self.request.method == 'POST':
return (per... | the_stack_v2_python_sparse | membership/views.py | 810Teams/clubs-and-events-backend | train | 3 |
9892ad5ee58e7127f37626b9651d03f46fb4c87e | [
"self.global_configs = global_configs\nself.scanner_configs = scanner_configs\nself.service_config = service_config\nself.model_name = model_name\nself.snapshot_timestamp = snapshot_timestamp\nself.scanner_name = scanner_name",
"runnable_scanners = []\nif self.scanner_name:\n scanner = self._instantiate_scanne... | <|body_start_0|>
self.global_configs = global_configs
self.scanner_configs = scanner_configs
self.service_config = service_config
self.model_name = model_name
self.snapshot_timestamp = snapshot_timestamp
self.scanner_name = scanner_name
<|end_body_0|>
<|body_start_1|>
... | Scanner Builder. | ScannerBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner config... | stack_v2_sparse_classes_36k_train_001659 | 5,021 | permissive | [
{
"docstring": "Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner configurations. service_config (ServiceConfig): Service configuration. model_name (str): name of the data model snapshot_timestamp (str): The snapshot timestamp scanner_name (str):... | 3 | null | Implement the Python class `ScannerBuilder` described below.
Class description:
Scanner Builder.
Method signatures and docstrings:
- def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None): Initialize the scanner builder. Args: global_configs (dict): Glob... | Implement the Python class `ScannerBuilder` described below.
Class description:
Scanner Builder.
Method signatures and docstrings:
- def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None): Initialize the scanner builder. Args: global_configs (dict): Glob... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner config... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScannerBuilder:
"""Scanner Builder."""
def __init__(self, global_configs, scanner_configs, service_config, model_name, snapshot_timestamp, scanner_name=None):
"""Initialize the scanner builder. Args: global_configs (dict): Global configurations. scanner_configs (dict): Scanner configurations. ser... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/scanner_builder.py | kevensen/forseti-security | train | 1 |
3f67d9d72ce564d2b1e35bbbe28fdb22ef5b5b69 | [
"f = False\nif x < 0:\n f = True\nx2 = list(reversed(str(abs(x))))\nif f:\n x2.insert(0, '-')\nlast = int(''.join(x2))\nif abs(last) > 2147483647:\n return 0\nelse:\n return last",
"sum = 0\nif x < 0:\n y = -x\nelse:\n y = x\nwhile y > 0:\n sum = sum * 10 + y % 10\n y = y // 10\nprint(sum)... | <|body_start_0|>
f = False
if x < 0:
f = True
x2 = list(reversed(str(abs(x))))
if f:
x2.insert(0, '-')
last = int(''.join(x2))
if abs(last) > 2147483647:
return 0
else:
return last
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f = False
if x < 0:
f = True
x2 = list(reversed(... | stack_v2_sparse_classes_36k_train_001660 | 1,545 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000753 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int ... | b0f498ebe84e46b7e17e94759dd462891dcc8f85 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
f = False
if x < 0:
f = True
x2 = list(reversed(str(abs(x))))
if f:
x2.insert(0, '-')
last = int(''.join(x2))
if abs(last) > 2147483647:
return 0
e... | the_stack_v2_python_sparse | 初级算法/string_2.py | wulinlw/leetcode_cn | train | 0 | |
3cd644b3e8210074f84db0de9f3792795d209543 | [
"input_lines = ['12\\n11\\n190\\n0', '']\nexpected = [[12, 11, 190, 0], []]\nfor index, case in enumerate(input_lines):\n ints = day17_lib.parse_input(case)\n self.assertListEqual(ints, expected[index])",
"input_containers = [[20, 15, 10, 5, 5]]\ninput_capacities = [25]\nexpected = [4]\nfor index, container... | <|body_start_0|>
input_lines = ['12\n11\n190\n0', '']
expected = [[12, 11, 190, 0], []]
for index, case in enumerate(input_lines):
ints = day17_lib.parse_input(case)
self.assertListEqual(ints, expected[index])
<|end_body_0|>
<|body_start_1|>
input_containers = [[... | Tests for `day13_lib.py` | Day17TestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day17TestCase:
"""Tests for `day13_lib.py`"""
def test_parse_input(self):
"""Tests for the parse_input method"""
<|body_0|>
def test_get_exact_combinations(self):
"""Tests for the get_exact_combinations method"""
<|body_1|>
def test_get_exact_min_com... | stack_v2_sparse_classes_36k_train_001661 | 1,607 | permissive | [
{
"docstring": "Tests for the parse_input method",
"name": "test_parse_input",
"signature": "def test_parse_input(self)"
},
{
"docstring": "Tests for the get_exact_combinations method",
"name": "test_get_exact_combinations",
"signature": "def test_get_exact_combinations(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004708 | Implement the Python class `Day17TestCase` described below.
Class description:
Tests for `day13_lib.py`
Method signatures and docstrings:
- def test_parse_input(self): Tests for the parse_input method
- def test_get_exact_combinations(self): Tests for the get_exact_combinations method
- def test_get_exact_min_combina... | Implement the Python class `Day17TestCase` described below.
Class description:
Tests for `day13_lib.py`
Method signatures and docstrings:
- def test_parse_input(self): Tests for the parse_input method
- def test_get_exact_combinations(self): Tests for the get_exact_combinations method
- def test_get_exact_min_combina... | aa8dc35471c57df3c952233ef5b5ba758dfc0ae3 | <|skeleton|>
class Day17TestCase:
"""Tests for `day13_lib.py`"""
def test_parse_input(self):
"""Tests for the parse_input method"""
<|body_0|>
def test_get_exact_combinations(self):
"""Tests for the get_exact_combinations method"""
<|body_1|>
def test_get_exact_min_com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Day17TestCase:
"""Tests for `day13_lib.py`"""
def test_parse_input(self):
"""Tests for the parse_input method"""
input_lines = ['12\n11\n190\n0', '']
expected = [[12, 11, 190, 0], []]
for index, case in enumerate(input_lines):
ints = day17_lib.parse_input(case)... | the_stack_v2_python_sparse | day17_test.py | Elgolfin/adventofcode-2015-py | train | 0 |
4b5138967c1399153a6017b312fffa391e733bdc | [
"self.dt_in = datetime(2017, 2, 17, 6, 0)\nself.cftime_in = cftime.DatetimeGregorian(2017, 2, 17, hour=6, minute=0)\nself.expected = 1487311200.0",
"result = datetime_to_iris_time(self.dt_in)\nself.assertIsInstance(result, np.int64)\nself.assertEqual(result, self.expected)",
"result = datetime_to_iris_time(self... | <|body_start_0|>
self.dt_in = datetime(2017, 2, 17, 6, 0)
self.cftime_in = cftime.DatetimeGregorian(2017, 2, 17, hour=6, minute=0)
self.expected = 1487311200.0
<|end_body_0|>
<|body_start_1|>
result = datetime_to_iris_time(self.dt_in)
self.assertIsInstance(result, np.int64)
... | Test the datetime_to_iris_time function. | Test_datetime_to_iris_time | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_datetime_to_iris_time:
"""Test the datetime_to_iris_time function."""
def setUp(self):
"""Define datetime for use in tests."""
<|body_0|>
def test_seconds(self):
"""Test datetime_to_iris_time returns float with expected value in seconds"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_001662 | 19,622 | permissive | [
{
"docstring": "Define datetime for use in tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test datetime_to_iris_time returns float with expected value in seconds",
"name": "test_seconds",
"signature": "def test_seconds(self)"
},
{
"docstring": "Test d... | 3 | null | Implement the Python class `Test_datetime_to_iris_time` described below.
Class description:
Test the datetime_to_iris_time function.
Method signatures and docstrings:
- def setUp(self): Define datetime for use in tests.
- def test_seconds(self): Test datetime_to_iris_time returns float with expected value in seconds
... | Implement the Python class `Test_datetime_to_iris_time` described below.
Class description:
Test the datetime_to_iris_time function.
Method signatures and docstrings:
- def setUp(self): Define datetime for use in tests.
- def test_seconds(self): Test datetime_to_iris_time returns float with expected value in seconds
... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_datetime_to_iris_time:
"""Test the datetime_to_iris_time function."""
def setUp(self):
"""Define datetime for use in tests."""
<|body_0|>
def test_seconds(self):
"""Test datetime_to_iris_time returns float with expected value in seconds"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_datetime_to_iris_time:
"""Test the datetime_to_iris_time function."""
def setUp(self):
"""Define datetime for use in tests."""
self.dt_in = datetime(2017, 2, 17, 6, 0)
self.cftime_in = cftime.DatetimeGregorian(2017, 2, 17, hour=6, minute=0)
self.expected = 1487311200.... | the_stack_v2_python_sparse | improver_tests/utilities/temporal/test_temporal.py | metoppv/improver | train | 101 |
89825e71b6994510bab81350757ae7eae38b5a6c | [
"self.tag = tag\nself.count = 0\nself.sum = 0.0\nself.average = 0.0\nself.min = None\nself.max = None\nself.seen_numbers = False",
"self.count += 1\nif self.tag:\n value = row.get(self.tag)\n try:\n n = float(value)\n self.sum += n\n self.average = self.sum / self.count\n if self... | <|body_start_0|>
self.tag = tag
self.count = 0
self.sum = 0.0
self.average = 0.0
self.min = None
self.max = None
self.seen_numbers = False
<|end_body_0|>
<|body_start_1|>
self.count += 1
if self.tag:
value = row.get(self.tag)
... | Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max | Aggregator | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aggregator:
"""Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max"""
def __init__(self, tag):
"""Constructor @param tag the HXL tag being counted in the row."""
<|body_0|>
def add(self, row):
"""Add a new ... | stack_v2_sparse_classes_36k_train_001663 | 6,532 | permissive | [
{
"docstring": "Constructor @param tag the HXL tag being counted in the row.",
"name": "__init__",
"signature": "def __init__(self, tag)"
},
{
"docstring": "Add a new row of data to the aggregator.",
"name": "add",
"signature": "def add(self, row)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021009 | Implement the Python class `Aggregator` described below.
Class description:
Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max
Method signatures and docstrings:
- def __init__(self, tag): Constructor @param tag the HXL tag being counted in the row.
- def add(s... | Implement the Python class `Aggregator` described below.
Class description:
Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max
Method signatures and docstrings:
- def __init__(self, tag): Constructor @param tag the HXL tag being counted in the row.
- def add(s... | b0209e75789501d99a2fb2df8a30cf55a383065a | <|skeleton|>
class Aggregator:
"""Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max"""
def __init__(self, tag):
"""Constructor @param tag the HXL tag being counted in the row."""
<|body_0|>
def add(self, row):
"""Add a new ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Aggregator:
"""Class to collect aggregates for a single combination. Currently calculates count, sum, average, min, and max"""
def __init__(self, tag):
"""Constructor @param tag the HXL tag being counted in the row."""
self.tag = tag
self.count = 0
self.sum = 0.0
s... | the_stack_v2_python_sparse | hxl/filters/count.py | jayvdb/libhxl-python | train | 0 |
57075916f7e244c45d7b3e3fe373e4ebfa04e094 | [
"w = AddText(None)\nyield w\nw.close()",
"assert isinstance(widget, QtWidgets.QDialog)\nassert isinstance(widget._font, QtGui.QFont)\nassert widget._color == 'black'",
"font_1 = QtGui.QFont('Helvetica', 15)\nmocker.patch.object(QtWidgets.QFontDialog, 'getFont', return_value=(font_1, True))\nwidget.onFontChange(... | <|body_start_0|>
w = AddText(None)
yield w
w.close()
<|end_body_0|>
<|body_start_1|>
assert isinstance(widget, QtWidgets.QDialog)
assert isinstance(widget._font, QtGui.QFont)
assert widget._color == 'black'
<|end_body_1|>
<|body_start_2|>
font_1 = QtGui.QFont('H... | Test the AddText | AddTextTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testOnFontChange(self, widget, mocker):
"""Test the... | stack_v2_sparse_classes_36k_train_001664 | 1,950 | permissive | [
{
"docstring": "Create/Destroy the AddText",
"name": "widget",
"signature": "def widget(self, qapp)"
},
{
"docstring": "Test the GUI in its default state",
"name": "testDefaults",
"signature": "def testDefaults(self, widget)"
},
{
"docstring": "Test the QFontDialog output",
"... | 4 | stack_v2_sparse_classes_30k_train_019499 | Implement the Python class `AddTextTest` described below.
Class description:
Test the AddText
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AddText
- def testDefaults(self, widget): Test the GUI in its default state
- def testOnFontChange(self, widget, mocker): Test the QFontDialog ou... | Implement the Python class `AddTextTest` described below.
Class description:
Test the AddText
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the AddText
- def testDefaults(self, widget): Test the GUI in its default state
- def testOnFontChange(self, widget, mocker): Test the QFontDialog ou... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testOnFontChange(self, widget, mocker):
"""Test the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddTextTest:
"""Test the AddText"""
def widget(self, qapp):
"""Create/Destroy the AddText"""
w = AddText(None)
yield w
w.close()
def testDefaults(self, widget):
"""Test the GUI in its default state"""
assert isinstance(widget, QtWidgets.QDialog)
... | the_stack_v2_python_sparse | src/sas/qtgui/Plotting/UnitTesting/AddTextTest.py | SasView/sasview | train | 48 |
848ab49301bf5b94f5ee9b1b7658b727ec94f65a | [
"self.model = model\nself.data_state = State.from_visible(data, model)\nnpart = self.data_state.batch_size() if num_fantasy_particles is None else num_fantasy_particles\nself.model_state = SequentialMC.generate_fantasy_state(model, npart, fantasy_steps, beta_std=beta_std)\nself.reconstructions = model.compute_recon... | <|body_start_0|>
self.model = model
self.data_state = State.from_visible(data, model)
npart = self.data_state.batch_size() if num_fantasy_particles is None else num_fantasy_particles
self.model_state = SequentialMC.generate_fantasy_state(model, npart, fantasy_steps, beta_std=beta_std)
... | ModelAssessment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelAssessment:
def __init__(self, data, model, fantasy_steps=10, num_fantasy_particles=None, beta_std=0):
"""Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_units)) model (BoltzmannMachine) fantasy_steps (int; optional) num_fantasy_particles (int; optional) beta... | stack_v2_sparse_classes_36k_train_001665 | 4,343 | permissive | [
{
"docstring": "Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_units)) model (BoltzmannMachine) fantasy_steps (int; optional) num_fantasy_particles (int; optional) beta_std (float; optional)",
"name": "__init__",
"signature": "def __init__(self, data, model, fantasy_steps=10, nu... | 5 | stack_v2_sparse_classes_30k_train_017675 | Implement the Python class `ModelAssessment` described below.
Class description:
Implement the ModelAssessment class.
Method signatures and docstrings:
- def __init__(self, data, model, fantasy_steps=10, num_fantasy_particles=None, beta_std=0): Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_u... | Implement the Python class `ModelAssessment` described below.
Class description:
Implement the ModelAssessment class.
Method signatures and docstrings:
- def __init__(self, data, model, fantasy_steps=10, num_fantasy_particles=None, beta_std=0): Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_u... | 5275d56c3caac7ddb1b1baa87060f0b7c3a54aa5 | <|skeleton|>
class ModelAssessment:
def __init__(self, data, model, fantasy_steps=10, num_fantasy_particles=None, beta_std=0):
"""Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_units)) model (BoltzmannMachine) fantasy_steps (int; optional) num_fantasy_particles (int; optional) beta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelAssessment:
def __init__(self, data, model, fantasy_steps=10, num_fantasy_particles=None, beta_std=0):
"""Create a ModelAssessment object. Args: data (tensor ~ (num_samples, num_units)) model (BoltzmannMachine) fantasy_steps (int; optional) num_fantasy_particles (int; optional) beta_std (float; o... | the_stack_v2_python_sparse | paysage/metrics/model_assessment.py | shevisj/paysage | train | 0 | |
27a9995676b055c0fdbef5c2fb8df0007d6e5e67 | [
"super().__init__()\nself.blocks = len(rnns)\nfor index, rnn in enumerate(rnns, 1):\n setattr(self, 'rnn' + str(index), rnn)\nself.output_layer = cnn",
"if len(inputs) > 0:\n inputs = inputs.transpose(0, 1)\ncur_rnn = getattr(self, 'rnn1')\nres = []\nhidden_states = []\ninputs, state_stage = cur_rnn(seq_len... | <|body_start_0|>
super().__init__()
self.blocks = len(rnns)
for index, rnn in enumerate(rnns, 1):
setattr(self, 'rnn' + str(index), rnn)
self.output_layer = cnn
<|end_body_0|>
<|body_start_1|>
if len(inputs) > 0:
inputs = inputs.transpose(0, 1)
cu... | decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
<|body_0|>
def forward(se... | stack_v2_sparse_classes_36k_train_001666 | 41,120 | no_license | [
{
"docstring": "rnns are a list of convlstm cells, and cnn is a convcell",
"name": "__init__",
"signature": "def __init__(self, rnns, cnn)"
},
{
"docstring": "forward pass of the decoder :param seq_len: how long the sequence is decoded to be :param initial_state: a list of tuples [(h, c), ..., (... | 2 | stack_v2_sparse_classes_30k_train_011003 | Implement the Python class `Decoder` described below.
Class description:
decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer.
Method signatures and docstrings:
- def __init__(self, rnns, cnn): rnns are a list of convlstm cells, and cn... | Implement the Python class `Decoder` described below.
Class description:
decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer.
Method signatures and docstrings:
- def __init__(self, rnns, cnn): rnns are a list of convlstm cells, and cn... | b6a3161635bfa3b5da8ec871e1025e01f878e732 | <|skeleton|>
class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
<|body_0|>
def forward(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
super().__init__()
self.blocks = le... | the_stack_v2_python_sparse | src/bayesian_neural_net.py | KEHUIYAO/BCLS | train | 0 |
f23e2f45bb2cad751652bd5bc4fcc3f1d08e49a7 | [
"if user_id is None:\n return None\nSessionId = super().create_session(user_id)\nif SessionId is None:\n return None\nusInstance = UserSession()\nusInstance.user_id = user_id\nusInstance.session_id = SessionId\nusInstance.save()\nreturn SessionId",
"UserSession.load_from_file()\nobj = UserSession.search({'s... | <|body_start_0|>
if user_id is None:
return None
SessionId = super().create_session(user_id)
if SessionId is None:
return None
usInstance = UserSession()
usInstance.user_id = user_id
usInstance.session_id = SessionId
usInstance.save()
... | [summary] Args: SessionExpAuth ([type]): [description] | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""[summary] Args: SessionExpAuth ([type]): [description]"""
def create_session(self, user_id=None):
"""[summary] Args: user_id ([type], optional): [description]. Defaults to None."""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
""... | stack_v2_sparse_classes_36k_train_001667 | 2,155 | no_license | [
{
"docstring": "[summary] Args: user_id ([type], optional): [description]. Defaults to None.",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": "[Request database and return user_id based on the session_id] Args: session_id ([type], optional): [de... | 3 | stack_v2_sparse_classes_30k_train_015006 | Implement the Python class `SessionDBAuth` described below.
Class description:
[summary] Args: SessionExpAuth ([type]): [description]
Method signatures and docstrings:
- def create_session(self, user_id=None): [summary] Args: user_id ([type], optional): [description]. Defaults to None.
- def user_id_for_session_id(se... | Implement the Python class `SessionDBAuth` described below.
Class description:
[summary] Args: SessionExpAuth ([type]): [description]
Method signatures and docstrings:
- def create_session(self, user_id=None): [summary] Args: user_id ([type], optional): [description]. Defaults to None.
- def user_id_for_session_id(se... | 94cae2ce3aa4cd72fc5907bd0148694054a9e60f | <|skeleton|>
class SessionDBAuth:
"""[summary] Args: SessionExpAuth ([type]): [description]"""
def create_session(self, user_id=None):
"""[summary] Args: user_id ([type], optional): [description]. Defaults to None."""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionDBAuth:
"""[summary] Args: SessionExpAuth ([type]): [description]"""
def create_session(self, user_id=None):
"""[summary] Args: user_id ([type], optional): [description]. Defaults to None."""
if user_id is None:
return None
SessionId = super().create_session(use... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | nakadorx/holbertonschool-web_back_end | train | 0 |
d3d5a702792a92c898b25c9781a7e3c7409403f5 | [
"self.x = x\nself.y = y\nself.z = z\nself.u = u\nself.v = v\nself.w = w\nself.spacing = spacing\nself.dimensions = dimensions\nself.origin = origin\nself.resolution = Vec3(len(np.unique(x)), len(np.unique(y)), len(np.unique(z)))",
"n_points = self.dimensions.x1 * self.dimensions.x2 * self.dimensions.x3\nvtk_file ... | <|body_start_0|>
self.x = x
self.y = y
self.z = z
self.u = u
self.v = v
self.w = w
self.spacing = spacing
self.dimensions = dimensions
self.origin = origin
self.resolution = Vec3(len(np.unique(x)), len(np.unique(y)), len(np.unique(z)))
<|en... | Generate a FlowData object to handle data I/O | FlowData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array):... | stack_v2_sparse_classes_36k_train_001668 | 4,601 | permissive | [
{
"docstring": "Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array): Cartesian coordinate data. z (np.array): Cartesian coordinate data. u (np.array): x-component of velocity. v (np.array): y-component of velocity. w (np.array)... | 3 | stack_v2_sparse_classes_30k_train_011948 | Implement the Python class `FlowData` described below.
Class description:
Generate a FlowData object to handle data I/O
Method signatures and docstrings:
- def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None): Initialize FlowData object with coordinates, velocity fields, and meta data. Arg... | Implement the Python class `FlowData` described below.
Class description:
Generate a FlowData object to handle data I/O
Method signatures and docstrings:
- def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None): Initialize FlowData object with coordinates, velocity fields, and meta data. Arg... | 85f2a56fa0ab7c2237d308690a554c6101dbcd34 | <|skeleton|>
class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlowData:
"""Generate a FlowData object to handle data I/O"""
def __init__(self, x, y, z, u, v, w, spacing=None, dimensions=None, origin=None):
"""Initialize FlowData object with coordinates, velocity fields, and meta data. Args: x (np.array): Cartesian coordinate data. y (np.array): Cartesian co... | the_stack_v2_python_sparse | floris/tools/flow_data.py | PStanfel/floris | train | 3 |
21d770fc14f3520e31a3e8c5b646433d839fc98a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads. | AdGroupAdLabelServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupAdLabelServiceServicer:
"""Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads."""
def GetAdGroupAdLabel(self, request, context):
"""Returns the requested ad group ad label in full detail."""
<|body_0|>
def MutateAdGroupAd... | stack_v2_sparse_classes_36k_train_001669 | 3,551 | permissive | [
{
"docstring": "Returns the requested ad group ad label in full detail.",
"name": "GetAdGroupAdLabel",
"signature": "def GetAdGroupAdLabel(self, request, context)"
},
{
"docstring": "Creates and removes ad group ad labels. Operation statuses are returned.",
"name": "MutateAdGroupAdLabels",
... | 2 | null | Implement the Python class `AdGroupAdLabelServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads.
Method signatures and docstrings:
- def GetAdGroupAdLabel(self, request, context): Returns the requested ad group ad label in fu... | Implement the Python class `AdGroupAdLabelServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads.
Method signatures and docstrings:
- def GetAdGroupAdLabel(self, request, context): Returns the requested ad group ad label in fu... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class AdGroupAdLabelServiceServicer:
"""Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads."""
def GetAdGroupAdLabel(self, request, context):
"""Returns the requested ad group ad label in full detail."""
<|body_0|>
def MutateAdGroupAd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdGroupAdLabelServiceServicer:
"""Proto file describing the Ad Group Ad Label service. Service to manage labels on ad group ads."""
def GetAdGroupAdLabel(self, request, context):
"""Returns the requested ad group ad label in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/ad_group_ad_label_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
397d6fe39572fdf140a58a4776ec6bb3abe51fcd | [
"discussion = Discussion.query.get(discussion_id)\nif discussion is None:\n return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')\nif discussion.image_path is None:\n return abort(HTTPStatus.NOT_FOUND, message='Discussion cover image is not found')\nreturn file_storage.download(file_storage.Fi... | <|body_start_0|>
discussion = Discussion.query.get(discussion_id)
if discussion is None:
return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')
if discussion.image_path is None:
return abort(HTTPStatus.NOT_FOUND, message='Discussion cover image is not found... | DiscussionImageResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscussionImageResource:
def get(self, discussion_id):
"""Get discussion cover image"""
<|body_0|>
def put(self, discussion_id):
"""Replace discussion cover image * User can replace the image of **their discussion** * User with permission to **"edit discussions"** ca... | stack_v2_sparse_classes_36k_train_001670 | 2,546 | permissive | [
{
"docstring": "Get discussion cover image",
"name": "get",
"signature": "def get(self, discussion_id)"
},
{
"docstring": "Replace discussion cover image * User can replace the image of **their discussion** * User with permission to **\"edit discussions\"** can replace the image",
"name": "p... | 2 | null | Implement the Python class `DiscussionImageResource` described below.
Class description:
Implement the DiscussionImageResource class.
Method signatures and docstrings:
- def get(self, discussion_id): Get discussion cover image
- def put(self, discussion_id): Replace discussion cover image * User can replace the image... | Implement the Python class `DiscussionImageResource` described below.
Class description:
Implement the DiscussionImageResource class.
Method signatures and docstrings:
- def get(self, discussion_id): Get discussion cover image
- def put(self, discussion_id): Replace discussion cover image * User can replace the image... | dce87ffe395ae4bd08b47f28e07594e1889da819 | <|skeleton|>
class DiscussionImageResource:
def get(self, discussion_id):
"""Get discussion cover image"""
<|body_0|>
def put(self, discussion_id):
"""Replace discussion cover image * User can replace the image of **their discussion** * User with permission to **"edit discussions"** ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscussionImageResource:
def get(self, discussion_id):
"""Get discussion cover image"""
discussion = Discussion.query.get(discussion_id)
if discussion is None:
return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')
if discussion.image_path is None:
... | the_stack_v2_python_sparse | src/backend/app/api/public/discussions/discussion/discussion_image.py | aimanow/sft | train | 0 | |
cbeccddb5d6c8d11f1e7abc36756e6213413386c | [
"self.first_register = False\ndecorator_name = ''.join(('@', Implement.__name__.lower()))\nself.decorator_name = decorator_name\nself.args = args\nself.kwargs = kwargs\nself.scope = CONTEXT.in_pycompss()\nself.core_element = None\nself.core_element_configured = False\nif self.scope:\n check_arguments(MANDATORY_A... | <|body_start_0|>
self.first_register = False
decorator_name = ''.join(('@', Implement.__name__.lower()))
self.decorator_name = decorator_name
self.args = args
self.kwargs = kwargs
self.scope = CONTEXT.in_pycompss()
self.core_element = None
self.core_elemen... | Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation. | Implement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorat... | stack_v2_sparse_classes_36k_train_001671 | 6,895 | permissive | [
{
"docstring": "Store arguments passed to the decorator. self = itself. args = not used. kwargs = dictionary with the given implement parameters. :param args: Arguments. :param kwargs: Keyword arguments.",
"name": "__init__",
"signature": "def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> N... | 3 | stack_v2_sparse_classes_30k_train_013652 | Implement the Python class `Implement` described below.
Class description:
Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: t... | Implement the Python class `Implement` described below.
Class description:
Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: t... | 5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092 | <|skeleton|>
class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. self = it... | the_stack_v2_python_sparse | compss/programming_model/bindings/python/src/pycompss/api/implement.py | bsc-wdc/compss | train | 39 |
888a4acfa32b1adf7a54521f3d6a695973d61eb0 | [
"if contents:\n assert isinstance(contents, MemoryBuffer)\nif filename is not None:\n contents = MemoryBuffer(filename=filename)\nif contents is None:\n raise Exception('No input found.')\nptr = lib.LLVMCreateObjectFile(contents)\nLLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile)\nself.tak... | <|body_start_0|>
if contents:
assert isinstance(contents, MemoryBuffer)
if filename is not None:
contents = MemoryBuffer(filename=filename)
if contents is None:
raise Exception('No input found.')
ptr = lib.LLVMCreateObjectFile(contents)
LLVMObj... | Represents an object/binary file. | ObjectFile | [
"NCSA",
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like st... | stack_v2_sparse_classes_36k_train_001672 | 16,044 | permissive | [
{
"docstring": "Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like str) or a llvm.core.MemoryBuffer instance.",
"name": "__init__",
"signature": "def __init__(self, filename=None... | 3 | stack_v2_sparse_classes_30k_train_016473 | Implement the Python class `ObjectFile` described below.
Class description:
Represents an object/binary file.
Method signatures and docstrings:
- def __init__(self, filename=None, contents=None): Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). co... | Implement the Python class `ObjectFile` described below.
Class description:
Represents an object/binary file.
Method signatures and docstrings:
- def __init__(self, filename=None, contents=None): Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). co... | 700d4b7795d76a37110f8acfb6f05ee4894ab651 | <|skeleton|>
class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like str) or a llvm.... | the_stack_v2_python_sparse | bindings/python/llvm/object.py | etclabscore/evm_llvm | train | 88 |
8b12da51d54c17a8841385b75fb3ec7735a84732 | [
"if '/' in filename:\n return self.generate_http_response(HTTP_STATUS_CODE.BadRequest, exc_cls=exceptions.BadRequest.__name__, exc_msg='subdirectory is not allowed')\ntry:\n cacher_dir = get_rest_cacher_dir()\n \"\\n data = self.get_request().data and json.loads(self.get_request().data)\\n ... | <|body_start_0|>
if '/' in filename:
return self.generate_http_response(HTTP_STATUS_CODE.BadRequest, exc_cls=exceptions.BadRequest.__name__, exc_msg='subdirectory is not allowed')
try:
cacher_dir = get_rest_cacher_dir()
"\n data = self.get_request().data an... | upload/download file | Cacher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cacher:
"""upload/download file"""
def post(self, filename):
"""upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error"""
<|body_0|>
def get(self, filename):
"""donwload file. HTTP Success: 200 OK HTTP Error: 404 Not Found 500 InternalEr... | stack_v2_sparse_classes_36k_train_001673 | 3,793 | permissive | [
{
"docstring": "upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error",
"name": "post",
"signature": "def post(self, filename)"
},
{
"docstring": "donwload file. HTTP Success: 200 OK HTTP Error: 404 Not Found 500 InternalError :returns: dictionary of an request.",
... | 2 | stack_v2_sparse_classes_30k_train_009185 | Implement the Python class `Cacher` described below.
Class description:
upload/download file
Method signatures and docstrings:
- def post(self, filename): upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error
- def get(self, filename): donwload file. HTTP Success: 200 OK HTTP Error: 404 Not... | Implement the Python class `Cacher` described below.
Class description:
upload/download file
Method signatures and docstrings:
- def post(self, filename): upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error
- def get(self, filename): donwload file. HTTP Success: 200 OK HTTP Error: 404 Not... | 193a95ec7ee154a2615fa8dcd99a79df5ddd3bec | <|skeleton|>
class Cacher:
"""upload/download file"""
def post(self, filename):
"""upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error"""
<|body_0|>
def get(self, filename):
"""donwload file. HTTP Success: 200 OK HTTP Error: 404 Not Found 500 InternalEr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cacher:
"""upload/download file"""
def post(self, filename):
"""upload file. HTTP Success: 200 OK HTTP Error: 400 Bad request 500 Internal Error"""
if '/' in filename:
return self.generate_http_response(HTTP_STATUS_CODE.BadRequest, exc_cls=exceptions.BadRequest.__name__, exc_m... | the_stack_v2_python_sparse | main/lib/idds/rest/v1/cacher.py | HSF/iDDS | train | 3 |
77f8713c7443fb029ded2cb01acaebe8d1d8a8fd | [
"super(SmoothL1Loss, self).__init__()\nself.beta = desc['beta'] if 'beta' in desc else 1.0\nself.reduction = desc['reduction'] if 'reduction' in desc else 'mean'\nself.loss_weight = desc['loss_weight'] if 'loss_weight' in desc else 1.0",
"reduction = reduction_override if reduction_override else self.reduction\ni... | <|body_start_0|>
super(SmoothL1Loss, self).__init__()
self.beta = desc['beta'] if 'beta' in desc else 1.0
self.reduction = desc['reduction'] if 'reduction' in desc else 'mean'
self.loss_weight = desc['loss_weight'] if 'loss_weight' in desc else 1.0
<|end_body_0|>
<|body_start_1|>
... | Smooth L1 Loss. | SmoothL1Loss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, desc):
"""Init smooth l1 loss. :param desc: config dict"""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. :param pred: predict... | stack_v2_sparse_classes_36k_train_001674 | 2,297 | permissive | [
{
"docstring": "Init smooth l1 loss. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward compute. :param pred: predict :param target: target :param weight: weight :param avg_factor: avg factor :param reduction_override: reduce overrid... | 2 | stack_v2_sparse_classes_30k_train_001629 | Implement the Python class `SmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, desc): Init smooth l1 loss. :param desc: config dict
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs): Forward compute.... | Implement the Python class `SmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, desc): Init smooth l1 loss. :param desc: config dict
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs): Forward compute.... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class SmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, desc):
"""Init smooth l1 loss. :param desc: config dict"""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. :param pred: predict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, desc):
"""Init smooth l1 loss. :param desc: config dict"""
super(SmoothL1Loss, self).__init__()
self.beta = desc['beta'] if 'beta' in desc else 1.0
self.reduction = desc['reduction'] if 'reduction' in desc else 'mean'
... | the_stack_v2_python_sparse | zeus/networks/pytorch/losses/smooth_l1_loss.py | huawei-noah/xingtian | train | 308 |
655b7198ad851b32d8db7927ca870e87fe162746 | [
"rewards = np.array([d[-1] for d in data])\nreturns = torch.Tensor(compute_discount_reward(rewards, self.agent.gamma))\ntargets = torch.Tensor(np.array([d[1] for d in data])).long()\nstates = torch.cat([d[0] for d in data])\naction_log_probs = torch.cat([d[2].view(-1) for d in data])\nloss = -action_log_probs * ret... | <|body_start_0|>
rewards = np.array([d[-1] for d in data])
returns = torch.Tensor(compute_discount_reward(rewards, self.agent.gamma))
targets = torch.Tensor(np.array([d[1] for d in data])).long()
states = torch.cat([d[0] for d in data])
action_log_probs = torch.cat([d[2].view(-1)... | PersonalTrainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonalTrainer:
def update_agent(self, data):
"""Perform one step of gradient ascent. Use the Returns Gt directly. MC way."""
<|body_0|>
def train_one_episode(self, env):
"""Train on episode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rewards =... | stack_v2_sparse_classes_36k_train_001675 | 1,818 | no_license | [
{
"docstring": "Perform one step of gradient ascent. Use the Returns Gt directly. MC way.",
"name": "update_agent",
"signature": "def update_agent(self, data)"
},
{
"docstring": "Train on episode",
"name": "train_one_episode",
"signature": "def train_one_episode(self, env)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018773 | Implement the Python class `PersonalTrainer` described below.
Class description:
Implement the PersonalTrainer class.
Method signatures and docstrings:
- def update_agent(self, data): Perform one step of gradient ascent. Use the Returns Gt directly. MC way.
- def train_one_episode(self, env): Train on episode | Implement the Python class `PersonalTrainer` described below.
Class description:
Implement the PersonalTrainer class.
Method signatures and docstrings:
- def update_agent(self, data): Perform one step of gradient ascent. Use the Returns Gt directly. MC way.
- def train_one_episode(self, env): Train on episode
<|skel... | e77df6bd35444bff7ba9e39bbcc444cd671a1743 | <|skeleton|>
class PersonalTrainer:
def update_agent(self, data):
"""Perform one step of gradient ascent. Use the Returns Gt directly. MC way."""
<|body_0|>
def train_one_episode(self, env):
"""Train on episode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonalTrainer:
def update_agent(self, data):
"""Perform one step of gradient ascent. Use the Returns Gt directly. MC way."""
rewards = np.array([d[-1] for d in data])
returns = torch.Tensor(compute_discount_reward(rewards, self.agent.gamma))
targets = torch.Tensor(np.array([d... | the_stack_v2_python_sparse | src/reinforce/trainer.py | cthorey/rl_playground | train | 0 | |
d473e119e063b3158b744760923a124152778445 | [
"start, end = time\nconstraint = int(constraint)\noptions = '\\n precision=8;\\n statics=1;\\n baked=1;\\n sdk=0;\\n constraint=%s;\\n animLayers=0;\\n selected=selectedOnly;\\n whichRange=1;\\n range=%s:%s;\\n hierarchy=none;\\n controlPo... | <|body_start_0|>
start, end = time
constraint = int(constraint)
options = '\n precision=8;\n statics=1;\n baked=1;\n sdk=0;\n constraint=%s;\n animLayers=0;\n selected=selectedOnly;\n whichRange=1;\n range=%s:%s;\n hierarchy=n... | Atom | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Atom:
def exportAtom(path, time, constraint=False):
"""@type path: str @type time: list[int] @type constraint: bool"""
<|body_0|>
def importAtom(path, namespace='', search=None, replace=None, targetTime=TargetTime.FromFile):
"""time=1:10; template=character;; selecte... | stack_v2_sparse_classes_36k_train_001676 | 2,693 | permissive | [
{
"docstring": "@type path: str @type time: list[int] @type constraint: bool",
"name": "exportAtom",
"signature": "def exportAtom(path, time, constraint=False)"
},
{
"docstring": "time=1:10; template=character;; selected=template; @type path: str @type search: str @type replace: str @type namesp... | 2 | stack_v2_sparse_classes_30k_train_004451 | Implement the Python class `Atom` described below.
Class description:
Implement the Atom class.
Method signatures and docstrings:
- def exportAtom(path, time, constraint=False): @type path: str @type time: list[int] @type constraint: bool
- def importAtom(path, namespace='', search=None, replace=None, targetTime=Targ... | Implement the Python class `Atom` described below.
Class description:
Implement the Atom class.
Method signatures and docstrings:
- def exportAtom(path, time, constraint=False): @type path: str @type time: list[int] @type constraint: bool
- def importAtom(path, namespace='', search=None, replace=None, targetTime=Targ... | 0950bd108f803d643324cbfc322f83b358faba03 | <|skeleton|>
class Atom:
def exportAtom(path, time, constraint=False):
"""@type path: str @type time: list[int] @type constraint: bool"""
<|body_0|>
def importAtom(path, namespace='', search=None, replace=None, targetTime=TargetTime.FromFile):
"""time=1:10; template=character;; selecte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Atom:
def exportAtom(path, time, constraint=False):
"""@type path: str @type time: list[int] @type constraint: bool"""
start, end = time
constraint = int(constraint)
options = '\n precision=8;\n statics=1;\n baked=1;\n sdk=0;\n constraint=%s;\... | the_stack_v2_python_sparse | packages/mutils/atom.py | qeeji/studiolibrary | train | 0 | |
23509248321e8b3b939dba7d92e4b3f406c684ac | [
"sqlalchemy_uri = self.get_uri()\nsqlite_uri = sqlalchemy_uri.replace('sqlite:///', 'file:')\nconn = sqlite3.connect(sqlite_uri, uri=True)\nreturn conn",
"conn_id = getattr(self, self.conn_name_attr)\nairflow_conn = self.get_connection(conn_id)\nif airflow_conn.conn_type is None:\n airflow_conn.conn_type = sel... | <|body_start_0|>
sqlalchemy_uri = self.get_uri()
sqlite_uri = sqlalchemy_uri.replace('sqlite:///', 'file:')
conn = sqlite3.connect(sqlite_uri, uri=True)
return conn
<|end_body_0|>
<|body_start_1|>
conn_id = getattr(self, self.conn_name_attr)
airflow_conn = self.get_conne... | Interact with SQLite. | SqliteHook | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqliteHook:
"""Interact with SQLite."""
def get_conn(self) -> sqlite3.dbapi2.Connection:
"""Returns a sqlite connection object."""
<|body_0|>
def get_uri(self) -> str:
"""Override DbApiHook get_uri method for get_sqlalchemy_engine()."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_001677 | 2,402 | permissive | [
{
"docstring": "Returns a sqlite connection object.",
"name": "get_conn",
"signature": "def get_conn(self) -> sqlite3.dbapi2.Connection"
},
{
"docstring": "Override DbApiHook get_uri method for get_sqlalchemy_engine().",
"name": "get_uri",
"signature": "def get_uri(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_019973 | Implement the Python class `SqliteHook` described below.
Class description:
Interact with SQLite.
Method signatures and docstrings:
- def get_conn(self) -> sqlite3.dbapi2.Connection: Returns a sqlite connection object.
- def get_uri(self) -> str: Override DbApiHook get_uri method for get_sqlalchemy_engine(). | Implement the Python class `SqliteHook` described below.
Class description:
Interact with SQLite.
Method signatures and docstrings:
- def get_conn(self) -> sqlite3.dbapi2.Connection: Returns a sqlite connection object.
- def get_uri(self) -> str: Override DbApiHook get_uri method for get_sqlalchemy_engine().
<|skele... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class SqliteHook:
"""Interact with SQLite."""
def get_conn(self) -> sqlite3.dbapi2.Connection:
"""Returns a sqlite connection object."""
<|body_0|>
def get_uri(self) -> str:
"""Override DbApiHook get_uri method for get_sqlalchemy_engine()."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqliteHook:
"""Interact with SQLite."""
def get_conn(self) -> sqlite3.dbapi2.Connection:
"""Returns a sqlite connection object."""
sqlalchemy_uri = self.get_uri()
sqlite_uri = sqlalchemy_uri.replace('sqlite:///', 'file:')
conn = sqlite3.connect(sqlite_uri, uri=True)
... | the_stack_v2_python_sparse | airflow/providers/sqlite/hooks/sqlite.py | apache/airflow | train | 22,756 |
138f492e01bd023a546bc95d483ef91dce6024ef | [
"self.input_dict = input_dict\nself.output_dict = output_dict\nself.project_name = project_name",
"if calculate_costs_input_dict['num_turbines'] > 10:\n calculate_costs_output_dict['substation_cost_usd'] = 11652 * (calculate_costs_input_dict['interconnect_voltage_kV'] + calculate_costs_input_dict['project_size... | <|body_start_0|>
self.input_dict = input_dict
self.output_dict = output_dict
self.project_name = project_name
<|end_body_0|>
<|body_start_1|>
if calculate_costs_input_dict['num_turbines'] > 10:
calculate_costs_output_dict['substation_cost_usd'] = 11652 * (calculate_costs_inp... | **SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical data)* Get project size (project_size_meg... | SubstationCost | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubstationCost:
"""**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical... | stack_v2_sparse_classes_36k_train_001678 | 5,371 | permissive | [
{
"docstring": "Parameters ---------- input_dict : dict The input dictionary with key value pairs described in the class documentation output_dict : dict The output dictionary with key value pairs as found on the output documentation.",
"name": "__init__",
"signature": "def __init__(self, input_dict, ou... | 4 | stack_v2_sparse_classes_30k_train_003529 | Implement the Python class `SubstationCost` described below.
Class description:
**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is cu... | Implement the Python class `SubstationCost` described below.
Class description:
**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is cu... | d7270ebe1c554293a9d36730d67ab555c071cb17 | <|skeleton|>
class SubstationCost:
"""**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubstationCost:
"""**SubstationCost.py** - Created by Annika Eberle and Owen Roberts on Dec. 17, 2018 - Refactored by Parangat Bhaskar and Alicia Key on June 3, 2019 Calculates the costs associated with substations for land-based wind projects *(module is currently based on curve fit of empirical data)* Get p... | the_stack_v2_python_sparse | wisdem/landbosse/model/SubstationCost.py | WISDEM/WISDEM | train | 120 |
80d7f9712f8333feb5f4bb0ac397efbd21ec5d7f | [
"result = []\n\ndef dfs(node):\n if not node:\n return\n result.append(str(node.val))\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\ndfs(root)\nreturn ' '.join(result)",
"if not data:\n return\ndata = map(int, data.split()[::-1])\n\ndef dfs(left, right):\n... | <|body_start_0|>
result = []
def dfs(node):
if not node:
return
result.append(str(node.val))
if node.left:
dfs(node.left)
if node.right:
dfs(node.right)
dfs(root)
return ' '.join(result)
<|en... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str, preordered. :rtyp... | stack_v2_sparse_classes_36k_train_001679 | 3,220 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str, preordered. :rtype: TreeNode 5... | 2 | stack_v2_sparse_classes_30k_train_016551 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'
- def deserialize(self, data): Decodes you... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'
- def deserialize(self, data): Decodes you... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str, preordered. :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str 請用297解決 謝謝. 或者, preorder serialize without '#'"""
result = []
def dfs(node):
if not node:
return
result.append(str(node.val))
if... | the_stack_v2_python_sparse | co_ms/449_Serialize_and_Deserialize_BST.py | vsdrun/lc_public | train | 6 | |
466171e0da9874e9635228007ce5ab28b604010e | [
"pipe_type = 'Train' if is_training else 'Eval'\nResnetPipe.instance_count += 1\npipe_name = '{}:{}'.format(self.__class__.__name__ + pipe_type, ResnetPipe.instance_count)\npipe_name = str(pipe_name)\nsuper(ResnetPipe, self).__init__(device=device, prefetch_depth=queue_depth, batch_size=batch_size, pipe_name=pipe_n... | <|body_start_0|>
pipe_type = 'Train' if is_training else 'Eval'
ResnetPipe.instance_count += 1
pipe_name = '{}:{}'.format(self.__class__.__name__ + pipe_type, ResnetPipe.instance_count)
pipe_name = str(pipe_name)
super(ResnetPipe, self).__init__(device=device, prefetch_depth=queu... | Class defining resnet media pipe. | ResnetPipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResnetPipe:
"""Class defining resnet media pipe."""
def __init__(self, device, queue_depth, batch_size, channel, height, width, is_training, data_dir, out_dtype, num_slices, slice_index, random_crop_type):
""":params device: device name. <hpu> :params queue_depth: Number of preloaded... | stack_v2_sparse_classes_36k_train_001680 | 7,328 | no_license | [
{
"docstring": ":params device: device name. <hpu> :params queue_depth: Number of preloaded image batches for every slice in mediapipe. <1/2/3> :params channel: mediapipe image output channel size. :params height: mediapipe image output height. :params width: mediapipe image output width. :params is_training: b... | 2 | null | Implement the Python class `ResnetPipe` described below.
Class description:
Class defining resnet media pipe.
Method signatures and docstrings:
- def __init__(self, device, queue_depth, batch_size, channel, height, width, is_training, data_dir, out_dtype, num_slices, slice_index, random_crop_type): :params device: de... | Implement the Python class `ResnetPipe` described below.
Class description:
Class defining resnet media pipe.
Method signatures and docstrings:
- def __init__(self, device, queue_depth, batch_size, channel, height, width, is_training, data_dir, out_dtype, num_slices, slice_index, random_crop_type): :params device: de... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class ResnetPipe:
"""Class defining resnet media pipe."""
def __init__(self, device, queue_depth, batch_size, channel, height, width, is_training, data_dir, out_dtype, num_slices, slice_index, random_crop_type):
""":params device: device name. <hpu> :params queue_depth: Number of preloaded... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResnetPipe:
"""Class defining resnet media pipe."""
def __init__(self, device, queue_depth, batch_size, channel, height, width, is_training, data_dir, out_dtype, num_slices, slice_index, random_crop_type):
""":params device: device name. <hpu> :params queue_depth: Number of preloaded image batche... | the_stack_v2_python_sparse | TensorFlow/computer_vision/common/resnet_media_pipe.py | HabanaAI/Model-References | train | 108 |
c80c2dfc3e119295d926f0e2d0a83c5951eaaa08 | [
"self.taxable_states = {'WI': 0.055}\nself.subtotal = float(input('What is the order amount? '))\nself.state = str(input('What is the state? '))",
"tax_rate = 0\nif self.state.upper() in self.taxable_states.keys():\n tax_rate += self.taxable_states[self.state.upper()]\ntax = self.subtotal * tax_rate\norder = {... | <|body_start_0|>
self.taxable_states = {'WI': 0.055}
self.subtotal = float(input('What is the order amount? '))
self.state = str(input('What is the state? '))
<|end_body_0|>
<|body_start_1|>
tax_rate = 0
if self.state.upper() in self.taxable_states.keys():
tax_rate +... | Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only one state is entered state: (str) State in which the customer resides sub... | Taxes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Taxes:
"""Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only one state is entered state: (str) State ... | stack_v2_sparse_classes_36k_train_001681 | 1,787 | no_license | [
{
"docstring": "Initializes the class -- prompts user for input",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculates the total charges for the customer Args: n/a -- uses class attributes Returns: order: (Dict) { tax: (Float) total taxes due total: (Float) order s... | 2 | stack_v2_sparse_classes_30k_train_007635 | Implement the Python class `Taxes` described below.
Class description:
Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only o... | Implement the Python class `Taxes` described below.
Class description:
Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only o... | 218894fbad8ac3389003ce7321fd4c4020239fd6 | <|skeleton|>
class Taxes:
"""Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only one state is entered state: (str) State ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Taxes:
"""Represents a simple point of sale system that calculates sales tax based on the shopper's state of residence Attributes: taxable_states: (dict) States and their associated tax rate (i.e., {ST1: tax_rate1, ST2: tax_rate2}). For this exercise, only one state is entered state: (str) State in which the ... | the_stack_v2_python_sparse | challenges/c14_TaxCalculator/tax_calculator/tax_calculator.py | andrew-rietz/FiftySeven_Coding_Challenges | train | 0 |
b95b7494671c6bef9c9541cf8c9e691a02b2d87c | [
"self.params = {}\nself.reg = reg\nself.dtype = dtype\nC, H, W = input_dim\nself.params['W1'] = np.random.normal(0, weight_scale, (num_filters, C, filter_size, filter_size))\nself.params['b1'] = np.zeros(num_filters)\nself.params['W2'] = np.random.normal(0, weight_scale, (num_filters * H / 2 * W / 2, hidden_dim))\n... | <|body_start_0|>
self.params = {}
self.reg = reg
self.dtype = dtype
C, H, W = input_dim
self.params['W1'] = np.random.normal(0, weight_scale, (num_filters, C, filter_size, filter_size))
self.params['b1'] = np.zeros(num_filters)
self.params['W2'] = np.random.normal... | A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels. | CustomLayerConvNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C inpu... | stack_v2_sparse_classes_36k_train_001682 | 8,901 | no_license | [
{
"docstring": "Initialize a new network. Inputs: - input_dim: Tuple (C, H, W) giving size of input data - num_filters: Number of filters to use in the convolutional layer - filter_size: Size of filters to use in the convolutional layer - hidden_dim: Number of units to use in the fully-connected hidden layer - ... | 2 | stack_v2_sparse_classes_30k_train_012788 | Implement the Python class `CustomLayerConvNet` described below.
Class description:
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each wi... | Implement the Python class `CustomLayerConvNet` described below.
Class description:
A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each wi... | c885a43d6181ff62c595f3d41823f112219e61db | <|skeleton|>
class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomLayerConvNet:
"""A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels.""... | the_stack_v2_python_sparse | assignment2/cs231n/classifiers/NormalConvNet.py | EllieLily/cs213n | train | 0 |
1bd510f2f92265655ea8d3f2a323ce1df1f7e8c3 | [
"while longUrl not in self.encoded:\n if self.counting > 999:\n self.counting = 0\n self.digits += 1\n else:\n self.counting += 1\n timestamp = time.asctime(time.localtime(time.time()))\n shortKey = sha1(longUrl + timestamp).hexdigest()[:self.digits]\n if shortKey not in self.dec... | <|body_start_0|>
while longUrl not in self.encoded:
if self.counting > 999:
self.counting = 0
self.digits += 1
else:
self.counting += 1
timestamp = time.asctime(time.localtime(time.time()))
shortKey = sha1(longUrl + ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_001683 | 1,231 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_train_011489 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | 74d67d672597aa80a7ac06ece630a6e11a37cbc0 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
while longUrl not in self.encoded:
if self.counting > 999:
self.counting = 0
self.digits += 1
else:
self.counting += ... | the_stack_v2_python_sparse | 535_Encode_and_Decode_TinyURL/535.py | spfantasy/LeetCode | train | 0 | |
1fc3fbe94f5c1fd10a7585e941704bfde7c9b5e1 | [
"self.left = None\nself.right = None\nself.data = data",
"if self.left:\n self.left.print_tree()\nprint(self.data, sep=' => ')\nif self.right:\n self.right.print_tree()",
"if not self.data:\n self.data = data\nelif data < self.data:\n if not self.left:\n self.left = Node(data)\n else:\n ... | <|body_start_0|>
self.left = None
self.right = None
self.data = data
<|end_body_0|>
<|body_start_1|>
if self.left:
self.left.print_tree()
print(self.data, sep=' => ')
if self.right:
self.right.print_tree()
<|end_body_1|>
<|body_start_2|>
... | Node class. | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Node class."""
def __init__(self, data):
"""Init method."""
<|body_0|>
def print_tree(self):
"""Method to print."""
<|body_1|>
def insert(self, data):
"""Method to insert."""
<|body_2|>
def search(self, value):
"... | stack_v2_sparse_classes_36k_train_001684 | 1,550 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Method to print.",
"name": "print_tree",
"signature": "def print_tree(self)"
},
{
"docstring": "Method to insert.",
"name": "insert",
"signature": "def insert(sel... | 4 | stack_v2_sparse_classes_30k_train_013591 | Implement the Python class `Node` described below.
Class description:
Node class.
Method signatures and docstrings:
- def __init__(self, data): Init method.
- def print_tree(self): Method to print.
- def insert(self, data): Method to insert.
- def search(self, value): Method to search. | Implement the Python class `Node` described below.
Class description:
Node class.
Method signatures and docstrings:
- def __init__(self, data): Init method.
- def print_tree(self): Method to print.
- def insert(self, data): Method to insert.
- def search(self, value): Method to search.
<|skeleton|>
class Node:
"... | fd6ea6012f3b3fead6ce5c4452f838ed5c0a1706 | <|skeleton|>
class Node:
"""Node class."""
def __init__(self, data):
"""Init method."""
<|body_0|>
def print_tree(self):
"""Method to print."""
<|body_1|>
def insert(self, data):
"""Method to insert."""
<|body_2|>
def search(self, value):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
"""Node class."""
def __init__(self, data):
"""Init method."""
self.left = None
self.right = None
self.data = data
def print_tree(self):
"""Method to print."""
if self.left:
self.left.print_tree()
print(self.data, sep=' => ')
... | the_stack_v2_python_sparse | python/sample_programs/binary_tree.py | icgowtham/Miscellany | train | 0 |
37781832e950f7d78955f2a4db41b365f957cbdf | [
"self.model_func = model_func\nself.cmd_args = cmd_args\nself.settings = settings\nself.input_specs = input_specs\nself.write_path = write_path",
"val_arry = np.sort(np.array(list(data.keys())))\nnp.random.shuffle(val_arry)\nslice_idx = np.tile(np.arange(0, k), ceil(len(val_arry) / k))[:len(val_arry)]\nself.folds... | <|body_start_0|>
self.model_func = model_func
self.cmd_args = cmd_args
self.settings = settings
self.input_specs = input_specs
self.write_path = write_path
<|end_body_0|>
<|body_start_1|>
val_arry = np.sort(np.array(list(data.keys())))
np.random.shuffle(val_arry)... | CrossValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidation:
def __init__(self, model_func, cmd_args, settings, input_specs, write_path):
"""INPUTS: model_func: the model function to return the current model cmd_args: the command line arguements settings: the ai settings file input_specs: the input specifications from data process... | stack_v2_sparse_classes_36k_train_001685 | 5,002 | no_license | [
{
"docstring": "INPUTS: model_func: the model function to return the current model cmd_args: the command line arguements settings: the ai settings file input_specs: the input specifications from data processing write_path: the path to write out to EFFECT: initializes the cross validation to run KxK cross fold v... | 4 | stack_v2_sparse_classes_30k_train_006024 | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, model_func, cmd_args, settings, input_specs, write_path): INPUTS: model_func: the model function to return the current model cmd_args: the comman... | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, model_func, cmd_args, settings, input_specs, write_path): INPUTS: model_func: the model function to return the current model cmd_args: the comman... | a2f567650776dde8aa71c77d9bde6dc95fe4d418 | <|skeleton|>
class CrossValidation:
def __init__(self, model_func, cmd_args, settings, input_specs, write_path):
"""INPUTS: model_func: the model function to return the current model cmd_args: the command line arguements settings: the ai settings file input_specs: the input specifications from data process... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossValidation:
def __init__(self, model_func, cmd_args, settings, input_specs, write_path):
"""INPUTS: model_func: the model function to return the current model cmd_args: the command line arguements settings: the ai settings file input_specs: the input specifications from data processing write_path... | the_stack_v2_python_sparse | src/cross_validation.py | wwlaoxi/mri_liver_seg | train | 1 | |
b260fd0914c47421324427279edede9e0229b242 | [
"if not preorder:\n return None\n\ndef build(i, lb, ub):\n if i >= len(preorder) or preorder[i] >= ub or preorder[i] <= lb:\n return (i, None)\n root = TreeNode(preorder[i])\n i, root.left = build(i + 1, lb, root.val)\n i, root.right = build(i, root.val, ub)\n return (i, root)\nreturn build... | <|body_start_0|>
if not preorder:
return None
def build(i, lb, ub):
if i >= len(preorder) or preorder[i] >= ub or preorder[i] <= lb:
return (i, None)
root = TreeNode(preorder[i])
i, root.left = build(i + 1, lb, root.val)
i, roo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
"""Recursion"""
<|body_0|>
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
"""Stack"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not preorder... | stack_v2_sparse_classes_36k_train_001686 | 2,878 | no_license | [
{
"docstring": "Recursion",
"name": "bstFromPreorder",
"signature": "def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]"
},
{
"docstring": "Stack",
"name": "bstFromPreorder",
"signature": "def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]"
}
] | 2 | stack_v2_sparse_classes_30k_train_004383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: Recursion
- def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: Stack | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: Recursion
- def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: Stack
<|skeleton|>
class ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
"""Recursion"""
<|body_0|>
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
"""Stack"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
"""Recursion"""
if not preorder:
return None
def build(i, lb, ub):
if i >= len(preorder) or preorder[i] >= ub or preorder[i] <= lb:
return (i, None)
root... | the_stack_v2_python_sparse | leetcode/solved/1050_Construct_Binary_Search_Tree_from_Preorder_Traversal/solution.py | sungminoh/algorithms | train | 0 | |
0177ad3e08a14972089afe69fa1e072c297f290f | [
"self.num_in = num_in\nself.num_out = num_out\nself.weight = tf.Variable(tf.random_normal([num_in, num_out]))\nself.bias = tf.Variable(tf.random_normal([num_out]))",
"out_without_bias = tf.matmul(input_x, self.weight)\noutput = tf.nn.bias_add(out_without_bias, self.bias)\nreturn output"
] | <|body_start_0|>
self.num_in = num_in
self.num_out = num_out
self.weight = tf.Variable(tf.random_normal([num_in, num_out]))
self.bias = tf.Variable(tf.random_normal([num_out]))
<|end_body_0|>
<|body_start_1|>
out_without_bias = tf.matmul(input_x, self.weight)
output = tf... | a layer class: a fc layer implementation in tensorflow | FCLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCLayer:
"""a layer class: a fc layer implementation in tensorflow"""
def __init__(self, num_in, num_out):
"""init function"""
<|body_0|>
def ops(self, input_x):
"""operation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.num_in = num_in
... | stack_v2_sparse_classes_36k_train_001687 | 6,225 | no_license | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self, num_in, num_out)"
},
{
"docstring": "operation",
"name": "ops",
"signature": "def ops(self, input_x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020203 | Implement the Python class `FCLayer` described below.
Class description:
a layer class: a fc layer implementation in tensorflow
Method signatures and docstrings:
- def __init__(self, num_in, num_out): init function
- def ops(self, input_x): operation | Implement the Python class `FCLayer` described below.
Class description:
a layer class: a fc layer implementation in tensorflow
Method signatures and docstrings:
- def __init__(self, num_in, num_out): init function
- def ops(self, input_x): operation
<|skeleton|>
class FCLayer:
"""a layer class: a fc layer imple... | cf8eea1b8ed412f97a581214c4ee876ac22d1ae6 | <|skeleton|>
class FCLayer:
"""a layer class: a fc layer implementation in tensorflow"""
def __init__(self, num_in, num_out):
"""init function"""
<|body_0|>
def ops(self, input_x):
"""operation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FCLayer:
"""a layer class: a fc layer implementation in tensorflow"""
def __init__(self, num_in, num_out):
"""init function"""
self.num_in = num_in
self.num_out = num_out
self.weight = tf.Variable(tf.random_normal([num_in, num_out]))
self.bias = tf.Variable(tf.rand... | the_stack_v2_python_sparse | nets/utils_net.py | baifengbai/QASystem | train | 0 |
87a7e039e27f4b1b3d22c985e9a3f9461d2728ec | [
"user = self\nuser_employee = self.env['hr.employee'].search_read([('user_id', '=', user.id)], fields=['id'])\nresult = []\nif user_employee:\n employee_ref = user_employee[0]['id']\n result.append(str(employee_ref))\n my_subordinates = self.env['hr.employee'].search_read(['|', ('coach_id', '=', employee_r... | <|body_start_0|>
user = self
user_employee = self.env['hr.employee'].search_read([('user_id', '=', user.id)], fields=['id'])
result = []
if user_employee:
employee_ref = user_employee[0]['id']
result.append(str(employee_ref))
my_subordinates = self.env... | ResUsers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUsers:
def get_my_subordinate_employees(self):
"""Return employee's subordinates - list of employees for which user is a Manager Or Coach"""
<|body_0|>
def get_my_subordinate_employees_list(self):
"""Return employee's subordinates - list of employees for which use... | stack_v2_sparse_classes_36k_train_001688 | 1,903 | no_license | [
{
"docstring": "Return employee's subordinates - list of employees for which user is a Manager Or Coach",
"name": "get_my_subordinate_employees",
"signature": "def get_my_subordinate_employees(self)"
},
{
"docstring": "Return employee's subordinates - list of employees for which user is a Manage... | 2 | stack_v2_sparse_classes_30k_train_007872 | Implement the Python class `ResUsers` described below.
Class description:
Implement the ResUsers class.
Method signatures and docstrings:
- def get_my_subordinate_employees(self): Return employee's subordinates - list of employees for which user is a Manager Or Coach
- def get_my_subordinate_employees_list(self): Ret... | Implement the Python class `ResUsers` described below.
Class description:
Implement the ResUsers class.
Method signatures and docstrings:
- def get_my_subordinate_employees(self): Return employee's subordinates - list of employees for which user is a Manager Or Coach
- def get_my_subordinate_employees_list(self): Ret... | 4fe19ca76523cf274a3a85c8bcad653100ff556f | <|skeleton|>
class ResUsers:
def get_my_subordinate_employees(self):
"""Return employee's subordinates - list of employees for which user is a Manager Or Coach"""
<|body_0|>
def get_my_subordinate_employees_list(self):
"""Return employee's subordinates - list of employees for which use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResUsers:
def get_my_subordinate_employees(self):
"""Return employee's subordinates - list of employees for which user is a Manager Or Coach"""
user = self
user_employee = self.env['hr.employee'].search_read([('user_id', '=', user.id)], fields=['id'])
result = []
if use... | the_stack_v2_python_sparse | odoo app/ksa_hr_vacation/models/res_users.py | ahmed-amine-ellouze/personal | train | 0 | |
b98ab0a1c89c4b644a3692a6edf449cf65cabe48 | [
"self.logger = create_logger('methods.inprocessing.NeuralNetwork')\nself.optimizer_class = optimizer\nself.loss_class = loss\nkwargs['activation_type'] = import_object(activation)\nself.learning_rate = learning_rate\nself.weight_decay = weight_decay\nself.epochs = epochs\nself.batch_size = batch_size\nself.logger.d... | <|body_start_0|>
self.logger = create_logger('methods.inprocessing.NeuralNetwork')
self.optimizer_class = optimizer
self.loss_class = loss
kwargs['activation_type'] = import_object(activation)
self.learning_rate = learning_rate
self.weight_decay = weight_decay
sel... | NeuralNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.... | stack_v2_sparse_classes_36k_train_001689 | 7,243 | permissive | [
{
"docstring": "Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.optim package. loss_class : str The loss function to use. Must be a class from the torch.nn package. activation_class : str The activation function to use. Must be a class f... | 3 | stack_v2_sparse_classes_30k_train_010044 | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs): Creates a neural netw... | Implement the Python class `NeuralNetwork` described below.
Class description:
Implement the NeuralNetwork class.
Method signatures and docstrings:
- def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs): Creates a neural netw... | a0012dfcaef0b5d33452451dca955a99f7e7cccf | <|skeleton|>
class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuralNetwork:
def __init__(self, optimizer: str, loss: str, activation: str, learning_rate: float, weight_decay: float, epochs: int, batch_size: int, **kwargs):
"""Creates a neural network model. Parameters ---------- optimizer : str The optimizer to use. Must be a class from the torch.optim package.... | the_stack_v2_python_sparse | src/aequitas/fairflow/methods/inprocessing/neural_network.py | dssg/aequitas | train | 575 | |
4d64efd5fa91033e73c51016e341b86b65d69617 | [
"urlconf = getattr(request, 'urlconf', None)\nif not _is_valid_path(request.path_info, urlconf):\n if request.path_info.endswith('/'):\n new_path = request.path_info[:-1]\n else:\n new_path = request.path_info + '/'\n if _is_valid_path(new_path, urlconf):\n return http.HttpResponsePerm... | <|body_start_0|>
urlconf = getattr(request, 'urlconf', None)
if not _is_valid_path(request.path_info, urlconf):
if request.path_info.endswith('/'):
new_path = request.path_info[:-1]
else:
new_path = request.path_info + '/'
if _is_valid_... | Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised within a view for a non-slashed url, and APPEND_SLASH is True, and the slash-appended url resolves, ... | AppendOrRemoveSlashMiddleware | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppendOrRemoveSlashMiddleware:
"""Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised within a view for a non-slashed url, and AP... | stack_v2_sparse_classes_36k_train_001690 | 3,111 | permissive | [
{
"docstring": "Returns a redirect if adding/removing a slash is appropriate. This works in the same way as the default APPEND_SLASH behaviour but in either direction.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "If a 404 is raised within a vi... | 2 | null | Implement the Python class `AppendOrRemoveSlashMiddleware` described below.
Class description:
Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised with... | Implement the Python class `AppendOrRemoveSlashMiddleware` described below.
Class description:
Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised with... | 408f3fa3d36542d8fc1236ba1cac804de6f14b0c | <|skeleton|>
class AppendOrRemoveSlashMiddleware:
"""Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised within a view for a non-slashed url, and AP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppendOrRemoveSlashMiddleware:
"""Like django's built in APPEND_SLASH functionality, but also works in reverse. Eg. will remove the slash if a slash-appended url won't resolve, but its non-slashed counterpart will. Additionally, if a 404 error is raised within a view for a non-slashed url, and APPEND_SLASH is... | the_stack_v2_python_sparse | hard-gists/1440567/snippet.py | dockerizeme/dockerizeme | train | 24 |
85f47f0d3e6a9c0418d427d00de354e8fc2f4223 | [
"self.wind_speed = np.ones((3, 4), dtype=np.float32)\nself.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)\nself.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)\nself.plugin = OrographicEnhancement()\nself.plugin.grid_spacing_km = 3.0",
"distance = self.plugin._get_point_distances(self.wind_... | <|body_start_0|>
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)
self.plugin = OrographicEnhancement()
self.plugin.grid_spacing_km = 3.0
<|end_body_... | Test the _locate_source_points method | Test__locate_source_points | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_36k_train_001691 | 34,979 | permissive | [
{
"docstring": "Define input matrices and plugin",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test location of source points",
"name": "test_basic",
"signature": "def test_basic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018490 | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points
<|skeleton|>
class Test__locate_source_points:... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4)... | the_stack_v2_python_sparse | improver_tests/orographic_enhancement/test_OrographicEnhancement.py | metoppv/improver | train | 101 |
286d748e23d5e038635e94147652c49421c6195f | [
"m = max(persons) + 1\nself.v = [0] * m\nself.t = []\nself.s = min(persons)\nmax_c = 0\nmax_t = min(persons)\nfor i in range(len(persons)):\n self.v[persons[i]] += 1\n if self.v[persons[i]] >= max_c:\n max_t = persons[i]\n max_c = self.v[persons[i]]\n self.t.append(max_t)\nself.n = len(times)... | <|body_start_0|>
m = max(persons) + 1
self.v = [0] * m
self.t = []
self.s = min(persons)
max_c = 0
max_t = min(persons)
for i in range(len(persons)):
self.v[persons[i]] += 1
if self.v[persons[i]] >= max_c:
max_t = persons[i]... | TopVotedCandidate | [] | 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|>
m = max(persons) + 1
self.v =... | stack_v2_sparse_classes_36k_train_001692 | 1,161 | no_license | [
{
"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 | stack_v2_sparse_classes_30k_train_003436 | 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... | 72d172ea25777980a49439042dbc39448fcad73d | <|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]"""
m = max(persons) + 1
self.v = [0] * m
self.t = []
self.s = min(persons)
max_c = 0
max_t = min(persons)
for i in range(len(persons)):
... | the_stack_v2_python_sparse | src/leetcode/P911.py | stupidchen/leetcode | train | 7 | |
5b48b2d3caf802d9b3553a22deea0e09c662fba8 | [
"profile_pk = request.session.get('updated')\nif not profile_pk or (request.user.is_authenticated and request.user.profile.pk != profile_pk):\n request.session['get_params'] = request.GET.dict()\n if request.user.is_authenticated:\n redirect_url = reverse('users:update')\n self.messages.info('Bi... | <|body_start_0|>
profile_pk = request.session.get('updated')
if not profile_pk or (request.user.is_authenticated and request.user.profile.pk != profile_pk):
request.session['get_params'] = request.GET.dict()
if request.user.is_authenticated:
redirect_url = reverse... | Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user. | UpdateOrCreateRequiredMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateOrCreateRequiredMixin:
"""Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user."""
def get(self, request, *args, **kwargs):
"""Return update if session doesn't contain current user, ma... | stack_v2_sparse_classes_36k_train_001693 | 4,884 | permissive | [
{
"docstring": "Return update if session doesn't contain current user, marked as updated.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Returns updated user profile and removes session variable.",
"name": "get_profile",
"signature": "def get_p... | 2 | null | Implement the Python class `UpdateOrCreateRequiredMixin` described below.
Class description:
Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): ... | Implement the Python class `UpdateOrCreateRequiredMixin` described below.
Class description:
Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): ... | 47c13f3429b95b9ad5ca59b45cf971895260bb5c | <|skeleton|>
class UpdateOrCreateRequiredMixin:
"""Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user."""
def get(self, request, *args, **kwargs):
"""Return update if session doesn't contain current user, ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateOrCreateRequiredMixin:
"""Saves (and restores) GET parameters to session and returns view to create or update profile before continuing. Resets after first retrieve of user."""
def get(self, request, *args, **kwargs):
"""Return update if session doesn't contain current user, marked as updat... | the_stack_v2_python_sparse | scholariumat/users/views.py | valuehack/scholariumat | train | 0 |
82b29622c4e494668afec113fb2f5b208bf81e5e | [
"nums_set = set(nums)\nfor i in nums_set:\n if nums.count(i) > len(nums) // 2:\n return i",
"candidate, count = (nums[0], 1)\nfor i in range(1, len(nums)):\n if count == 0:\n candidate = nums[i]\n if nums[i] == candidate:\n count += 1\n else:\n count -= 1\nreturn candidate"... | <|body_start_0|>
nums_set = set(nums)
for i in nums_set:
if nums.count(i) > len(nums) // 2:
return i
<|end_body_0|>
<|body_start_1|>
candidate, count = (nums[0], 1)
for i in range(1, len(nums)):
if count == 0:
candidate = nums[i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityNum1(self, nums: [int]) -> int:
"""暴力法 :param nums: :return:"""
<|body_0|>
def majorityNum2(self, nums: [int]) -> int:
"""再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。 即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。 所以可以这样操作: 设置两个变量 cand... | stack_v2_sparse_classes_36k_train_001694 | 2,023 | no_license | [
{
"docstring": "暴力法 :param nums: :return:",
"name": "majorityNum1",
"signature": "def majorityNum1(self, nums: [int]) -> int"
},
{
"docstring": "再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。 即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。 所以可以这样操作: 设置两个变量 candidate 和 count,candidate 用来保存... | 2 | stack_v2_sparse_classes_30k_val_000382 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityNum1(self, nums: [int]) -> int: 暴力法 :param nums: :return:
- def majorityNum2(self, nums: [int]) -> int: 再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。 即如果把 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityNum1(self, nums: [int]) -> int: 暴力法 :param nums: :return:
- def majorityNum2(self, nums: [int]) -> int: 再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。 即如果把 ... | 5647b418cc932cceb9e311fec016c089ca7d22d5 | <|skeleton|>
class Solution:
def majorityNum1(self, nums: [int]) -> int:
"""暴力法 :param nums: :return:"""
<|body_0|>
def majorityNum2(self, nums: [int]) -> int:
"""再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组中其他数字出现次数的总和都是比不上这个数字出现的次数 。 即如果把 该众数记为 +1 ,把其他数记为 −1 ,将它们全部加起来,和是大于 0 的。 所以可以这样操作: 设置两个变量 cand... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityNum1(self, nums: [int]) -> int:
"""暴力法 :param nums: :return:"""
nums_set = set(nums)
for i in nums_set:
if nums.count(i) > len(nums) // 2:
return i
def majorityNum2(self, nums: [int]) -> int:
"""再来回顾一下题目:寻找数组中超过一半的数字,这意味着数组... | the_stack_v2_python_sparse | Leetcode/169求众数.py | EricWangyz/Exercises | train | 0 | |
21c9a132193cfabb2307db6078d81b4b0ca3547a | [
"rospy.loginfo('Waiting for world_model action servers to become available...')\nself._cwoi = actionlib.SimpleActionClient('/spatial_world_model/create_world_object_instance', CreateWorldObjectInstanceAction)\nself._uwoi = actionlib.SimpleActionClient('/spatial_world_model/update_world_object_instance', UpdateWorld... | <|body_start_0|>
rospy.loginfo('Waiting for world_model action servers to become available...')
self._cwoi = actionlib.SimpleActionClient('/spatial_world_model/create_world_object_instance', CreateWorldObjectInstanceAction)
self._uwoi = actionlib.SimpleActionClient('/spatial_world_model/update_w... | The main RobotPoseListener object adds/updates the robot's pose in the world model. | RobotPoseListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RobotPoseListener:
"""The main RobotPoseListener object adds/updates the robot's pose in the world model."""
def __init__(self):
"""Create the RobotPoseListener to listen to a pose topic and update the world model accordingly."""
<|body_0|>
def pose_cb(self, message, arg... | stack_v2_sparse_classes_36k_train_001695 | 8,073 | no_license | [
{
"docstring": "Create the RobotPoseListener to listen to a pose topic and update the world model accordingly.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Main callback for a pose topic. This will insert a new entity in the world object instance database or update ... | 2 | null | Implement the Python class `RobotPoseListener` described below.
Class description:
The main RobotPoseListener object adds/updates the robot's pose in the world model.
Method signatures and docstrings:
- def __init__(self): Create the RobotPoseListener to listen to a pose topic and update the world model accordingly.
... | Implement the Python class `RobotPoseListener` described below.
Class description:
The main RobotPoseListener object adds/updates the robot's pose in the world model.
Method signatures and docstrings:
- def __init__(self): Create the RobotPoseListener to listen to a pose topic and update the world model accordingly.
... | 4a835a04b469360b11243405d4d1f19b706c510d | <|skeleton|>
class RobotPoseListener:
"""The main RobotPoseListener object adds/updates the robot's pose in the world model."""
def __init__(self):
"""Create the RobotPoseListener to listen to a pose topic and update the world model accordingly."""
<|body_0|>
def pose_cb(self, message, arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RobotPoseListener:
"""The main RobotPoseListener object adds/updates the robot's pose in the world model."""
def __init__(self):
"""Create the RobotPoseListener to listen to a pose topic and update the world model accordingly."""
rospy.loginfo('Waiting for world_model action servers to be... | the_stack_v2_python_sparse | spatial_world_model/world_listeners/scripts/robot_pose_listener | Playfish/cafe_demo | train | 0 |
2f8b017ef07ea356df463501615c938469e1869b | [
"padding = (1, 1)\nsuper(ConvEncoder, self).__init__()\nself._block_1 = torch.nn.Sequential(torch.nn.Conv2d(in_channels, 64, kernel_size=(3, 3), stride=(2, 2), padding_mode='zeros', padding=padding), torch.nn.BatchNorm2d(64) if not use_group_norm else torch.nn.GroupNorm(group_norm_groups, 64), torch.nn.ReLU(), torc... | <|body_start_0|>
padding = (1, 1)
super(ConvEncoder, self).__init__()
self._block_1 = torch.nn.Sequential(torch.nn.Conv2d(in_channels, 64, kernel_size=(3, 3), stride=(2, 2), padding_mode='zeros', padding=padding), torch.nn.BatchNorm2d(64) if not use_group_norm else torch.nn.GroupNorm(group_norm_... | Transforms a 2D pillar embedding into a 3D flow vector | ConvEncoder | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvEncoder:
"""Transforms a 2D pillar embedding into a 3D flow vector"""
def __init__(self, in_channels=64, out_channels=256, use_group_norm=False, group_norm_groups=4):
"""This class can either use batch norm or group norm. GroupNorm has LayerNorm and InstanceNorm as special cases.... | stack_v2_sparse_classes_36k_train_001696 | 6,470 | permissive | [
{
"docstring": "This class can either use batch norm or group norm. GroupNorm has LayerNorm and InstanceNorm as special cases. It allows to work with much smaller batch sizes. :param in_channels: :param out_channels: :param use_group_norm:",
"name": "__init__",
"signature": "def __init__(self, in_channe... | 2 | stack_v2_sparse_classes_30k_train_018358 | Implement the Python class `ConvEncoder` described below.
Class description:
Transforms a 2D pillar embedding into a 3D flow vector
Method signatures and docstrings:
- def __init__(self, in_channels=64, out_channels=256, use_group_norm=False, group_norm_groups=4): This class can either use batch norm or group norm. G... | Implement the Python class `ConvEncoder` described below.
Class description:
Transforms a 2D pillar embedding into a 3D flow vector
Method signatures and docstrings:
- def __init__(self, in_channels=64, out_channels=256, use_group_norm=False, group_norm_groups=4): This class can either use batch norm or group norm. G... | 8fb42ae338082a2d92853e109f043040558c50c9 | <|skeleton|>
class ConvEncoder:
"""Transforms a 2D pillar embedding into a 3D flow vector"""
def __init__(self, in_channels=64, out_channels=256, use_group_norm=False, group_norm_groups=4):
"""This class can either use batch norm or group norm. GroupNorm has LayerNorm and InstanceNorm as special cases.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvEncoder:
"""Transforms a 2D pillar embedding into a 3D flow vector"""
def __init__(self, in_channels=64, out_channels=256, use_group_norm=False, group_norm_groups=4):
"""This class can either use batch norm or group norm. GroupNorm has LayerNorm and InstanceNorm as special cases. It allows to... | the_stack_v2_python_sparse | networks/convEncoder.py | zivzone/FastFlow3D | train | 0 |
f3ba9eb0a420b2b1b5e16d344d20e27731163783 | [
"if not os.path.exists(path):\n os.mkdir(path)\ndict_file_name = os.path.join(path, 'dict.pkl')\nif os.path.exists(dict_file_name):\n print('Loading dictionary...')\n self.dictionary = pickle.load(open(dict_file_name, 'rb'))\n build_dict = False\nelse:\n self.dictionary = Dictionary()\n build_dict... | <|body_start_0|>
if not os.path.exists(path):
os.mkdir(path)
dict_file_name = os.path.join(path, 'dict.pkl')
if os.path.exists(dict_file_name):
print('Loading dictionary...')
self.dictionary = pickle.load(open(dict_file_name, 'rb'))
build_dict = Fa... | Word-level language model corpus. | Corpus | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Corpus:
"""Word-level language model corpus."""
def __init__(self, path, thd=0):
"""Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears less then thd times in train.txt will be replaced by <un... | stack_v2_sparse_classes_36k_train_001697 | 4,269 | permissive | [
{
"docstring": "Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears less then thd times in train.txt will be replaced by <unk>",
"name": "__init__",
"signature": "def __init__(self, path, thd=0)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_004680 | Implement the Python class `Corpus` described below.
Class description:
Word-level language model corpus.
Method signatures and docstrings:
- def __init__(self, path, thd=0): Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears... | Implement the Python class `Corpus` described below.
Class description:
Word-level language model corpus.
Method signatures and docstrings:
- def __init__(self, path, thd=0): Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Corpus:
"""Word-level language model corpus."""
def __init__(self, path, thd=0):
"""Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears less then thd times in train.txt will be replaced by <un... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Corpus:
"""Word-level language model corpus."""
def __init__(self, path, thd=0):
"""Initialization. Args: path: path to corpus location, the folder should include 'train.txt', 'valid.txt' and 'test.txt' thd: tokens that appears less then thd times in train.txt will be replaced by <unk>"""
... | the_stack_v2_python_sparse | structformer/data_penn.py | Jimmy-INL/google-research | train | 1 |
c7dd4f1b09ef97bb3ed995de895c79920ffe8e63 | [
"self._lgeos = lgeos\nself._writer = self._lgeos.GEOSWKTWriter_create()\napplied_settings = self.defaults.copy()\napplied_settings.update(settings)\nfor name in applied_settings:\n setattr(self, name, applied_settings[name])",
"if hasattr(self, name):\n object.__setattr__(self, name, value)\nelse:\n rais... | <|body_start_0|>
self._lgeos = lgeos
self._writer = self._lgeos.GEOSWKTWriter_create()
applied_settings = self.defaults.copy()
applied_settings.update(settings)
for name in applied_settings:
setattr(self, name, applied_settings[name])
<|end_body_0|>
<|body_start_1|>
... | WKTWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WKTWriter:
def __init__(self, lgeos, **settings):
"""Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1 2 3) older: POINT (1.0000000000000000 2.0000000000000000) The older formatting can be achieved fo... | stack_v2_sparse_classes_36k_train_001698 | 29,370 | permissive | [
{
"docstring": "Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1 2 3) older: POINT (1.0000000000000000 2.0000000000000000) The older formatting can be achieved for GEOS 3.3.0 and up by setting the properties: trim = False o... | 4 | null | Implement the Python class `WKTWriter` described below.
Class description:
Implement the WKTWriter class.
Method signatures and docstrings:
- def __init__(self, lgeos, **settings): Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1... | Implement the Python class `WKTWriter` described below.
Class description:
Implement the WKTWriter class.
Method signatures and docstrings:
- def __init__(self, lgeos, **settings): Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class WKTWriter:
def __init__(self, lgeos, **settings):
"""Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1 2 3) older: POINT (1.0000000000000000 2.0000000000000000) The older formatting can be achieved fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WKTWriter:
def __init__(self, lgeos, **settings):
"""Create WKT Writer Note: writer defaults are set differently for GEOS 3.3.0 and up. For example, with 'POINT Z (1 2 3)': newer: POINT Z (1 2 3) older: POINT (1.0000000000000000 2.0000000000000000) The older formatting can be achieved for GEOS 3.3.0 a... | the_stack_v2_python_sparse | Shapely_numpy/source/shapely/geos.py | ryfeus/lambda-packs | train | 1,283 | |
856dd973599627ba24280343b201f9662447d786 | [
"super().__init__(**kwargs)\nself.snrLimit = snrLimit\nself.nObs = nObs\nself.tWindow = tWindow\nself.badval = 0",
"vis = _setVis(ssoObs, self.snrLimit, self.snrCol, self.visCol)\nif len(vis) == 0:\n return self.badval\ntNights = np.sort(ssoObs[self.nightCol][vis])\ndeltaNights = np.roll(tNights, 1 - self.nObs... | <|body_start_0|>
super().__init__(**kwargs)
self.snrLimit = snrLimit
self.nObs = nObs
self.tWindow = tWindow
self.badval = 0
<|end_body_0|>
<|body_start_1|>
vis = _setVis(ssoObs, self.snrLimit, self.snrCol, self.visCol)
if len(vis) == 0:
return self.b... | Count the number of discovery opportunities with very good software for an SSobject. | MagicDiscoveryMetric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicDiscoveryMetric:
"""Count the number of discovery opportunities with very good software for an SSobject."""
def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs):
"""@ nObs = the total number of observations required for 'discovery' @ tWindow = the timespan of the disc... | stack_v2_sparse_classes_36k_train_001699 | 49,560 | no_license | [
{
"docstring": "@ nObs = the total number of observations required for 'discovery' @ tWindow = the timespan of the discovery window. @ snrLimit .. if snrLimit is None then uses 'completeness' calculation, .. if snrLimit is not None, then uses this value as a cutoff.",
"name": "__init__",
"signature": "d... | 2 | null | Implement the Python class `MagicDiscoveryMetric` described below.
Class description:
Count the number of discovery opportunities with very good software for an SSobject.
Method signatures and docstrings:
- def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs): @ nObs = the total number of observations requ... | Implement the Python class `MagicDiscoveryMetric` described below.
Class description:
Count the number of discovery opportunities with very good software for an SSobject.
Method signatures and docstrings:
- def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs): @ nObs = the total number of observations requ... | 81c08613e966e6c516dfda7a2c1a491e77170140 | <|skeleton|>
class MagicDiscoveryMetric:
"""Count the number of discovery opportunities with very good software for an SSobject."""
def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs):
"""@ nObs = the total number of observations required for 'discovery' @ tWindow = the timespan of the disc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagicDiscoveryMetric:
"""Count the number of discovery opportunities with very good software for an SSobject."""
def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs):
"""@ nObs = the total number of observations required for 'discovery' @ tWindow = the timespan of the discovery window.... | the_stack_v2_python_sparse | python/lsst/sims/maf/metrics/moMetrics.py | rjassef/sims_maf | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.