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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5be2c6791ed776c6ae3736af06f2619b9f4645d6 | [
"import heapq\nself.k = k\nself.k_nums = sorted(nums)[-k:]\nheapq.heapify(self.k_nums)",
"import heapq\nif len(self.k_nums) < self.k:\n heapq.heappush(self.k_nums, val)\nelif self.k_nums[0] < val:\n heapq.heapreplace(self.k_nums, val)\nelse:\n pass\nreturn self.k_nums[0]"
] | <|body_start_0|>
import heapq
self.k = k
self.k_nums = sorted(nums)[-k:]
heapq.heapify(self.k_nums)
<|end_body_0|>
<|body_start_1|>
import heapq
if len(self.k_nums) < self.k:
heapq.heappush(self.k_nums, val)
elif self.k_nums[0] < val:
heap... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import heapq
self.k = k
self.k_nums = sort... | stack_v2_sparse_classes_36k_train_033700 | 1,814 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002448 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 621c579c76e9f6b926354a9c25c0b0ed66890800 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
import heapq
self.k = k
self.k_nums = sorted(nums)[-k:]
heapq.heapify(self.k_nums)
def add(self, val):
""":type val: int :rtype: int"""
import heapq
if len(sel... | the_stack_v2_python_sparse | leetcode_703.py | JayWu7/Code | train | 3 | |
506507bac4769c857f5466906e713d3118799ea0 | [
"super(ConsolePrompt, self).__init__()\nself.daemon = True\nself._message = message\nself._callback = callback\nself._color = color\nself._stop_event = threading.Event()\nself._answered = False",
"self._stop_event.set()\nif not self._answered:\n console_output.cli_print(os.linesep, color=self._color, end='', l... | <|body_start_0|>
super(ConsolePrompt, self).__init__()
self.daemon = True
self._message = message
self._callback = callback
self._color = color
self._stop_event = threading.Event()
self._answered = False
<|end_body_0|>
<|body_start_1|>
self._stop_event.se... | Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background. | ConsolePrompt | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: mes... | stack_v2_sparse_classes_36k_train_033701 | 10,088 | permissive | [
{
"docstring": "Initializes a ConsolePrompt. Args: message: A string to be presented to the user. callback: A function to be called with the response string. color: An ANSI color code, or the empty string.",
"name": "__init__",
"signature": "def __init__(self, message: Text, callback: Callable[[Text], N... | 3 | stack_v2_sparse_classes_30k_test_001130 | Implement the Python class `ConsolePrompt` described below.
Class description:
Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background.
Method signatures and docstrings:
- def __init__(self, message: Text, callback: Callable[[Text], None]... | Implement the Python class `ConsolePrompt` described below.
Class description:
Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background.
Method signatures and docstrings:
- def __init__(self, message: Text, callback: Callable[[Text], None]... | 3a9a24987b2b34782fca55a8df8d007167dbb19a | <|skeleton|>
class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: mes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: message: A strin... | the_stack_v2_python_sparse | openhtf/plugs/user_input.py | google/openhtf | train | 471 |
0f432af0878131554e1b5a27c3c4624a9da34f60 | [
"self.dp = nums\nfor i in range(1, len(nums)):\n self.dp[i] += self.dp[i - 1]",
"if i > 0:\n return self.dp[j] - self.dp[i - 1]\nelse:\n return self.dp[j]"
] | <|body_start_0|>
self.dp = nums
for i in range(1, len(nums)):
self.dp[i] += self.dp[i - 1]
<|end_body_0|>
<|body_start_1|>
if i > 0:
return self.dp[j] - self.dp[i - 1]
else:
return self.dp[j]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_033702 | 576 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | c95e789d24ae9044e73acdba01a57c30b19ef9c1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.dp = nums
for i in range(1, len(nums)):
self.dp[i] += self.dp[i - 1]
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type... | the_stack_v2_python_sparse | range_sum_query_immutable.py | xiang525/my_leetcode | train | 0 | |
0fc1cbabb7e623919f8961f9dd343c2cb84f3d1f | [
"super(TemplateCreate, self).AssertBasePermission(mr)\nif not self.CheckPerm(mr, permissions.EDIT_PROJECT):\n raise permissions.PermissionException('User is not allowed to administer this project')",
"config = self.services.config.GetProjectConfig(mr.cnxn, mr.project_id)\nfield_views = tracker_views.MakeAllFie... | <|body_start_0|>
super(TemplateCreate, self).AssertBasePermission(mr)
if not self.CheckPerm(mr, permissions.EDIT_PROJECT):
raise permissions.PermissionException('User is not allowed to administer this project')
<|end_body_0|>
<|body_start_1|>
config = self.services.config.GetProject... | Servlet allowing project owners to create an issue template. | TemplateCreate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateCreate:
"""Servlet allowing project owners to create an issue template."""
def AssertBasePermission(self, mr):
"""Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from the request"""
<|body_0|>
def GatherPageData(s... | stack_v2_sparse_classes_36k_train_033703 | 6,534 | permissive | [
{
"docstring": "Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from the request",
"name": "AssertBasePermission",
"signature": "def AssertBasePermission(self, mr)"
},
{
"docstring": "Build up a dictionary of data values to use when rendering the... | 3 | stack_v2_sparse_classes_30k_train_011074 | Implement the Python class `TemplateCreate` described below.
Class description:
Servlet allowing project owners to create an issue template.
Method signatures and docstrings:
- def AssertBasePermission(self, mr): Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from th... | Implement the Python class `TemplateCreate` described below.
Class description:
Servlet allowing project owners to create an issue template.
Method signatures and docstrings:
- def AssertBasePermission(self, mr): Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from th... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class TemplateCreate:
"""Servlet allowing project owners to create an issue template."""
def AssertBasePermission(self, mr):
"""Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from the request"""
<|body_0|>
def GatherPageData(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateCreate:
"""Servlet allowing project owners to create an issue template."""
def AssertBasePermission(self, mr):
"""Check whether the user has any permission to visit this page. Args: mr: commonly used info parsed from the request"""
super(TemplateCreate, self).AssertBasePermission(... | the_stack_v2_python_sparse | appengine/monorail/tracker/templatecreate.py | xinghun61/infra | train | 2 |
af019fdef1b602f4368963cdbc480401dd4fad33 | [
"self.dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nres = []\nif not digits:\n return res\nself.helper(digits, '', res)\nreturn res",
"if not digits:\n res.append(path)\n return\nfor letter in self.dict[digits[0]]:\n self.helper(digits[1:], ... | <|body_start_0|>
self.dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = []
if not digits:
return res
self.helper(digits, '', res)
return res
<|end_body_0|>
<|body_start_1|>
if not digits:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def helper(self, digits, path, res):
""":type root: :param path: :type res: List[str] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.... | stack_v2_sparse_classes_36k_train_033704 | 743 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":type root: :param path: :type res: List[str] :return:",
"name": "helper",
"signature": "def helper(self, digits, path, res)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def helper(self, digits, path, res): :type root: :param path: :type res: List[str] :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def helper(self, digits, path, res): :type root: :param path: :type res: List[str] :return:
<|skeleto... | 772e047c4e1e9abf0d74b7dd539d684f216799b9 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def helper(self, digits, path, res):
""":type root: :param path: :type res: List[str] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
self.dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = []
if not digits:
return res
self.helper(digits, ''... | the_stack_v2_python_sparse | code/LetterCombinationsofPhoneNumber.py | crl0636/Python | train | 1 | |
1973c14aa7344330f89da254548c859416527796 | [
"if value is not None:\n if dialect.name in ('sqlite', 'mysql'):\n return value.replace(tzinfo=None)\n return value.astimezone(pytz.UTC)",
"if dialect.name in ('sqlite', 'mysql') and value is not None:\n return value.replace(tzinfo=pytz.UTC)\nreturn value"
] | <|body_start_0|>
if value is not None:
if dialect.name in ('sqlite', 'mysql'):
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
<|end_body_0|>
<|body_start_1|>
if dialect.name in ('sqlite', 'mysql') and value is not None:
return val... | UTCDateTime | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UTCDateTime:
def process_bind_param(self, value, dialect):
"""Way into the database."""
<|body_0|>
def process_result_value(self, value, dialect):
"""Way out of the database."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is not None:
... | stack_v2_sparse_classes_36k_train_033705 | 4,451 | permissive | [
{
"docstring": "Way into the database.",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value, dialect)"
},
{
"docstring": "Way out of the database.",
"name": "process_result_value",
"signature": "def process_result_value(self, value, dialect)"
}
] | 2 | null | Implement the Python class `UTCDateTime` described below.
Class description:
Implement the UTCDateTime class.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Way into the database.
- def process_result_value(self, value, dialect): Way out of the database. | Implement the Python class `UTCDateTime` described below.
Class description:
Implement the UTCDateTime class.
Method signatures and docstrings:
- def process_bind_param(self, value, dialect): Way into the database.
- def process_result_value(self, value, dialect): Way out of the database.
<|skeleton|>
class UTCDateT... | bc999f1b9baf129dc06126940880a01ac94ba405 | <|skeleton|>
class UTCDateTime:
def process_bind_param(self, value, dialect):
"""Way into the database."""
<|body_0|>
def process_result_value(self, value, dialect):
"""Way out of the database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UTCDateTime:
def process_bind_param(self, value, dialect):
"""Way into the database."""
if value is not None:
if dialect.name in ('sqlite', 'mysql'):
return value.replace(tzinfo=None)
return value.astimezone(pytz.UTC)
def process_result_value(self, ... | the_stack_v2_python_sparse | flaskbb/utils/database.py | flaskbb/flaskbb | train | 1,443 | |
c87919dc93fafaa2d8e584a99a9487bedd084d4f | [
"if len(center) == dim:\n self._center = center\nelif len(center) > dim:\n dim = len(center)\n self._center = center\nelse:\n self._center = np.zeros(shape=(dim,))\nif self._center.shape != (dim,):\n raise ValueError(f'Expected {dim}-dimensional inputs.')\nself._amp = amplitude\nself._width = width\n... | <|body_start_0|>
if len(center) == dim:
self._center = center
elif len(center) > dim:
dim = len(center)
self._center = center
else:
self._center = np.zeros(shape=(dim,))
if self._center.shape != (dim,):
raise ValueError(f'Expect... | Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w})^{2}}, where $\\mathbf{r}$ are the nodal coordinates, and $\\mathbf{r}_0$, $am... | AcousticPulse | [
"X11",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcousticPulse:
"""Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w})^{2}}, where $\\mathbf{r}$ are the no... | stack_v2_sparse_classes_36k_train_033706 | 32,800 | permissive | [
{
"docstring": "Initialize acoustic pulse parameters. Parameters ---------- dim: int specify the number of dimensions for the pulse amplitude: float specifies the value of $amplitude$ width: float specifies the rms width of the pulse center: numpy.ndarray pulse location, shape ``(dim,)``",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_013840 | Implement the Python class `AcousticPulse` described below.
Class description:
Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w... | Implement the Python class `AcousticPulse` described below.
Class description:
Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w... | 47f144782258eae2b1fb39520e96f414ae176ff4 | <|skeleton|>
class AcousticPulse:
"""Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w})^{2}}, where $\\mathbf{r}$ are the no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcousticPulse:
"""Solution initializer for N-dimensional Gaussian acoustic pulse. The Gaussian pulse is defined by: .. math:: {\\rho}E(\\mathbf{r}) = {\\rho}E + a_0 * G(\\mathbf{r})\\\\ G(\\mathbf{r}) = \\exp^{-(\\frac{(\\mathbf{r}-\\mathbf{r}_0)}{\\sqrt{2}w})^{2}}, where $\\mathbf{r}$ are the nodal coordinat... | the_stack_v2_python_sparse | mirgecom/initializers.py | kaushikcfd/mirgecom | train | 0 |
7f0d30328a2587dfa25eb079dba49795fdf3c61e | [
"params = dict()\nif Utils.is_containing_bracket(synapse_order):\n params = cls._associate_order_params_to_values(user_order, synapse_order)\n logger.debug('Parameters for order: %s' % params)\nreturn params",
"logger.debug('[OrderAnalyser._associate_order_params_to_values] user order: %s, order from synaps... | <|body_start_0|>
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_values(user_order, synapse_order)
logger.debug('Parameters for order: %s' % params)
return params
<|end_body_0|>
<|body_start_1|>
logger.debug(... | NeuronParameterLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_36k_train_033707 | 2,737 | permissive | [
{
"docstring": "Class method to get all params coming from a string order. Returns a dict of key/value.",
"name": "get_parameters",
"signature": "def get_parameters(cls, synapse_order, user_order)"
},
{
"docstring": "Associate the variables from the order to the incoming user order :param order_... | 2 | stack_v2_sparse_classes_30k_train_008598 | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | cea86934e3474b4f944b77001f952285fe2f70bf | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_va... | the_stack_v2_python_sparse | kalliope/core/NeuronParameterLoader.py | metal3d/kalliope | train | 1 | |
8c0f71d5070d8640af8e6291bbfd1146b4a75300 | [
"if path != None:\n matrix = load_npz(path)\n with open(path + '_rows', 'rb') as f:\n rows = pickle.load(f)\n with open(path + '_columns', 'rb') as f:\n columns = pickle.load(f)\nrow2id = {r: i for i, r in enumerate(rows)}\nid2row = {i: r for i, r in enumerate(rows)}\ncolumn2id = {c: i for i,... | <|body_start_0|>
if path != None:
matrix = load_npz(path)
with open(path + '_rows', 'rb') as f:
rows = pickle.load(f)
with open(path + '_columns', 'rb') as f:
columns = pickle.load(f)
row2id = {r: i for i, r in enumerate(rows)}
... | Load and save Space objects. | Space | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Space:
"""Load and save Space objects."""
def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]):
"""Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `p... | stack_v2_sparse_classes_36k_train_033708 | 1,939 | no_license | [
{
"docstring": "Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `path` should be path to a matrix in npz format, expects rows and columns in same folder at '[path]_rows' and '[path]_columns' `rows` ... | 2 | stack_v2_sparse_classes_30k_train_014701 | Implement the Python class `Space` described below.
Class description:
Load and save Space objects.
Method signatures and docstrings:
- def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) b... | Implement the Python class `Space` described below.
Class description:
Load and save Space objects.
Method signatures and docstrings:
- def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]): Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) b... | c25540943031538cbb569c4771c7b6cdefc9408c | <|skeleton|>
class Space:
"""Load and save Space objects."""
def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]):
"""Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Space:
"""Load and save Space objects."""
def __init__(self, path=None, matrix=csr_matrix([]), rows=[], columns=[]):
"""Can be either initialized (i) by providing a path, (ii) by providing a matrix, rows and columns, or (iii) by providing neither, then an empty instance is created `path` should b... | the_stack_v2_python_sparse | code/utils_.py | wabyking/unipd-DIACR-Ita | train | 0 |
c8c7743fa094ded31aa581a690b015718024a24f | [
"if not self.start_year and (not self.end_year):\n return ''\nif self.start_year == self.end_year:\n return self.start_year\ndate_parts = [self.start_year, '-', self.end_year]\nreturn ''.join([str(dp) for dp in date_parts if dp is not None])",
"if exclude is None:\n exclude = []\nif 'start_year' in exclu... | <|body_start_0|>
if not self.start_year and (not self.end_year):
return ''
if self.start_year == self.end_year:
return self.start_year
date_parts = [self.start_year, '-', self.end_year]
return ''.join([str(dp) for dp in date_parts if dp is not None])
<|end_body_0|... | Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year. | DateRange | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateRange:
"""Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year."""
def dates(self):
"""Date or date range as a string for display"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_033709 | 2,365 | permissive | [
{
"docstring": "Date or date range as a string for display",
"name": "dates",
"signature": "def dates(self)"
},
{
"docstring": "Override to clean fields to make sure start/end year are sensical",
"name": "clean_fields",
"signature": "def clean_fields(self, exclude=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014969 | Implement the Python class `DateRange` described below.
Class description:
Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year.
Method signatures and docstrings:
- def dates(self): Date or dat... | Implement the Python class `DateRange` described below.
Class description:
Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year.
Method signatures and docstrings:
- def dates(self): Date or dat... | 6371bb1266d7751af59aeaa3426ef7ac02a1fe17 | <|skeleton|>
class DateRange:
"""Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year."""
def dates(self):
"""Date or date range as a string for display"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateRange:
"""Abstract model with optional start and end years, and a custom dates property to display the date range nicely. Includes validation that requires end year falls after start year."""
def dates(self):
"""Date or date range as a string for display"""
if not self.start_year and ... | the_stack_v2_python_sparse | derrida/common/models.py | Princeton-CDH/derrida-django | train | 13 |
bee3b1af0f61e572b249c76356e2481ce1841ab6 | [
"profiles = None\nprofilesDao = ProfilesDao()\ntry:\n profiles = profilesDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn profiles",
"record = None\nprofilesDao = ProfilesDao()\ntry:\n record = profilesDao.edit(args)\nexcept Exception as e:\n abort(500, e)\nreturn record",
"record = Non... | <|body_start_0|>
profiles = None
profilesDao = ProfilesDao()
try:
profiles = profilesDao.add(args)
except Exception as e:
abort(500, e)
return profiles
<|end_body_0|>
<|body_start_1|>
record = None
profilesDao = ProfilesDao()
try:
... | ProfilesAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilesAPI:
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def get(self):
"""view"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
profiles = None
profilesDao = ProfilesDao()
... | stack_v2_sparse_classes_36k_train_033710 | 2,026 | permissive | [
{
"docstring": "add",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "edit",
"name": "put",
"signature": "def put(self, args)"
},
{
"docstring": "view",
"name": "get",
"signature": "def get(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_001253 | Implement the Python class `ProfilesAPI` described below.
Class description:
Implement the ProfilesAPI class.
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def get(self): view | Implement the Python class `ProfilesAPI` described below.
Class description:
Implement the ProfilesAPI class.
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def get(self): view
<|skeleton|>
class ProfilesAPI:
def post(self, args):
"""add"""
<|body_0|>... | 0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86 | <|skeleton|>
class ProfilesAPI:
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def get(self):
"""view"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfilesAPI:
def post(self, args):
"""add"""
profiles = None
profilesDao = ProfilesDao()
try:
profiles = profilesDao.add(args)
except Exception as e:
abort(500, e)
return profiles
def put(self, args):
"""edit"""
recor... | the_stack_v2_python_sparse | app/modules/profiles/resource.py | daitouli/baoaiback | train | 0 | |
8de9b66afccb357f2071ee07b92fe3adbd36282d | [
"self.ftp_target = ftp_target\nself.ftp_port = ftp_port\nself.verbosity = verbosity\nself.peer = '{}:{}'.format(self.ftp_target, ftp_port)\nif ssl:\n self.ftp_client = ftplib.FTP_TLS()\nelse:\n self.ftp_client = ftplib.FTP()",
"for _ in range(retries):\n try:\n self.ftp_client.connect(self.ftp_tar... | <|body_start_0|>
self.ftp_target = ftp_target
self.ftp_port = ftp_port
self.verbosity = verbosity
self.peer = '{}:{}'.format(self.ftp_target, ftp_port)
if ssl:
self.ftp_client = ftplib.FTP_TLS()
else:
self.ftp_client = ftplib.FTP()
<|end_body_0|>
... | FTP Client provides methods to handle communication with FTP server | FTPCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTPCli:
"""FTP Client provides methods to handle communication with FTP server"""
def __init__(self, ftp_target: str, ftp_port: int, ssl: bool=False, verbosity: bool=False) -> None:
"""FTP client constructor :param str ftp_target: target FTP server ip address :param int ftp_port: tar... | stack_v2_sparse_classes_36k_train_033711 | 4,319 | permissive | [
{
"docstring": "FTP client constructor :param str ftp_target: target FTP server ip address :param int ftp_port: target FTP server port :param bool ssl: target FTP ssl enabled :param bool verbosity: display verbose output :return None:",
"name": "__init__",
"signature": "def __init__(self, ftp_target: st... | 6 | null | Implement the Python class `FTPCli` described below.
Class description:
FTP Client provides methods to handle communication with FTP server
Method signatures and docstrings:
- def __init__(self, ftp_target: str, ftp_port: int, ssl: bool=False, verbosity: bool=False) -> None: FTP client constructor :param str ftp_targ... | Implement the Python class `FTPCli` described below.
Class description:
FTP Client provides methods to handle communication with FTP server
Method signatures and docstrings:
- def __init__(self, ftp_target: str, ftp_port: int, ssl: bool=False, verbosity: bool=False) -> None: FTP client constructor :param str ftp_targ... | 56ae6325c08bcedd22c57b9fe11b58f1b38314ca | <|skeleton|>
class FTPCli:
"""FTP Client provides methods to handle communication with FTP server"""
def __init__(self, ftp_target: str, ftp_port: int, ssl: bool=False, verbosity: bool=False) -> None:
"""FTP client constructor :param str ftp_target: target FTP server ip address :param int ftp_port: tar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FTPCli:
"""FTP Client provides methods to handle communication with FTP server"""
def __init__(self, ftp_target: str, ftp_port: int, ssl: bool=False, verbosity: bool=False) -> None:
"""FTP client constructor :param str ftp_target: target FTP server ip address :param int ftp_port: target FTP serve... | the_stack_v2_python_sparse | maza/core/ftp/ftp_client.py | ArturSpirin/maza | train | 2 |
e0938ab0e8efea66f7cba7e4fd1d826450c2609d | [
"super().__init__(parameter_dictionary)\nself.model_string = 'jimenez'\nmodel_dictionary = parameter_dictionary[self.model_string]\nself.ad = float(model_dictionary['ad'])\nself.kd = float(model_dictionary['kd'])\nself.bd = float(model_dictionary['bd'])",
"xi_init = cosd(turbine.yaw_angle) * sind(turbine.yaw_angl... | <|body_start_0|>
super().__init__(parameter_dictionary)
self.model_string = 'jimenez'
model_dictionary = parameter_dictionary[self.model_string]
self.ad = float(model_dictionary['ad'])
self.kd = float(model_dictionary['kd'])
self.bd = float(model_dictionary['bd'])
<|end_b... | Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for? | Jimenez | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Jimenez:
"""Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?"""
def __init__(self, par... | stack_v2_sparse_classes_36k_train_033712 | 10,947 | permissive | [
{
"docstring": "Instantiate Jimenez object and pass function paramter values. Args: parameter_dictionary (dict): input dictionary with the following key-value pairs: { \"kd\": 0.05, \"ad\": 0.0, \"bd\": 0.0 }",
"name": "__init__",
"signature": "def __init__(self, parameter_dictionary)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_010805 | Implement the Python class `Jimenez` described below.
Class description:
Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parame... | Implement the Python class `Jimenez` described below.
Class description:
Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parame... | 85f2a56fa0ab7c2237d308690a554c6101dbcd34 | <|skeleton|>
class Jimenez:
"""Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?"""
def __init__(self, par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Jimenez:
"""Subclass of the :py:class:`floris.simulation.wake_deflection.WakeDeflection` object class. Parameters required for Jimenez wake model: - ad: #TODO What is this parameter for? - kd: #TODO What is this parameter for? - bd: #TODO What is this parameter for?"""
def __init__(self, parameter_dictio... | the_stack_v2_python_sparse | floris/simulation/wake_deflection.py | PStanfel/floris | train | 3 |
551f753e060560e693b62a1f4bd84897cb9ff63f | [
"self.driver = driver\nself.ProjectFilePath = GetProjectFilePath()\nself.Page_object_data_file = open(self.ProjectFilePath + '\\\\Page_object\\\\Data\\\\DistributionlineEleQuamoncalc.yaml')\nself.Page_Data = yaml.load(self.Page_object_data_file)\nself.Page_object_data_file.close()\nself.Data = self.Page_Data['Distr... | <|body_start_0|>
self.driver = driver
self.ProjectFilePath = GetProjectFilePath()
self.Page_object_data_file = open(self.ProjectFilePath + '\\Page_object\\Data\\DistributionlineEleQuamoncalc.yaml')
self.Page_Data = yaml.load(self.Page_object_data_file)
self.Page_object_data_file.... | DistributionlineEleQuamoncalc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistributionlineEleQuamoncalc:
def __init__(self, driver):
"""配线月电量法计算"""
<|body_0|>
def DistributionlineEleQuamoncalc_Fun(self):
"""配线月电量法计算"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver = driver
self.ProjectFilePath = GetProj... | stack_v2_sparse_classes_36k_train_033713 | 4,375 | no_license | [
{
"docstring": "配线月电量法计算",
"name": "__init__",
"signature": "def __init__(self, driver)"
},
{
"docstring": "配线月电量法计算",
"name": "DistributionlineEleQuamoncalc_Fun",
"signature": "def DistributionlineEleQuamoncalc_Fun(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012348 | Implement the Python class `DistributionlineEleQuamoncalc` described below.
Class description:
Implement the DistributionlineEleQuamoncalc class.
Method signatures and docstrings:
- def __init__(self, driver): 配线月电量法计算
- def DistributionlineEleQuamoncalc_Fun(self): 配线月电量法计算 | Implement the Python class `DistributionlineEleQuamoncalc` described below.
Class description:
Implement the DistributionlineEleQuamoncalc class.
Method signatures and docstrings:
- def __init__(self, driver): 配线月电量法计算
- def DistributionlineEleQuamoncalc_Fun(self): 配线月电量法计算
<|skeleton|>
class DistributionlineEleQuam... | 190796e380df1e28770f73a392ac92f482eb9809 | <|skeleton|>
class DistributionlineEleQuamoncalc:
def __init__(self, driver):
"""配线月电量法计算"""
<|body_0|>
def DistributionlineEleQuamoncalc_Fun(self):
"""配线月电量法计算"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistributionlineEleQuamoncalc:
def __init__(self, driver):
"""配线月电量法计算"""
self.driver = driver
self.ProjectFilePath = GetProjectFilePath()
self.Page_object_data_file = open(self.ProjectFilePath + '\\Page_object\\Data\\DistributionlineEleQuamoncalc.yaml')
self.Page_Data ... | the_stack_v2_python_sparse | Project/Page_object/Page_object/DistributionlineEleQuamoncalc.py | RainsWang/Python2.7-Selenium | train | 1 | |
8088bc5b2311607af3c9946eb29481f6881a7730 | [
"if not provider:\n raise ValueError('Cache provider input must not be empty.')\nself._instances = {}\nself._provider = provider\nself._unique_settings_keys = unique_settings_keys",
"instance_vals = {key: config.get(key) for key in self._unique_settings_keys}\ninstance_key = hashlib.sha256(str(instance_vals).e... | <|body_start_0|>
if not provider:
raise ValueError('Cache provider input must not be empty.')
self._instances = {}
self._provider = provider
self._unique_settings_keys = unique_settings_keys
<|end_body_0|>
<|body_start_1|>
instance_vals = {key: config.get(key) for ke... | Cache the result of another provider. | CachedProvider | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
"""P... | stack_v2_sparse_classes_36k_train_033714 | 4,857 | permissive | [
{
"docstring": "Initialize the cached provider instance.",
"name": "__init__",
"signature": "def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=())"
},
{
"docstring": "Provide the object instance given a config and injector. Instances are cached keyed on a SHA256 digest of th... | 2 | stack_v2_sparse_classes_30k_test_000649 | Implement the Python class `CachedProvider` described below.
Class description:
Cache the result of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()): Initialize the cached provider instance.
- def provide(self, config: BaseSettings, injec... | Implement the Python class `CachedProvider` described below.
Class description:
Cache the result of another provider.
Method signatures and docstrings:
- def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()): Initialize the cached provider instance.
- def provide(self, config: BaseSettings, injec... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
"""P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CachedProvider:
"""Cache the result of another provider."""
def __init__(self, provider: BaseProvider, unique_settings_keys: tuple=()):
"""Initialize the cached provider instance."""
if not provider:
raise ValueError('Cache provider input must not be empty.')
self._ins... | the_stack_v2_python_sparse | aries_cloudagent/config/provider.py | hyperledger/aries-cloudagent-python | train | 370 |
f452576f0ee4ef180215eab15f0c0121441063ac | [
"if type(fileObj) == FileType:\n self.fh = fileObj\nelse:\n self.fh = open(fileObj)\nself.block = []\nself.lineCount = 0\nself.blockIds = set()\nself.lastId = None\nself.idField = int(idField)\nself.mustBeSorted = mustBeSorted\nself.headers = self.fh.readline().strip('\\n').strip('#').split('\\t')",
"blockI... | <|body_start_0|>
if type(fileObj) == FileType:
self.fh = fileObj
else:
self.fh = open(fileObj)
self.block = []
self.lineCount = 0
self.blockIds = set()
self.lastId = None
self.idField = int(idField)
self.mustBeSorted = mustBeSorted
... | a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE sorted with sort: remember to use the -n option, do not pipe into sort to save m... | BlockReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockReader:
"""a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE sorted with sort: remember to use the -n ... | stack_v2_sparse_classes_36k_train_033715 | 26,136 | no_license | [
{
"docstring": "initialize blockReader to read from file fname, the idField is the field which contains the id that the file is sorted on",
"name": "__init__",
"signature": "def __init__(self, fileObj, idField, mustBeSorted=True)"
},
{
"docstring": "read next block and return as list of tuples",... | 2 | null | Implement the Python class `BlockReader` described below.
Class description:
a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE so... | Implement the Python class `BlockReader` described below.
Class description:
a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE so... | 99ad033be03779e9680ce8024cdd7a4bdc5a58bd | <|skeleton|>
class BlockReader:
"""a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE sorted with sort: remember to use the -n ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockReader:
"""a parser for sorted, tables: Splits a table 'blocks' where values in one field are identical. Returns one block at a time. As such, it can process GB of tables, without having to load them into memory. if mustBeSorted==True: Tables MUST BE sorted with sort: remember to use the -n option, do no... | the_stack_v2_python_sparse | lib/maxTables.py | maximilianh/pubMunch | train | 43 |
183d4cd3678443a8a05df1d09b2721573c7706f1 | [
"args_parser = RequestParser()\nargs_parser.add_argument('page', type=inputs.positive, required=False, location='args')\nargs_parser.add_argument('per_page', type=inputs.int_range(constants.PER_PAGE_MIN, constants.PER_PAGE_MAX, 'per_page'), required=False, location='args')\nargs_parser.add_argument('keyword', locat... | <|body_start_0|>
args_parser = RequestParser()
args_parser.add_argument('page', type=inputs.positive, required=False, location='args')
args_parser.add_argument('per_page', type=inputs.int_range(constants.PER_PAGE_MIN, constants.PER_PAGE_MAX, 'per_page'), required=False, location='args')
... | 权限管理 | PermissionListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionListResource:
"""权限管理"""
def get(self):
"""获取权限列表"""
<|body_0|>
def post(self):
"""新建权限"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args_parser = RequestParser()
args_parser.add_argument('page', type=inputs.positive, requir... | stack_v2_sparse_classes_36k_train_033716 | 8,050 | no_license | [
{
"docstring": "获取权限列表",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新建权限",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000772 | Implement the Python class `PermissionListResource` described below.
Class description:
权限管理
Method signatures and docstrings:
- def get(self): 获取权限列表
- def post(self): 新建权限 | Implement the Python class `PermissionListResource` described below.
Class description:
权限管理
Method signatures and docstrings:
- def get(self): 获取权限列表
- def post(self): 新建权限
<|skeleton|>
class PermissionListResource:
"""权限管理"""
def get(self):
"""获取权限列表"""
<|body_0|>
def post(self):
... | c9703a9c57a98babf8d1e41b227aada9ef4bfe15 | <|skeleton|>
class PermissionListResource:
"""权限管理"""
def get(self):
"""获取权限列表"""
<|body_0|>
def post(self):
"""新建权限"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionListResource:
"""权限管理"""
def get(self):
"""获取权限列表"""
args_parser = RequestParser()
args_parser.add_argument('page', type=inputs.positive, required=False, location='args')
args_parser.add_argument('per_page', type=inputs.int_range(constants.PER_PAGE_MIN, constants... | the_stack_v2_python_sparse | mis/resources/system/permission.py | Yaooooooooooooo/toutiao-backend | train | 0 |
9786952b6889a2254568a02489762ec36bbde4dc | [
"self.hash_func = hash_func\nself.group_size = group_size\nif self.hash_func is None:\n raise ValueError('hash_func must be specified when using GroupHashingPartitioner')\nif self.group_size < 1:\n raise ValueError('group_size cannot be < 1 when using GroupHashingPartitioner')",
"if key is None:\n raise ... | <|body_start_0|>
self.hash_func = hash_func
self.group_size = group_size
if self.hash_func is None:
raise ValueError('hash_func must be specified when using GroupHashingPartitioner')
if self.group_size < 1:
raise ValueError('group_size cannot be < 1 when using Gro... | Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys will be shared equally between a subset of four partitions, instead of always being direct... | GroupHashingPartitioner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupHashingPartitioner:
"""Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys will be shared equally between a subset... | stack_v2_sparse_classes_36k_train_033717 | 5,870 | permissive | [
{
"docstring": ":param hash_func: A hash function :type hash_func: function :param group_size: Size of the partition group to assign to. For example, if there are 16 partitions, and we want to smooth the distribution of identical keys between a set of 4, use 4 as the group_size. :type group_size: Integer value ... | 2 | stack_v2_sparse_classes_30k_train_008768 | Implement the Python class `GroupHashingPartitioner` described below.
Class description:
Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys ... | Implement the Python class `GroupHashingPartitioner` described below.
Class description:
Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys ... | c7054bd05b127385b8c6f56a4e2241d92ff42ab4 | <|skeleton|>
class GroupHashingPartitioner:
"""Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys will be shared equally between a subset... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupHashingPartitioner:
"""Messages published with the identical keys will be directed to a consistent subset of 'n' partitions from the set of available partitions. For example, if there are 16 partitions and group_size=4, messages with the identical keys will be shared equally between a subset of four part... | the_stack_v2_python_sparse | py_kafk/tar/pykafka-2.8.1-dev.1/pykafka/partitioners.py | liuansen/python-utils-class | train | 3 |
e2f113fd94c45045ea8d27922025b95b39b35418 | [
"cells = [attention_cell] + cells\nself.use_new_attention = use_new_attention\nsuper(GNMTAttentionMultiCell, self).__init__(cells, state_is_tuple=True)",
"if not tf.contrib.framework.nest.is_sequence(state):\n raise ValueError('Expected state to be a tuple of length %d, but received: %s' % (len(self.state_size... | <|body_start_0|>
cells = [attention_cell] + cells
self.use_new_attention = use_new_attention
super(GNMTAttentionMultiCell, self).__init__(cells, state_is_tuple=True)
<|end_body_0|>
<|body_start_1|>
if not tf.contrib.framework.nest.is_sequence(state):
raise ValueError('Expect... | A MultiCell with GNMT attention style. | GNMTAttentionMultiCell | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GNMTAttentionMultiCell:
"""A MultiCell with GNMT attention style."""
def __init__(self, attention_cell, cells, use_new_attention=False):
"""Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper. cells: A list of RNNCell wrapped with AttentionInputWra... | stack_v2_sparse_classes_36k_train_033718 | 12,252 | permissive | [
{
"docstring": "Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper. cells: A list of RNNCell wrapped with AttentionInputWrapper. use_new_attention: Whether to use the attention generated from current step bottom layer's output. Default is False.",
"name": "__init__",
... | 2 | null | Implement the Python class `GNMTAttentionMultiCell` described below.
Class description:
A MultiCell with GNMT attention style.
Method signatures and docstrings:
- def __init__(self, attention_cell, cells, use_new_attention=False): Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper... | Implement the Python class `GNMTAttentionMultiCell` described below.
Class description:
A MultiCell with GNMT attention style.
Method signatures and docstrings:
- def __init__(self, attention_cell, cells, use_new_attention=False): Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper... | c540fcc99eeacfb5c51de8daa0f8cca339f50799 | <|skeleton|>
class GNMTAttentionMultiCell:
"""A MultiCell with GNMT attention style."""
def __init__(self, attention_cell, cells, use_new_attention=False):
"""Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper. cells: A list of RNNCell wrapped with AttentionInputWra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GNMTAttentionMultiCell:
"""A MultiCell with GNMT attention style."""
def __init__(self, attention_cell, cells, use_new_attention=False):
"""Creates a GNMTAttentionMultiCell. Args: attention_cell: An instance of AttentionWrapper. cells: A list of RNNCell wrapped with AttentionInputWrapper. use_new... | the_stack_v2_python_sparse | translation/gnmt/tensorflow/nmt/gnmt_model.py | mlcommons/inference | train | 575 |
5cf4d6b1215a27cb9aa981eadf4357749960b2cc | [
"self.head = None\nself.array = array\nself.ind = ind",
"node_at_cycle = None\nself.head = temp = Node(None)\nfor index, ele in enumerate(self.array):\n new_node = Node(ele)\n temp.next = new_node\n if index == self.ind:\n node_at_cycle = temp\n temp = temp.next\ntemp.next = node_at_cycle\nretu... | <|body_start_0|>
self.head = None
self.array = array
self.ind = ind
<|end_body_0|>
<|body_start_1|>
node_at_cycle = None
self.head = temp = Node(None)
for index, ele in enumerate(self.array):
new_node = Node(ele)
temp.next = new_node
i... | Class to form linked-list with cycle | FormLinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormLinkedList:
"""Class to form linked-list with cycle"""
def __init__(self, array, ind):
"""Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1"""
<|body_0|>
def createll(self):
"""Funct... | stack_v2_sparse_classes_36k_train_033719 | 3,925 | permissive | [
{
"docstring": "Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1",
"name": "__init__",
"signature": "def __init__(self, array, ind)"
},
{
"docstring": "Function to create linked-list with cycle :return:",
"name": "... | 2 | stack_v2_sparse_classes_30k_val_000451 | Implement the Python class `FormLinkedList` described below.
Class description:
Class to form linked-list with cycle
Method signatures and docstrings:
- def __init__(self, array, ind): Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1
- def ... | Implement the Python class `FormLinkedList` described below.
Class description:
Class to form linked-list with cycle
Method signatures and docstrings:
- def __init__(self, array, ind): Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1
- def ... | d24c4001a797c12347973263a0f4f98939e86900 | <|skeleton|>
class FormLinkedList:
"""Class to form linked-list with cycle"""
def __init__(self, array, ind):
"""Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1"""
<|body_0|>
def createll(self):
"""Funct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormLinkedList:
"""Class to form linked-list with cycle"""
def __init__(self, array, ind):
"""Initialization :param array: array of data of linked list :param ind: Tail linked to the index ind, if no cycle, then ind = -1"""
self.head = None
self.array = array
self.ind = in... | the_stack_v2_python_sparse | algorithms/LinkedList/floyds_tortoise_and_hare.py | bellatrixdatacommunity/data-structure-and-algorithms | train | 4 |
34324d09d54ce6de7f514320169601a83c760ecf | [
"holder = compute_base.ComputeApiHolder(base.ReleaseTrack.GA)\nzone_prop = properties.VALUES.compute.zone\nproject_prop = properties.VALUES.core.project\nself.batch_url = holder.client.batch_url\nself._compute_client = holder.client\nself.project = project_prop.Get(required=True)\nself.resources = holder.resources\... | <|body_start_0|>
holder = compute_base.ComputeApiHolder(base.ReleaseTrack.GA)
zone_prop = properties.VALUES.compute.zone
project_prop = properties.VALUES.core.project
self.batch_url = holder.client.batch_url
self._compute_client = holder.client
self.project = project_prop... | Helper that uses compute component logic to build GceConfiguration. | ConfigurationHelper | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self):
"""Updates required global state and constructs ConfigurationHelper."""
<|body_0|>
def _GetResourceUri(self, resource_name, collection, region=None, zone=No... | stack_v2_sparse_classes_36k_train_033720 | 4,621 | permissive | [
{
"docstring": "Updates required global state and constructs ConfigurationHelper.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Convert a GCE resource short-name into a URI.",
"name": "_GetResourceUri",
"signature": "def _GetResourceUri(self, resource_name, c... | 4 | null | Implement the Python class `ConfigurationHelper` described below.
Class description:
Helper that uses compute component logic to build GceConfiguration.
Method signatures and docstrings:
- def __init__(self): Updates required global state and constructs ConfigurationHelper.
- def _GetResourceUri(self, resource_name, ... | Implement the Python class `ConfigurationHelper` described below.
Class description:
Helper that uses compute component logic to build GceConfiguration.
Method signatures and docstrings:
- def __init__(self): Updates required global state and constructs ConfigurationHelper.
- def _GetResourceUri(self, resource_name, ... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self):
"""Updates required global state and constructs ConfigurationHelper."""
<|body_0|>
def _GetResourceUri(self, resource_name, collection, region=None, zone=No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigurationHelper:
"""Helper that uses compute component logic to build GceConfiguration."""
def __init__(self):
"""Updates required global state and constructs ConfigurationHelper."""
holder = compute_base.ComputeApiHolder(base.ReleaseTrack.GA)
zone_prop = properties.VALUES.com... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/dataproc/compute_helpers.py | KaranToor/MA450 | train | 1 |
c1df207614aac868817f0ebc58145b3fd6ab11c9 | [
"self.diffs = {}\nself.R = R\ncount = 0\nfor u in R.keys():\n for i, r in R[u]:\n if not i in self.diffs:\n self.diffs[i] = {}\n for i1, r1 in R[u]:\n if i == i1:\n continue\n if not i1 in self.diffs[i]:\n self.diffs[i][i1] = [0.0, 0.0]... | <|body_start_0|>
self.diffs = {}
self.R = R
count = 0
for u in R.keys():
for i, r in R[u]:
if not i in self.diffs:
self.diffs[i] = {}
for i1, r1 in R[u]:
if i == i1:
continue
... | A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan. | slopeone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class slopeone:
"""A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan."""
def __init__(self, R):
"""Generate the model. R -- A dict of the form UserID -> (ItemI... | stack_v2_sparse_classes_36k_train_033721 | 2,039 | no_license | [
{
"docstring": "Generate the model. R -- A dict of the form UserID -> (ItemId, Rating)",
"name": "__init__",
"signature": "def __init__(self, R)"
},
{
"docstring": "Returns the n best recommendations for user u. Set n = -1 to get all items recommended",
"name": "getRec",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_019059 | Implement the Python class `slopeone` described below.
Class description:
A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan.
Method signatures and docstrings:
- def __init__(self, R): Gen... | Implement the Python class `slopeone` described below.
Class description:
A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan.
Method signatures and docstrings:
- def __init__(self, R): Gen... | b01698c180cb86baa97394f7b3b51e3c849847cb | <|skeleton|>
class slopeone:
"""A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan."""
def __init__(self, R):
"""Generate the model. R -- A dict of the form UserID -> (ItemI... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class slopeone:
"""A class to compute recommendations with a Slope One Predictor. Based on: "Slope One Predictors for Online Rating-Based Collaborative Filtering" by Daniel Lemire and Anna Maclachlan."""
def __init__(self, R):
"""Generate the model. R -- A dict of the form UserID -> (ItemId, Rating)"""... | the_stack_v2_python_sparse | bin/recommender/slopeone.py | Foolius/recsyslab | train | 2 |
69f86ffd9038b134738c76594792cf6fcb8557e9 | [
"test_inventory = Inventory(123, 'chair', 100, 50)\nself.assertEqual(test_inventory.product_code, 123)\nself.assertEqual(test_inventory.description, 'chair')\nself.assertEqual(test_inventory.market_price, 100)\nself.assertEqual(test_inventory.rental_price, 50)",
"test_inventory = Inventory(123, 'chair', 100, 50).... | <|body_start_0|>
test_inventory = Inventory(123, 'chair', 100, 50)
self.assertEqual(test_inventory.product_code, 123)
self.assertEqual(test_inventory.description, 'chair')
self.assertEqual(test_inventory.market_price, 100)
self.assertEqual(test_inventory.rental_price, 50)
<|end_b... | Test the Inventory class | InventoryTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventoryTest:
"""Test the Inventory class"""
def test_init(self):
"""Test init"""
<|body_0|>
def test_return_as_dictionary(self):
"""Test the return as dictionary method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_inventory = Inventory... | stack_v2_sparse_classes_36k_train_033722 | 3,232 | no_license | [
{
"docstring": "Test init",
"name": "test_init",
"signature": "def test_init(self)"
},
{
"docstring": "Test the return as dictionary method",
"name": "test_return_as_dictionary",
"signature": "def test_return_as_dictionary(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019542 | Implement the Python class `InventoryTest` described below.
Class description:
Test the Inventory class
Method signatures and docstrings:
- def test_init(self): Test init
- def test_return_as_dictionary(self): Test the return as dictionary method | Implement the Python class `InventoryTest` described below.
Class description:
Test the Inventory class
Method signatures and docstrings:
- def test_init(self): Test init
- def test_return_as_dictionary(self): Test the return as dictionary method
<|skeleton|>
class InventoryTest:
"""Test the Inventory class"""
... | 6ffd7b4ab8346076d3b6cc02ca1ebca3bf028697 | <|skeleton|>
class InventoryTest:
"""Test the Inventory class"""
def test_init(self):
"""Test init"""
<|body_0|>
def test_return_as_dictionary(self):
"""Test the return as dictionary method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InventoryTest:
"""Test the Inventory class"""
def test_init(self):
"""Test init"""
test_inventory = Inventory(123, 'chair', 100, 50)
self.assertEqual(test_inventory.product_code, 123)
self.assertEqual(test_inventory.description, 'chair')
self.assertEqual(test_inven... | the_stack_v2_python_sparse | students/AndrewMiotke/lesson01/assignment/test_unit.py | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | train | 4 |
739e5e7240f92fca79ea739b71b5a5f7008da49a | [
"super(pmix, self).__init__(**kwargs)\nself.__baseurl = kwargs.pop('baseurl', 'https://github.com/openpmix/openpmix/releases/download')\nself.__check = kwargs.pop('check', False)\nself.__ospackages = kwargs.pop('ospackages', [])\nself.__prefix = kwargs.pop('prefix', '/usr/local/pmix')\nself.__runtime_ospackages = [... | <|body_start_0|>
super(pmix, self).__init__(**kwargs)
self.__baseurl = kwargs.pop('baseurl', 'https://github.com/openpmix/openpmix/releases/download')
self.__check = kwargs.pop('check', False)
self.__ospackages = kwargs.pop('ospackages', [])
self.__prefix = kwargs.pop('prefix', '... | The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag to specify whether the `make check` step should be performed. The defau... | pmix | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pmix:
"""The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag to specify whether the `make check` ste... | stack_v2_sparse_classes_36k_train_033723 | 7,160 | permissive | [
{
"docstring": "Initialize building block",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Based on the Linux distribution, set values accordingly. A user specified value overrides any defaults.",
"name": "__distro",
"signature": "def __distro(self)"
... | 3 | null | Implement the Python class `pmix` described below.
Class description:
The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag ... | Implement the Python class `pmix` described below.
Class description:
The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag ... | 60fd2a51c171258a6b3f93c2523101cb7018ba1b | <|skeleton|>
class pmix:
"""The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag to specify whether the `make check` ste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pmix:
"""The `pmix` building block configures, builds, and installs the [PMIX](https://github.com/openpmix/openpmix) component. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is False. check: Boolean flag to specify whether the `make check` step should be p... | the_stack_v2_python_sparse | hpccm/building_blocks/pmix.py | NVIDIA/hpc-container-maker | train | 419 |
fc32afcc9b211ae3281ea224e46296a23c77590b | [
"logger.debug('Args: %s; kwargs: %s', args, kwargs)\nself.helper = FormHelper()\nself.helper.form_id = 'signup_form'\nself.helper.form_class = 'signup'\nself.helper.layout = Layout(Fieldset('Account Details', 'username', 'email', 'password1', 'password2'), Fieldset('My Profile', HTML('\\n <p><sma... | <|body_start_0|>
logger.debug('Args: %s; kwargs: %s', args, kwargs)
self.helper = FormHelper()
self.helper.form_id = 'signup_form'
self.helper.form_class = 'signup'
self.helper.layout = Layout(Fieldset('Account Details', 'username', 'email', 'password1', 'password2'), Fieldset('M... | Customize django-allauth SignupForm to include tags. | CustomSignupForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSignupForm:
"""Customize django-allauth SignupForm to include tags."""
def __init__(self, *args, **kwargs):
"""Create a pretty crispy form."""
<|body_0|>
def signup(self, request, user):
"""Provide custom signup step (saving tags)."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_033724 | 2,749 | permissive | [
{
"docstring": "Create a pretty crispy form.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Provide custom signup step (saving tags).",
"name": "signup",
"signature": "def signup(self, request, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004278 | Implement the Python class `CustomSignupForm` described below.
Class description:
Customize django-allauth SignupForm to include tags.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a pretty crispy form.
- def signup(self, request, user): Provide custom signup step (saving tags). | Implement the Python class `CustomSignupForm` described below.
Class description:
Customize django-allauth SignupForm to include tags.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a pretty crispy form.
- def signup(self, request, user): Provide custom signup step (saving tags).
<|s... | 7882aa8ed42afe689e594a3e10c9fc6369f70bf5 | <|skeleton|>
class CustomSignupForm:
"""Customize django-allauth SignupForm to include tags."""
def __init__(self, *args, **kwargs):
"""Create a pretty crispy form."""
<|body_0|>
def signup(self, request, user):
"""Provide custom signup step (saving tags)."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomSignupForm:
"""Customize django-allauth SignupForm to include tags."""
def __init__(self, *args, **kwargs):
"""Create a pretty crispy form."""
logger.debug('Args: %s; kwargs: %s', args, kwargs)
self.helper = FormHelper()
self.helper.form_id = 'signup_form'
se... | the_stack_v2_python_sparse | freelancefinder/users/forms.py | simo97/freelancefinder | train | 0 |
471343fb66f19a525015d924c3895bfb6579e480 | [
"self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t... | <|body_start_0|>
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
self.test_user.save()
self.assertEqual(self.test_user.is_superuser, True)
... | This class covers the setup and tear down for all unit tests | BasicTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicTests:
"""This class covers the setup and tear down for all unit tests"""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_033725 | 2,724 | permissive | [
{
"docstring": "Instantiate the test client. Creates a test user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Depopulate created model instances from test database.",
"name": "tearDown",
"signature": "def tearDown(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010945 | Implement the Python class `BasicTests` described below.
Class description:
This class covers the setup and tear down for all unit tests
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances from test database. | Implement the Python class `BasicTests` described below.
Class description:
This class covers the setup and tear down for all unit tests
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances from test database.
... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class BasicTests:
"""This class covers the setup and tear down for all unit tests"""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicTests:
"""This class covers the setup and tear down for all unit tests"""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_u... | the_stack_v2_python_sparse | lab_website/tests.py | BridgesLab/Lab-Website | train | 0 |
30320a9cfbeb7999bf7cebd6f29d244942537849 | [
"self._clean_until = 0\nself._threshold = threshold\nself._prev_cleaning = None",
"if step_count == 0:\n self._clean_until = 0\nnot_me = 1 - observation['agent_slot']\nnear_river = observation['global']['observations']['POSITION'][..., 1] < 9\ncleaning = observation['global']['actions'] == CLEAN_UP_CLEAN_ACTIO... | <|body_start_0|>
self._clean_until = 0
self._threshold = threshold
self._prev_cleaning = None
<|end_body_0|>
<|body_start_1|>
if step_count == 0:
self._clean_until = 0
not_me = 1 - observation['agent_slot']
near_river = observation['global']['observations']['... | Cleanup puppeteer for a reciprocating agent. | ConditionalCleaner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
<|body_0|>
def __call__(self, step_count:... | stack_v2_sparse_classes_36k_train_033726 | 7,109 | permissive | [
{
"docstring": "Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.",
"name": "__init__",
"signature": "def __init__(self, threshold: int) -> None"
},
{
"docstring": "Puppeteer step. Args: step_count: steps since episode started. observati... | 2 | stack_v2_sparse_classes_30k_train_020061 | Implement the Python class `ConditionalCleaner` described below.
Class description:
Cleanup puppeteer for a reciprocating agent.
Method signatures and docstrings:
- def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.
... | Implement the Python class `ConditionalCleaner` described below.
Class description:
Cleanup puppeteer for a reciprocating agent.
Method signatures and docstrings:
- def __init__(self, threshold: int) -> None: Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning.
... | e42b916b32771f7af5ad4eccbdf4ded410735299 | <|skeleton|>
class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
<|body_0|>
def __call__(self, step_count:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalCleaner:
"""Cleanup puppeteer for a reciprocating agent."""
def __init__(self, threshold: int) -> None:
"""Initializes the puppeteer. Args: threshold: number of other cleaners below which it will switch to cleaning."""
self._clean_until = 0
self._threshold = threshold
... | the_stack_v2_python_sparse | meltingpot/python/utils/bots/puppeteer_functions.py | classicvalues/meltingpot | train | 0 |
b71e1ee02deee6fe263cc290586238f3aeb003d8 | [
"try:\n con = ldap.open(settings.LDAP_SERVER, 389)\n user = User.objects.get(username=username)\nexcept Exception as e:\n user = None\nreturn user",
"try:\n return User.objects.get(pk=user_id)\nexcept User.DoesNotExist:\n return None"
] | <|body_start_0|>
try:
con = ldap.open(settings.LDAP_SERVER, 389)
user = User.objects.get(username=username)
except Exception as e:
user = None
return user
<|end_body_0|>
<|body_start_1|>
try:
return User.objects.get(pk=user_id)
exc... | Provides methods to authenticate against LDAP and get_user from the Auth plug-in. | LDAPBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
... | stack_v2_sparse_classes_36k_train_033727 | 1,753 | no_license | [
{
"docstring": "Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389.",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Get user object from Auth.User.",
"name": ... | 2 | null | Implement the Python class `LDAPBackend` described below.
Class description:
Provides methods to authenticate against LDAP and get_user from the Auth plug-in.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate against the LDAP server provided by settings.LDAP_SERVER... | Implement the Python class `LDAPBackend` described below.
Class description:
Provides methods to authenticate against LDAP and get_user from the Auth plug-in.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate against the LDAP server provided by settings.LDAP_SERVER... | 7a337e0e3a20180b9564de68ab22620dc9aa1a36 | <|skeleton|>
class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LDAPBackend:
"""Provides methods to authenticate against LDAP and get_user from the Auth plug-in."""
def authenticate(self, username=None, password=None):
"""Authenticate against the LDAP server provided by settings.LDAP_SERVER. The LDAP server is assumed to listen to port 389."""
try:
... | the_stack_v2_python_sparse | project_management/access_control/authentication.py | raveena17/ILASM | train | 0 |
6927376359f499d34cba193dd6735e2435874c5c | [
"Editeur.__init__(self, pere, objet, attribut)\nself.ajouter_option('n', self.opt_ajouter_cycle)\nself.ajouter_option('d', self.opt_supprimer_cycle)",
"prototype = self.objet\narguments = arguments.strip()\nif not arguments:\n self.pere << \"|err|Précisez l'âge minimum du cycle suivi d'un espace et de son nom.... | <|body_start_0|>
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_ajouter_cycle)
self.ajouter_option('d', self.opt_supprimer_cycle)
<|end_body_0|>
<|body_start_1|>
prototype = self.objet
arguments = arguments.strip()
if not arguments:
... | Contexte-éditeur d'édition des cycles du prototype végétal. | EdtCycles | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdtCycles:
"""Contexte-éditeur d'édition des cycles du prototype végétal."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_ajouter_cycle(self, arguments):
"""Ajout d'un cycle. Syntaxe : /n <age> <nom du cy... | stack_v2_sparse_classes_36k_train_033728 | 5,177 | permissive | [
{
"docstring": "Constructeur de l'éditeur",
"name": "__init__",
"signature": "def __init__(self, pere, objet=None, attribut=None)"
},
{
"docstring": "Ajout d'un cycle. Syntaxe : /n <age> <nom du cycle>",
"name": "opt_ajouter_cycle",
"signature": "def opt_ajouter_cycle(self, arguments)"
... | 5 | null | Implement the Python class `EdtCycles` described below.
Class description:
Contexte-éditeur d'édition des cycles du prototype végétal.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def opt_ajouter_cycle(self, arguments): Ajout d'un cycle. Syntaxe ... | Implement the Python class `EdtCycles` described below.
Class description:
Contexte-éditeur d'édition des cycles du prototype végétal.
Method signatures and docstrings:
- def __init__(self, pere, objet=None, attribut=None): Constructeur de l'éditeur
- def opt_ajouter_cycle(self, arguments): Ajout d'un cycle. Syntaxe ... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class EdtCycles:
"""Contexte-éditeur d'édition des cycles du prototype végétal."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
<|body_0|>
def opt_ajouter_cycle(self, arguments):
"""Ajout d'un cycle. Syntaxe : /n <age> <nom du cy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdtCycles:
"""Contexte-éditeur d'édition des cycles du prototype végétal."""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
Editeur.__init__(self, pere, objet, attribut)
self.ajouter_option('n', self.opt_ajouter_cycle)
self.ajouter_opt... | the_stack_v2_python_sparse | src/secondaires/botanique/editeurs/vegedit/edt_cycles.py | vincent-lg/tsunami | train | 5 |
47f67abc9447f36403dc142cdc3dcc3c9628d0ab | [
"logger.debug('HANDLER RUNNER ({}): Starting runner'.format(handler_name))\n_handler_callback = self._generate_callback_for_handler('CLIENT_EVENT')\ntpe = concurrent.futures.ThreadPoolExecutor(max_workers=4)\nwhile True:\n handler_arg = await inbox.get()\n if isinstance(handler_arg, HandlerRunnerKillerSentine... | <|body_start_0|>
logger.debug('HANDLER RUNNER ({}): Starting runner'.format(handler_name))
_handler_callback = self._generate_callback_for_handler('CLIENT_EVENT')
tpe = concurrent.futures.ThreadPoolExecutor(max_workers=4)
while True:
handler_arg = await inbox.get()
... | Handler manager for use with asynchronous clients | AsyncHandlerManager | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncHandlerManager:
"""Handler manager for use with asynchronous clients"""
async def _receiver_handler_runner(self, inbox, handler_name):
"""Run infinite loop that waits for an inbox to receive an object from it, then calls the handler with that object"""
<|body_0|>
as... | stack_v2_sparse_classes_36k_train_033729 | 12,824 | permissive | [
{
"docstring": "Run infinite loop that waits for an inbox to receive an object from it, then calls the handler with that object",
"name": "_receiver_handler_runner",
"signature": "async def _receiver_handler_runner(self, inbox, handler_name)"
},
{
"docstring": "Run infinite loop that waits for t... | 6 | stack_v2_sparse_classes_30k_train_006731 | Implement the Python class `AsyncHandlerManager` described below.
Class description:
Handler manager for use with asynchronous clients
Method signatures and docstrings:
- async def _receiver_handler_runner(self, inbox, handler_name): Run infinite loop that waits for an inbox to receive an object from it, then calls t... | Implement the Python class `AsyncHandlerManager` described below.
Class description:
Handler manager for use with asynchronous clients
Method signatures and docstrings:
- async def _receiver_handler_runner(self, inbox, handler_name): Run infinite loop that waits for an inbox to receive an object from it, then calls t... | 5d343d5904aaa98c6a88101e0dc40263acff4db2 | <|skeleton|>
class AsyncHandlerManager:
"""Handler manager for use with asynchronous clients"""
async def _receiver_handler_runner(self, inbox, handler_name):
"""Run infinite loop that waits for an inbox to receive an object from it, then calls the handler with that object"""
<|body_0|>
as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncHandlerManager:
"""Handler manager for use with asynchronous clients"""
async def _receiver_handler_runner(self, inbox, handler_name):
"""Run infinite loop that waits for an inbox to receive an object from it, then calls the handler with that object"""
logger.debug('HANDLER RUNNER ({... | the_stack_v2_python_sparse | azure-iot-device/azure/iot/device/iothub/aio/async_handler_manager.py | Azure/azure-iot-sdk-python | train | 441 |
091f3bf0eb432fbd27cb769bd8cd5ca61181aaa0 | [
"import collections\nif len(hand) % W != 0:\n return False\nmaps = collections.Counter(hand)\nprint(maps)\nstart = sorted(maps.keys(), reverse=True)\nwhile start:\n for i in range(W):\n key = start[-1] + i\n if key not in maps or maps[key] <= 0:\n return False\n else:\n ... | <|body_start_0|>
import collections
if len(hand) % W != 0:
return False
maps = collections.Counter(hand)
print(maps)
start = sorted(maps.keys(), reverse=True)
while start:
for i in range(W):
key = start[-1] + i
if ke... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
<|body_0|>
def isNStraightHand_1(self, hand, W):
"""198ms :param hand: :param W: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
impo... | stack_v2_sparse_classes_36k_train_033730 | 1,902 | no_license | [
{
"docstring": ":type hand: List[int] :type W: int :rtype: bool 204 ms",
"name": "isNStraightHand",
"signature": "def isNStraightHand(self, hand, W)"
},
{
"docstring": "198ms :param hand: :param W: :return:",
"name": "isNStraightHand_1",
"signature": "def isNStraightHand_1(self, hand, W)... | 2 | stack_v2_sparse_classes_30k_train_008449 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNStraightHand(self, hand, W): :type hand: List[int] :type W: int :rtype: bool 204 ms
- def isNStraightHand_1(self, hand, W): 198ms :param hand: :param W: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isNStraightHand(self, hand, W): :type hand: List[int] :type W: int :rtype: bool 204 ms
- def isNStraightHand_1(self, hand, W): 198ms :param hand: :param W: :return:
<|skelet... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
<|body_0|>
def isNStraightHand_1(self, hand, W):
"""198ms :param hand: :param W: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isNStraightHand(self, hand, W):
""":type hand: List[int] :type W: int :rtype: bool 204 ms"""
import collections
if len(hand) % W != 0:
return False
maps = collections.Counter(hand)
print(maps)
start = sorted(maps.keys(), reverse=True)
... | the_stack_v2_python_sparse | HandOfStraights_MID_846.py | 953250587/leetcode-python | train | 2 | |
f87525aaeca11f5761675fd9838c7df9242938f3 | [
"f_count = len(filter_seq)\nevent_seq_tuple = itertools.tee(aevent_seq, f_count + 1)\nfor filter_desc, event_seq in zip(filter_seq, event_seq_tuple[1:]):\n offset = filter_desc.get('offset', 0)\n new_event_seq = filter_desc.get('filter').filter_objects(event_seq)\n for event in new_event_seq:\n filt... | <|body_start_0|>
f_count = len(filter_seq)
event_seq_tuple = itertools.tee(aevent_seq, f_count + 1)
for filter_desc, event_seq in zip(filter_seq, event_seq_tuple[1:]):
offset = filter_desc.get('offset', 0)
new_event_seq = filter_desc.get('filter').filter_objects(event_seq... | ... | BaseEventSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
<|body_0|>
def filter_events(self, event_seq, **_):
"""Should be implemented :param event_seq: :param _: :return:"""
<|bo... | stack_v2_sparse_classes_36k_train_033731 | 2,158 | permissive | [
{
"docstring": ":param aevent_seq: :param chart: :param filter_seq:",
"name": "plot",
"signature": "def plot(self, aevent_seq, chart, filter_seq)"
},
{
"docstring": "Should be implemented :param event_seq: :param _: :return:",
"name": "filter_events",
"signature": "def filter_events(self... | 2 | stack_v2_sparse_classes_30k_train_020453 | Implement the Python class `BaseEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def plot(self, aevent_seq, chart, filter_seq): :param aevent_seq: :param chart: :param filter_seq:
- def filter_events(self, event_seq, **_): Should be implemented :param event_seq: :param _: :re... | Implement the Python class `BaseEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def plot(self, aevent_seq, chart, filter_seq): :param aevent_seq: :param chart: :param filter_seq:
- def filter_events(self, event_seq, **_): Should be implemented :param event_seq: :param _: :re... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
<|body_0|>
def filter_events(self, event_seq, **_):
"""Should be implemented :param event_seq: :param _: :return:"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseEventSelector:
"""..."""
def plot(self, aevent_seq, chart, filter_seq):
""":param aevent_seq: :param chart: :param filter_seq:"""
f_count = len(filter_seq)
event_seq_tuple = itertools.tee(aevent_seq, f_count + 1)
for filter_desc, event_seq in zip(filter_seq, event_seq_... | the_stack_v2_python_sparse | shot_detector/selectors/event/base_event_selector.py | w495/python-video-shot-detector | train | 20 |
a7959037b2547bff44d513cd07966a7710900164 | [
"args: List[Union[str, ResolvedExpression]] = list(constructor_args)\nif abstract_expr:\n args.append(f'Debug_String => {sloc_info_arg(abstract_expr.location)}')\nsuper().__init__('Bind_Result', constructor_name, T.Equation, args, abstract_expr=abstract_expr)",
"assocs: List[Tuple[str, LiteralExpr]] = []\nif a... | <|body_start_0|>
args: List[Union[str, ResolvedExpression]] = list(constructor_args)
if abstract_expr:
args.append(f'Debug_String => {sloc_info_arg(abstract_expr.location)}')
super().__init__('Bind_Result', constructor_name, T.Equation, args, abstract_expr=abstract_expr)
<|end_body_0... | Base class for resolved expressions that create Assign/Propagate/Unify equations. | BindExpr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BindExpr:
"""Base class for resolved expressions that create Assign/Propagate/Unify equations."""
def __init__(self, constructor_name: str, constructor_args: List[Union[str, ResolvedExpression]], abstract_expr: Optional[AbstractExpression]=None):
""":param constructor_name: Name of t... | stack_v2_sparse_classes_36k_train_033732 | 30,619 | permissive | [
{
"docstring": ":param constructor_name: Name of the function to create the equation. :param constructor_args: Its arguments, exclusing the \"Debug_String\" one, which we automatically add. :param abstract_expr: Reference to the corresponding abstract expression, if any.",
"name": "__init__",
"signature... | 2 | stack_v2_sparse_classes_30k_val_000878 | Implement the Python class `BindExpr` described below.
Class description:
Base class for resolved expressions that create Assign/Propagate/Unify equations.
Method signatures and docstrings:
- def __init__(self, constructor_name: str, constructor_args: List[Union[str, ResolvedExpression]], abstract_expr: Optional[Abst... | Implement the Python class `BindExpr` described below.
Class description:
Base class for resolved expressions that create Assign/Propagate/Unify equations.
Method signatures and docstrings:
- def __init__(self, constructor_name: str, constructor_args: List[Union[str, ResolvedExpression]], abstract_expr: Optional[Abst... | a638facb03edb4baefdf8f1819db4ca56f191a5b | <|skeleton|>
class BindExpr:
"""Base class for resolved expressions that create Assign/Propagate/Unify equations."""
def __init__(self, constructor_name: str, constructor_args: List[Union[str, ResolvedExpression]], abstract_expr: Optional[AbstractExpression]=None):
""":param constructor_name: Name of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BindExpr:
"""Base class for resolved expressions that create Assign/Propagate/Unify equations."""
def __init__(self, constructor_name: str, constructor_args: List[Union[str, ResolvedExpression]], abstract_expr: Optional[AbstractExpression]=None):
""":param constructor_name: Name of the function t... | the_stack_v2_python_sparse | langkit/expressions/logic.py | shintakezou/langkit | train | 0 |
1d6b06e38e2bb547d6b7d30db8a1682ef06c4508 | [
"self.corner = posn\nself.width = w\nself.height = h",
"if rec1.corner.x <= rec2.corner.x and rec1.corner.x + rec1.width >= rec2.corner.x and (rec1.corner.y <= rec2.corner.y) and (rec1.corner.y + rec1.width >= rec2.corner.y):\n return True\nelif rec2.corner.x <= rec1.corner.x and rec2.corner.x + rec2.width >= ... | <|body_start_0|>
self.corner = posn
self.width = w
self.height = h
<|end_body_0|>
<|body_start_1|>
if rec1.corner.x <= rec2.corner.x and rec1.corner.x + rec1.width >= rec2.corner.x and (rec1.corner.y <= rec2.corner.y) and (rec1.corner.y + rec1.width >= rec2.corner.y):
return... | A class to manufacture rectangle objects | Rectangle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rectangle:
"""A class to manufacture rectangle objects"""
def __init__(self, posn, w, h):
"""Initialize rectangle at posn, with width w, height h"""
<|body_0|>
def there_is_collision(rec1, rec2):
"""Functions that verifies the superposition between two rectangles... | stack_v2_sparse_classes_36k_train_033733 | 3,255 | no_license | [
{
"docstring": "Initialize rectangle at posn, with width w, height h",
"name": "__init__",
"signature": "def __init__(self, posn, w, h)"
},
{
"docstring": "Functions that verifies the superposition between two rectangles",
"name": "there_is_collision",
"signature": "def there_is_collisio... | 2 | stack_v2_sparse_classes_30k_train_014828 | Implement the Python class `Rectangle` described below.
Class description:
A class to manufacture rectangle objects
Method signatures and docstrings:
- def __init__(self, posn, w, h): Initialize rectangle at posn, with width w, height h
- def there_is_collision(rec1, rec2): Functions that verifies the superposition b... | Implement the Python class `Rectangle` described below.
Class description:
A class to manufacture rectangle objects
Method signatures and docstrings:
- def __init__(self, posn, w, h): Initialize rectangle at posn, with width w, height h
- def there_is_collision(rec1, rec2): Functions that verifies the superposition b... | aa07d1fd2cfead79f57822d6eb680f19eb270e40 | <|skeleton|>
class Rectangle:
"""A class to manufacture rectangle objects"""
def __init__(self, posn, w, h):
"""Initialize rectangle at posn, with width w, height h"""
<|body_0|>
def there_is_collision(rec1, rec2):
"""Functions that verifies the superposition between two rectangles... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rectangle:
"""A class to manufacture rectangle objects"""
def __init__(self, posn, w, h):
"""Initialize rectangle at posn, with width w, height h"""
self.corner = posn
self.width = w
self.height = h
def there_is_collision(rec1, rec2):
"""Functions that verifie... | the_stack_v2_python_sparse | aula4/16.6.5.py | brunodoria/Exercises | train | 0 |
45c282e5451e9b9c2e4ffd94629784853dfa1c92 | [
"log.debug('GET request from user %s for project stage %s' % (request.user, stageplan_id))\nproj = Project.objects.get(project_number=project_number)\nstage = ProjectStage.objects.get(id=stageplan_id)\nif not check_project_read_acl(proj, request.user):\n log.debug('Refusing GET request for project %s from user %... | <|body_start_0|>
log.debug('GET request from user %s for project stage %s' % (request.user, stageplan_id))
proj = Project.objects.get(project_number=project_number)
stage = ProjectStage.objects.get(id=stageplan_id)
if not check_project_read_acl(proj, request.user):
log.debug(... | URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan | StageplanResourceHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
<|body_0|>
def update(self, request, proj... | stack_v2_sparse_classes_36k_train_033734 | 19,350 | no_license | [
{
"docstring": "View a Project Stage",
"name": "read",
"signature": "def read(self, request, project_number, stageplan_id)"
},
{
"docstring": "Update the Project Stage",
"name": "update",
"signature": "def update(self, request, project_number, stageplan_id)"
},
{
"docstring": "Di... | 3 | stack_v2_sparse_classes_30k_train_016306 | Implement the Python class `StageplanResourceHandler` described below.
Class description:
URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan
Method signatures and docstrings:
- def read(self, request, project_number, stageplan_id): View a Project Stage
... | Implement the Python class `StageplanResourceHandler` described below.
Class description:
URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan
Method signatures and docstrings:
- def read(self, request, project_number, stageplan_id): View a Project Stage
... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
<|body_0|>
def update(self, request, proj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
log.debug('GET request from user %s for project stage %s' %... | the_stack_v2_python_sparse | branches/rest-api-branch/django-project-management/wbs/api_views.py | NhaTrang/django-project-management | train | 0 |
edb8663bbc1e929f019132e71a93285c02a822ac | [
"self.readconfig = ReadConfig('./config/relydata.yaml')\nself.res = res\nself.parameter = parameter",
"if ',' in self.parameter:\n parameters = self.parameter.split(sep=',')\n for item in parameters:\n pra = item.split(sep='.')\n parameter_data = {pra[2]: self.res[pra[0]][pra[1]][pra[2]]}\n ... | <|body_start_0|>
self.readconfig = ReadConfig('./config/relydata.yaml')
self.res = res
self.parameter = parameter
<|end_body_0|>
<|body_start_1|>
if ',' in self.parameter:
parameters = self.parameter.split(sep=',')
for item in parameters:
pra = it... | RelyDependent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelyDependent:
def __init__(self, res, parameter=None):
"""初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数"""
<|body_0|>
def rely_dependent(self):
"""提取响应内容,并且存储到文件中 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.readconfig = R... | stack_v2_sparse_classes_36k_train_033735 | 1,255 | no_license | [
{
"docstring": "初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数",
"name": "__init__",
"signature": "def __init__(self, res, parameter=None)"
},
{
"docstring": "提取响应内容,并且存储到文件中 :return:",
"name": "rely_dependent",
"signature": "def rely_dependent(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000270 | Implement the Python class `RelyDependent` described below.
Class description:
Implement the RelyDependent class.
Method signatures and docstrings:
- def __init__(self, res, parameter=None): 初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数
- def rely_dependent(self): 提取响应内容,并且存储到文件中 :return: | Implement the Python class `RelyDependent` described below.
Class description:
Implement the RelyDependent class.
Method signatures and docstrings:
- def __init__(self, res, parameter=None): 初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数
- def rely_dependent(self): 提取响应内容,并且存储到文件中 :return:
<|skeleton|>
class... | 2eb22aba48ca50c822c94064f6d8abdacc32ef6f | <|skeleton|>
class RelyDependent:
def __init__(self, res, parameter=None):
"""初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数"""
<|body_0|>
def rely_dependent(self):
"""提取响应内容,并且存储到文件中 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelyDependent:
def __init__(self, res, parameter=None):
"""初始化init方法 :param res: 响应结果 :param parameter: 需要提取的请求参数"""
self.readconfig = ReadConfig('./config/relydata.yaml')
self.res = res
self.parameter = parameter
def rely_dependent(self):
"""提取响应内容,并且存储到文件中 :retur... | the_stack_v2_python_sparse | tpttest/TESTAPI/util/rely_dependent.py | Gentlemanbao/test01 | train | 0 | |
7a67e48b4680d4e2115c461925147065f73d1d10 | [
"n = len(nums)\np = [1] * n\nq = [1] * n\nres = [1] * n\nfor i in range(1, n):\n p[i] = p[i - 1] * nums[i - 1]\nfor i in range(n - 2, -1, -1):\n q[i] = q[i + 1] * nums[i + 1]\nfor i in range(n):\n res[i] = p[i] * q[i]\nreturn res",
"n = len(nums)\nres = [1] * n\nt = 1\nfor i in range(n):\n res[i] *= t... | <|body_start_0|>
n = len(nums)
p = [1] * n
q = [1] * n
res = [1] * n
for i in range(1, n):
p[i] = p[i - 1] * nums[i - 1]
for i in range(n - 2, -1, -1):
q[i] = q[i + 1] * nums[i + 1]
for i in range(n):
res[i] = p[i] * q[i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
"""p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf2(self, nums):
"""使用常数空间实现 变量t 存储前缀积和后缀积 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_033736 | 1,559 | no_license | [
{
"docstring": "p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf",
"signature": "def productExceptSelf(self, nums)"
},
{
"docstring": "使用常数空间实现 变量t 存储前缀积和后缀积 :param nums: :return:",
"name": "productExceptSelf2",
"signature": "def produc... | 2 | stack_v2_sparse_classes_30k_train_001174 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]
- def productExceptSelf2(self, nums): 使用常数空间实现 变量t 存储前缀积和后缀积 :param num... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf(self, nums): p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]
- def productExceptSelf2(self, nums): 使用常数空间实现 变量t 存储前缀积和后缀积 :param num... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def productExceptSelf(self, nums):
"""p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf2(self, nums):
"""使用常数空间实现 变量t 存储前缀积和后缀积 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def productExceptSelf(self, nums):
"""p[i] 除第i个元素的前缀积 q[i] 除第i个元素的后缀积 :type nums: List[int] :rtype: List[int]"""
n = len(nums)
p = [1] * n
q = [1] * n
res = [1] * n
for i in range(1, n):
p[i] = p[i - 1] * nums[i - 1]
for i in range(... | the_stack_v2_python_sparse | 238_除自身以外数组的乘积.py | lovehhf/LeetCode | train | 0 | |
b72d41e657efd9ebee6eaa078f657cb06e1951b0 | [
"newcallback = CallBack(callback, page) if callback else None\nok = True\nfor p, overlayrect in page.visiblePagesAt(rect):\n if overlayrect and p.renderer and (not p.renderer.update(p, device, overlayrect.translated(-p.pos()), newcallback)):\n ok = False\nreturn ok",
"newcallback = CallBack(callback, pa... | <|body_start_0|>
newcallback = CallBack(callback, page) if callback else None
ok = True
for p, overlayrect in page.visiblePagesAt(rect):
if overlayrect and p.renderer and (not p.renderer.update(p, device, overlayrect.translated(-p.pos()), newcallback)):
ok = False
... | A renderer that interfaces with the renderers of the sub pages of a MultiPage. | MultiPageRenderer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiPageRenderer:
"""A renderer that interfaces with the renderers of the sub pages of a MultiPage."""
def update(self, page, device, rect, callback=None):
"""Reimplemented to check/rerender (if needed) all sub pages."""
<|body_0|>
def paint(self, page, painter, rect, c... | stack_v2_sparse_classes_36k_train_033737 | 14,415 | no_license | [
{
"docstring": "Reimplemented to check/rerender (if needed) all sub pages.",
"name": "update",
"signature": "def update(self, page, device, rect, callback=None)"
},
{
"docstring": "Reimplemented to paint all the sub pages on top of each other.",
"name": "paint",
"signature": "def paint(s... | 6 | stack_v2_sparse_classes_30k_train_012489 | Implement the Python class `MultiPageRenderer` described below.
Class description:
A renderer that interfaces with the renderers of the sub pages of a MultiPage.
Method signatures and docstrings:
- def update(self, page, device, rect, callback=None): Reimplemented to check/rerender (if needed) all sub pages.
- def pa... | Implement the Python class `MultiPageRenderer` described below.
Class description:
A renderer that interfaces with the renderers of the sub pages of a MultiPage.
Method signatures and docstrings:
- def update(self, page, device, rect, callback=None): Reimplemented to check/rerender (if needed) all sub pages.
- def pa... | 2f870fa69495ffc22913550cbdf3e8c606d3d998 | <|skeleton|>
class MultiPageRenderer:
"""A renderer that interfaces with the renderers of the sub pages of a MultiPage."""
def update(self, page, device, rect, callback=None):
"""Reimplemented to check/rerender (if needed) all sub pages."""
<|body_0|>
def paint(self, page, painter, rect, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiPageRenderer:
"""A renderer that interfaces with the renderers of the sub pages of a MultiPage."""
def update(self, page, device, rect, callback=None):
"""Reimplemented to check/rerender (if needed) all sub pages."""
newcallback = CallBack(callback, page) if callback else None
... | the_stack_v2_python_sparse | VenvSocket/Lib/site-packages/qpageview/multipage.py | crq-13/PintMegaPapel | train | 0 |
9fca160be48c7968566767f5aeb449ee8de6d461 | [
"timetable_detail = []\nself._cr.execute('select t.start_time,t.end_time,s.name,week_day,\\n st.employee_id, hr.name as\\n teacher from time_table_line t,\\n subject_subject s, resource_resource r, school_teacher\\n st, hr_e... | <|body_start_0|>
timetable_detail = []
self._cr.execute('select t.start_time,t.end_time,s.name,week_day,\n st.employee_id, hr.name as\n teacher from time_table_line t,\n subject_subject s, resource_resource r, school_teacher\n ... | ReportTimetableInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportTimetableInfo:
def _get_timetable(self, timetable_id):
"""Method to combain values for timetable"""
<|body_0|>
def _get_report_values(self, docids, data=None):
"""Inherited method to get report data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_033738 | 2,646 | no_license | [
{
"docstring": "Method to combain values for timetable",
"name": "_get_timetable",
"signature": "def _get_timetable(self, timetable_id)"
},
{
"docstring": "Inherited method to get report data",
"name": "_get_report_values",
"signature": "def _get_report_values(self, docids, data=None)"
... | 2 | stack_v2_sparse_classes_30k_train_021116 | Implement the Python class `ReportTimetableInfo` described below.
Class description:
Implement the ReportTimetableInfo class.
Method signatures and docstrings:
- def _get_timetable(self, timetable_id): Method to combain values for timetable
- def _get_report_values(self, docids, data=None): Inherited method to get re... | Implement the Python class `ReportTimetableInfo` described below.
Class description:
Implement the ReportTimetableInfo class.
Method signatures and docstrings:
- def _get_timetable(self, timetable_id): Method to combain values for timetable
- def _get_report_values(self, docids, data=None): Inherited method to get re... | 6a9793f3a15da9eed40bf840b1d9a46457c5fd55 | <|skeleton|>
class ReportTimetableInfo:
def _get_timetable(self, timetable_id):
"""Method to combain values for timetable"""
<|body_0|>
def _get_report_values(self, docids, data=None):
"""Inherited method to get report data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportTimetableInfo:
def _get_timetable(self, timetable_id):
"""Method to combain values for timetable"""
timetable_detail = []
self._cr.execute('select t.start_time,t.end_time,s.name,week_day,\n st.employee_id, hr.name as\n teacher from ti... | the_stack_v2_python_sparse | timetable/report/timetable_info.py | JayVora-SerpentCS/OdooEduERP | train | 121 | |
79c030780eaf561ae61933004eb011d5c3548066 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('janellc_rstiffel_yash', 'janellc_rstiffel_yash')\nrepo.dropCollection('crimesData')\nrepo.createCollection('crimesData')\nn = 0\ndf = pd.DataFrame()\nstartTime = time.time()\nwhile True:\n url = 'http... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel_yash', 'janellc_rstiffel_yash')
repo.dropCollection('crimesData')
repo.createCollection('crimesData')
n = 0
df = ... | getCrimes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getCrimes:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything hap... | stack_v2_sparse_classes_36k_train_033739 | 3,693 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_000922 | Implement the Python class `getCrimes` described below.
Class description:
Implement the getCrimes class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=N... | Implement the Python class `getCrimes` described below.
Class description:
Implement the getCrimes class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=N... | c7a43805695bc7529119734a629e13c0266fe0e8 | <|skeleton|>
class getCrimes:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything hap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getCrimes:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('janellc_rstiffel_yash', 'janellc_rstiffel... | the_stack_v2_python_sparse | janellc_rstiffel_yash/getCrimes.py | rhondamak/course-2018-spr-proj | train | 0 | |
37d91390669a14c6f245955cddd5b48539f25b5f | [
"self.base_widget = base_widget\nself.tab_base_widget = tab_base_widget\nself.project = project\nself.xml_root = self.project.find(manager_node_path)\nif self.xml_root is None:\n raise LookupError('The given manager node \"%s\" is not in the project XML' % manager_node_path)\nself.tab_widgets = []\nself.xml_cont... | <|body_start_0|>
self.base_widget = base_widget
self.tab_base_widget = tab_base_widget
self.project = project
self.xml_root = self.project.find(manager_node_path)
if self.xml_root is None:
raise LookupError('The given manager node "%s" is not in the project XML' % man... | Handler for a group of UI elements with a XMLController as the center piece | AbstractManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractManager:
"""Handler for a group of UI elements with a XMLController as the center piece"""
def __init__(self, base_widget, tab_base_widget, project, manager_node_path):
"""@param base_widget (QWidget): Widget to place XmlController in @param tab_base_widget (QTabWidget): TabW... | stack_v2_sparse_classes_36k_train_033740 | 2,465 | no_license | [
{
"docstring": "@param base_widget (QWidget): Widget to place XmlController in @param tab_base_widget (QTabWidget): TabWidget to place gui elements (tabs) @param project (OpusProject): currently opened project @param manager_node_path (String): name of the top level node to manage",
"name": "__init__",
... | 4 | null | Implement the Python class `AbstractManager` described below.
Class description:
Handler for a group of UI elements with a XMLController as the center piece
Method signatures and docstrings:
- def __init__(self, base_widget, tab_base_widget, project, manager_node_path): @param base_widget (QWidget): Widget to place X... | Implement the Python class `AbstractManager` described below.
Class description:
Handler for a group of UI elements with a XMLController as the center piece
Method signatures and docstrings:
- def __init__(self, base_widget, tab_base_widget, project, manager_node_path): @param base_widget (QWidget): Widget to place X... | c392d15b35aa1d47bbc185ed76314f8e6dd9f92f | <|skeleton|>
class AbstractManager:
"""Handler for a group of UI elements with a XMLController as the center piece"""
def __init__(self, base_widget, tab_base_widget, project, manager_node_path):
"""@param base_widget (QWidget): Widget to place XmlController in @param tab_base_widget (QTabWidget): TabW... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractManager:
"""Handler for a group of UI elements with a XMLController as the center piece"""
def __init__(self, base_widget, tab_base_widget, project, manager_node_path):
"""@param base_widget (QWidget): Widget to place XmlController in @param tab_base_widget (QTabWidget): TabWidget to plac... | the_stack_v2_python_sparse | opus_gui/abstract_manager/abstract_manager.py | psrc/urbansim | train | 4 |
8f2d20b264f65bbcff282625aa4c42d9052d82ab | [
"request = self.context['request']\ntry:\n Follow.objects.get(follower=request.user, followed=self.context['user'], status=3)\nexcept Follow.DoesNotExist:\n return data\nraise serializers.ValidationError('You already send a follow request to this user')",
"followed = self.context['user']\ncode = uuid.uuid4(... | <|body_start_0|>
request = self.context['request']
try:
Follow.objects.get(follower=request.user, followed=self.context['user'], status=3)
except Follow.DoesNotExist:
return data
raise serializers.ValidationError('You already send a follow request to this user')
<... | Handle follow request creation. | FollowCreateSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowCreateSerializer:
"""Handle follow request creation."""
def validate(self, data):
"""Validate if there is already a follow request in status 'Waiting'."""
<|body_0|>
def create(self, data):
"""Handle creation."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_033741 | 4,291 | no_license | [
{
"docstring": "Validate if there is already a follow request in status 'Waiting'.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Handle creation.",
"name": "create",
"signature": "def create(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013068 | Implement the Python class `FollowCreateSerializer` described below.
Class description:
Handle follow request creation.
Method signatures and docstrings:
- def validate(self, data): Validate if there is already a follow request in status 'Waiting'.
- def create(self, data): Handle creation. | Implement the Python class `FollowCreateSerializer` described below.
Class description:
Handle follow request creation.
Method signatures and docstrings:
- def validate(self, data): Validate if there is already a follow request in status 'Waiting'.
- def create(self, data): Handle creation.
<|skeleton|>
class Follow... | e2f4557e2a85405838c6c9f65f1cb8a5f60a35ba | <|skeleton|>
class FollowCreateSerializer:
"""Handle follow request creation."""
def validate(self, data):
"""Validate if there is already a follow request in status 'Waiting'."""
<|body_0|>
def create(self, data):
"""Handle creation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowCreateSerializer:
"""Handle follow request creation."""
def validate(self, data):
"""Validate if there is already a follow request in status 'Waiting'."""
request = self.context['request']
try:
Follow.objects.get(follower=request.user, followed=self.context['user... | the_stack_v2_python_sparse | apps/users/serializers/follow.py | HebertFerrer/WebMaster-back-end | train | 0 |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\ngrad = adm.get_grading_by_id(grading_id)\nprint(grad)\nreturn grad",
"adm = ProjectAdministration()\ngrad = adm.get_grading_by_id(grading_id)\nif grad is not None:\n adm.delete_grading(grad)\n return ('gelöscht', 200)\nelse:\n return ('There was some error', 500)"
] | <|body_start_0|>
adm = ProjectAdministration()
grad = adm.get_grading_by_id(grading_id)
print(grad)
return grad
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
grad = adm.get_grading_by_id(grading_id)
if grad is not None:
adm.delete_grad... | GradingOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradingOperations:
def get(self, grading_id):
"""Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, grading_id):
"""Löschen eines bestimmten Grading-Objektes, welches durch die grading_id ... | stack_v2_sparse_classes_36k_train_033742 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, grading_id)"
},
{
"docstring": "Löschen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird.",
... | 2 | stack_v2_sparse_classes_30k_train_002472 | Implement the Python class `GradingOperations` described below.
Class description:
Implement the GradingOperations class.
Method signatures and docstrings:
- def get(self, grading_id): Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird.
- def delete(self, grading_id): Lö... | Implement the Python class `GradingOperations` described below.
Class description:
Implement the GradingOperations class.
Method signatures and docstrings:
- def get(self, grading_id): Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird.
- def delete(self, grading_id): Lö... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class GradingOperations:
def get(self, grading_id):
"""Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, grading_id):
"""Löschen eines bestimmten Grading-Objektes, welches durch die grading_id ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradingOperations:
def get(self, grading_id):
"""Auslesen eines bestimmten Grading-Objektes, welches durch die grading_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
grad = adm.get_grading_by_id(grading_id)
print(grad)
return grad
def delete(self, gr... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
63cbf8f1082846599d65faf5aabfe3207033e2a2 | [
"filters_serializer = UserFilterSerializer(data=request.query_params)\nfilters_serializer.is_valid(raise_exception=True)\nusers = UserService.get_users(filters=filters_serializer.validated_data)\nreturn get_paginated_response(pagination_class=HeaderLimitOffsetPagination, serializer_class=UserSerializer, queryset=us... | <|body_start_0|>
filters_serializer = UserFilterSerializer(data=request.query_params)
filters_serializer.is_valid(raise_exception=True)
users = UserService.get_users(filters=filters_serializer.validated_data)
return get_paginated_response(pagination_class=HeaderLimitOffsetPagination, ser... | UserViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
def list(self, request: Request) -> Response:
"""List all :class:`User`\\s"""
<|body_0|>
def retrieve(self, request: Request, user_id: Union[str, UUID]) -> Response:
"""Retrieve a specific :class:`User` based on it's ID :param user_id: The ID of the :cla... | stack_v2_sparse_classes_36k_train_033743 | 7,007 | no_license | [
{
"docstring": "List all :class:`User`\\\\s",
"name": "list",
"signature": "def list(self, request: Request) -> Response"
},
{
"docstring": "Retrieve a specific :class:`User` based on it's ID :param user_id: The ID of the :class:`User` to retrieve",
"name": "retrieve",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000305 | Implement the Python class `UserViewSet` described below.
Class description:
Implement the UserViewSet class.
Method signatures and docstrings:
- def list(self, request: Request) -> Response: List all :class:`User`\\s
- def retrieve(self, request: Request, user_id: Union[str, UUID]) -> Response: Retrieve a specific :... | Implement the Python class `UserViewSet` described below.
Class description:
Implement the UserViewSet class.
Method signatures and docstrings:
- def list(self, request: Request) -> Response: List all :class:`User`\\s
- def retrieve(self, request: Request, user_id: Union[str, UUID]) -> Response: Retrieve a specific :... | 3ae560565ae9ce7598a94fed4f7828f3c1675a35 | <|skeleton|>
class UserViewSet:
def list(self, request: Request) -> Response:
"""List all :class:`User`\\s"""
<|body_0|>
def retrieve(self, request: Request, user_id: Union[str, UUID]) -> Response:
"""Retrieve a specific :class:`User` based on it's ID :param user_id: The ID of the :cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserViewSet:
def list(self, request: Request) -> Response:
"""List all :class:`User`\\s"""
filters_serializer = UserFilterSerializer(data=request.query_params)
filters_serializer.is_valid(raise_exception=True)
users = UserService.get_users(filters=filters_serializer.validated_d... | the_stack_v2_python_sparse | leaderboard/apis/rest_api.py | DurzoB5/Photocrowd-TT | train | 0 | |
f6a2d4ef95c0345b2b75a984cfd91cf6ad9c2d3b | [
"length_a = len(A)\nlength_b = len(B)\nif length_a >= length_b:\n repeat = 1\nelse:\n repeat = int(length_b / length_a)\nmax_repeat = len(B) / len(A) + 3\ns = A * repeat\nwhile repeat < max_repeat:\n if s.find(B) >= 0:\n return repeat\n s += A\n repeat += 1\nreturn -1",
"if not B or A.find(B... | <|body_start_0|>
length_a = len(A)
length_b = len(B)
if length_a >= length_b:
repeat = 1
else:
repeat = int(length_b / length_a)
max_repeat = len(B) / len(A) + 3
s = A * repeat
while repeat < max_repeat:
if s.find(B) >= 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def repeatedStringMatch1(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_0|>
def repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length_a = len(A)
... | stack_v2_sparse_classes_36k_train_033744 | 1,356 | no_license | [
{
"docstring": ":type A: str :type B: str :rtype: int",
"name": "repeatedStringMatch1",
"signature": "def repeatedStringMatch1(self, A, B)"
},
{
"docstring": ":type A: str :type B: str :rtype: int",
"name": "repeatedStringMatch",
"signature": "def repeatedStringMatch(self, A, B)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedStringMatch1(self, A, B): :type A: str :type B: str :rtype: int
- def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedStringMatch1(self, A, B): :type A: str :type B: str :rtype: int
- def repeatedStringMatch(self, A, B): :type A: str :type B: str :rtype: int
<|skeleton|>
class Solut... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def repeatedStringMatch1(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_0|>
def repeatedStringMatch(self, A, B):
""":type A: str :type B: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def repeatedStringMatch1(self, A, B):
""":type A: str :type B: str :rtype: int"""
length_a = len(A)
length_b = len(B)
if length_a >= length_b:
repeat = 1
else:
repeat = int(length_b / length_a)
max_repeat = len(B) / len(A) + 3
... | the_stack_v2_python_sparse | python/leetcode_bak/686_Repeated_String_Match.py | bobcaoge/my-code | train | 0 | |
b5a33f6450019fff4535086ce66fb17a23707776 | [
"context = context or {}\nids = isinstance(ids, (int, long)) and [ids] or ids\ncr_date = time.strftime('%Y-%m-%d')\nsp_brw = self.browse(cur, uid, ids[0], context=context)\nif not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_contract_expiry) or context.get('force_expiry_pic... | <|body_start_0|>
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.strftime('%Y-%m-%d')
sp_brw = self.browse(cur, uid, ids[0], context=context)
if not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_c... | StockPickingOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy... | stack_v2_sparse_classes_36k_train_033745 | 5,912 | no_license | [
{
"docstring": "overwrite the method to add a verification of the contract due date before process the stock picking out.",
"name": "action_process",
"signature": "def action_process(self, cur, uid, ids, context=None)"
},
{
"docstring": "Ovwerwrite the copy method to also copy the date_contract_... | 2 | null | Implement the Python class `StockPickingOut` described below.
Class description:
Implement the StockPickingOut class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking out.
- d... | Implement the Python class `StockPickingOut` described below.
Class description:
Implement the StockPickingOut class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking out.
- d... | 511dc410b4eba1f8ea939c6af02a5adea5122c92 | <|skeleton|>
class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockPickingOut:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking out."""
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.str... | the_stack_v2_python_sparse | stock_purchase_expiry/model/stock.py | yelizariev/addons-vauxoo | train | 3 | |
902844d9636cfe7a9f505c65cfb6b86df5c5cb4b | [
"cloud = None\nprovider = config.get('provider', '')\nif provider.lower() == 'huggingface-hub':\n cloud = HuggingFaceHub(config)\nelif ObjectStorage.isprovider(provider):\n cloud = ObjectStorage(config)\nelif provider:\n cloud = CloudFactory.resolve(provider, config)\nreturn cloud",
"try:\n return Res... | <|body_start_0|>
cloud = None
provider = config.get('provider', '')
if provider.lower() == 'huggingface-hub':
cloud = HuggingFaceHub(config)
elif ObjectStorage.isprovider(provider):
cloud = ObjectStorage(config)
elif provider:
cloud = CloudFact... | Methods to create Cloud instances. | CloudFactory | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudFactory:
"""Methods to create Cloud instances."""
def create(config):
"""Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud"""
<|body_0|>
def resolve(backend, config):
"""Attempt to resolve a custom cloud backend. Args: backend: backe... | stack_v2_sparse_classes_36k_train_033746 | 1,544 | permissive | [
{
"docstring": "Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud",
"name": "create",
"signature": "def create(config)"
},
{
"docstring": "Attempt to resolve a custom cloud backend. Args: backend: backend class config: configuration parameters Returns: Cloud",
"name"... | 2 | null | Implement the Python class `CloudFactory` described below.
Class description:
Methods to create Cloud instances.
Method signatures and docstrings:
- def create(config): Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud
- def resolve(backend, config): Attempt to resolve a custom cloud backend.... | Implement the Python class `CloudFactory` described below.
Class description:
Methods to create Cloud instances.
Method signatures and docstrings:
- def create(config): Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud
- def resolve(backend, config): Attempt to resolve a custom cloud backend.... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class CloudFactory:
"""Methods to create Cloud instances."""
def create(config):
"""Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud"""
<|body_0|>
def resolve(backend, config):
"""Attempt to resolve a custom cloud backend. Args: backend: backe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudFactory:
"""Methods to create Cloud instances."""
def create(config):
"""Creates a Cloud instance. Args: config: cloud configuration Returns: Cloud"""
cloud = None
provider = config.get('provider', '')
if provider.lower() == 'huggingface-hub':
cloud = Hugg... | the_stack_v2_python_sparse | src/python/txtai/cloud/factory.py | neuml/txtai | train | 4,804 |
82fc4222c0d4381535838144c223da85e5d35c2a | [
"if len(nums) < 2:\n return 0\ntotal_moves = 0\nwhile not self.all_equal(nums):\n max_value = max(nums)\n min_value = min(nums)\n steps = max_value - min_value\n max_index = nums.index(max_value)\n self.add_steps_to_rest(nums, max_index, steps)\n total_moves += steps\nreturn total_moves",
"if... | <|body_start_0|>
if len(nums) < 2:
return 0
total_moves = 0
while not self.all_equal(nums):
max_value = max(nums)
min_value = min(nums)
steps = max_value - min_value
max_index = nums.index(max_value)
self.add_steps_to_rest(n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMoves(self, nums):
""":type: List[int] :rtype: int"""
<|body_0|>
def all_equal(self, nums):
"""Whether the element in a list are all equal to each other"""
<|body_1|>
def add_steps_to_rest(self, nums, index, steps):
"""Add a spec... | stack_v2_sparse_classes_36k_train_033747 | 1,696 | no_license | [
{
"docstring": ":type: List[int] :rtype: int",
"name": "minMoves",
"signature": "def minMoves(self, nums)"
},
{
"docstring": "Whether the element in a list are all equal to each other",
"name": "all_equal",
"signature": "def all_equal(self, nums)"
},
{
"docstring": "Add a specifi... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMoves(self, nums): :type: List[int] :rtype: int
- def all_equal(self, nums): Whether the element in a list are all equal to each other
- def add_steps_to_rest(self, nums, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMoves(self, nums): :type: List[int] :rtype: int
- def all_equal(self, nums): Whether the element in a list are all equal to each other
- def add_steps_to_rest(self, nums, ... | ecbb8fb7f96f644c16dbb0cf7ffb69bc959a5647 | <|skeleton|>
class Solution:
def minMoves(self, nums):
""":type: List[int] :rtype: int"""
<|body_0|>
def all_equal(self, nums):
"""Whether the element in a list are all equal to each other"""
<|body_1|>
def add_steps_to_rest(self, nums, index, steps):
"""Add a spec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMoves(self, nums):
""":type: List[int] :rtype: int"""
if len(nums) < 2:
return 0
total_moves = 0
while not self.all_equal(nums):
max_value = max(nums)
min_value = min(nums)
steps = max_value - min_value
... | the_stack_v2_python_sparse | source_code/453_MinimumMovesToEqualArrayElements.py | CircleZ3791117/CodingPractice | train | 14 | |
82722ff32f77bf2872f6301ce00d2058335e4baf | [
"super().__init__(name=name)\nself._vocab_size = vocab_size\nself._emb_dim = emb_dim\nself._num_layers = num_layers\nself._num_heads = num_heads\nself._dropout_prob = dropout_prob\nself._dropout_attn_prob = dropout_attn_prob\nself._self_att_init_scale = self_att_init_scale\nself._dense_init_scale = dense_init_scale... | <|body_start_0|>
super().__init__(name=name)
self._vocab_size = vocab_size
self._emb_dim = emb_dim
self._num_layers = num_layers
self._num_heads = num_heads
self._dropout_prob = dropout_prob
self._dropout_attn_prob = dropout_attn_prob
self._self_att_init_s... | TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf | TransformerXL | [
"CC-BY-SA-4.0",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerXL:
"""TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf"""
def __init__(self, vocab_size: int=256, emb_dim: int=256, num_layers: int=10, num_heads: int=8, d... | stack_v2_sparse_classes_36k_train_033748 | 19,199 | permissive | [
{
"docstring": "Initialize a TransformerXL. Args: vocab_size: the size of the vocabulary. emb_dim: the dimensionality of the embeddings. num_layers: number of transformer blocks. num_heads: number of attention heads. dropout_prob: dropout probability. dropout_attn_prob: dropout probability of the attention modu... | 3 | null | Implement the Python class `TransformerXL` described below.
Class description:
TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf
Method signatures and docstrings:
- def __init__(self, vocab_size... | Implement the Python class `TransformerXL` described below.
Class description:
TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf
Method signatures and docstrings:
- def __init__(self, vocab_size... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class TransformerXL:
"""TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf"""
def __init__(self, vocab_size: int=256, emb_dim: int=256, num_layers: int=10, num_heads: int=8, d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerXL:
"""TransformerXL language model with memory using GPT2 blocks. TransformerXL: https://arxiv.org/abs/1901.02860 GPT-2: http://www.persagen.com/files/misc/radford2019language.pdf"""
def __init__(self, vocab_size: int=256, emb_dim: int=256, num_layers: int=10, num_heads: int=8, dropout_prob: ... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/transformer.py | sethuramanio/deepmind-research | train | 1 |
8d260b0f6e202061a402873f52dfb1d01800bac8 | [
"super(MixtureOfExpert, self).__init__()\nself.experts = nn.ModuleList(experts)\nself.gate = gate\nself.softmax = nn.Softmax(dim=-1)\nself.return_mixture = return_mixture",
"expert_scores = self.softmax(self.gate(input))\nexpert_outputs = torch.stack([expert(input) for expert in self.experts], dim=-1)\nexpert_sco... | <|body_start_0|>
super(MixtureOfExpert, self).__init__()
self.experts = nn.ModuleList(experts)
self.gate = gate
self.softmax = nn.Softmax(dim=-1)
self.return_mixture = return_mixture
<|end_body_0|>
<|body_start_1|>
expert_scores = self.softmax(self.gate(input))
e... | MixtureOfExpert | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixtureOfExpert:
def __init__(self, experts: List[Module], gate: Module, return_mixture: bool=True):
""":param experts: list of separate expert networks. Each must take the same input and return output of same dimensionality :param gate: take the input and output (un-normalized) score fo... | stack_v2_sparse_classes_36k_train_033749 | 2,746 | permissive | [
{
"docstring": ":param experts: list of separate expert networks. Each must take the same input and return output of same dimensionality :param gate: take the input and output (un-normalized) score for each expert",
"name": "__init__",
"signature": "def __init__(self, experts: List[Module], gate: Module... | 2 | null | Implement the Python class `MixtureOfExpert` described below.
Class description:
Implement the MixtureOfExpert class.
Method signatures and docstrings:
- def __init__(self, experts: List[Module], gate: Module, return_mixture: bool=True): :param experts: list of separate expert networks. Each must take the same input ... | Implement the Python class `MixtureOfExpert` described below.
Class description:
Implement the MixtureOfExpert class.
Method signatures and docstrings:
- def __init__(self, experts: List[Module], gate: Module, return_mixture: bool=True): :param experts: list of separate expert networks. Each must take the same input ... | 689b9924d3c88a433f8f350b89c13a878ac7d7c3 | <|skeleton|>
class MixtureOfExpert:
def __init__(self, experts: List[Module], gate: Module, return_mixture: bool=True):
""":param experts: list of separate expert networks. Each must take the same input and return output of same dimensionality :param gate: take the input and output (un-normalized) score fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixtureOfExpert:
def __init__(self, experts: List[Module], gate: Module, return_mixture: bool=True):
""":param experts: list of separate expert networks. Each must take the same input and return output of same dimensionality :param gate: take the input and output (un-normalized) score for each expert"... | the_stack_v2_python_sparse | nntoolbox/components/mixture.py | nhatsmrt/nn-toolbox | train | 19 | |
a838a9a0e52cd87af618e4aa71c10bfd0a6fe197 | [
"def helper(nums1, nums2, k):\n if len(nums1) < len(nums2):\n nums1, nums2 = (nums2, nums1)\n if len(nums2) == 0:\n return nums1[k - 1]\n if k == 1:\n return min(nums1[0], nums2[0])\n t = min(k // 2, len(nums2))\n if nums1[t - 1] >= nums2[t - 1]:\n return helper(nums1, num... | <|body_start_0|>
def helper(nums1, nums2, k):
if len(nums1) < len(nums2):
nums1, nums2 = (nums2, nums1)
if len(nums2) == 0:
return nums1[k - 1]
if k == 1:
return min(nums1[0], nums2[0])
t = min(k // 2, len(nums2))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_033750 | 2,401 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
... | 2 | stack_v2_sparse_classes_30k_train_008480 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[in... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
def helper(nums1, nums2, k):
if len(nums1) < len(nums2):
nums1, nums2 = (nums2, nums1)
if len(nums2) == 0:
return ... | the_stack_v2_python_sparse | 0004_Median_of_Two_Sorted_Arrays.py | bingli8802/leetcode | train | 0 | |
09a1b6c560f856e1d686ae30b19f01eb21edce10 | [
"painter = QPainter(self.outPixmap())\npainter.drawPixmap(QPoint(0, 0), self.startPixmap())\nreturn (0.0, 1.0)",
"out = self.outPixmap()\npainter = QPainter(out)\npainter.eraseRect(0, 0, out.width(), out.height())\npainter.setOpacity(1.0 - alpha)\npainter.drawPixmap(QPoint(0, 0), self.startPixmap())\npainter.setO... | <|body_start_0|>
painter = QPainter(self.outPixmap())
painter.drawPixmap(QPoint(0, 0), self.startPixmap())
return (0.0, 1.0)
<|end_body_0|>
<|body_start_1|>
out = self.outPixmap()
painter = QPainter(out)
painter.eraseRect(0, 0, out.width(), out.height())
painter.... | A QPixmapTransition which animates using a cross fade effect. | QCrossFadeTransition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appro... | stack_v2_sparse_classes_36k_train_033751 | 14,565 | permissive | [
{
"docstring": "Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appropriate alpha blending value.",
"name": "preparePixmap",
"signature": "def preparePixmap(self)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_005769 | Implement the Python class `QCrossFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a cross fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The t... | Implement the Python class `QCrossFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a cross fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The t... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appropriate alpha ... | the_stack_v2_python_sparse | enaml/qt/q_pixmap_transition.py | MatthieuDartiailh/enaml | train | 26 |
0f8fd507dfdf72e0b39d2804636754342c615c6c | [
"self.id = id\nself.name = name\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nself.updated_at = APIHelper.RFC3339DateTime(updated_at) if updated_at else None\nself.is_active = is_active\nself.additional_properties = additional_properties",
"if dictionary is None:\n return No... | <|body_start_0|>
self.id = id
self.name = name
self.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None
self.updated_at = APIHelper.RFC3339DateTime(updated_at) if updated_at else None
self.is_active = is_active
self.additional_properties = additiona... | Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at (datetime): TODO: type description here. is_active (bool): TODO: type description... | LanguageSetDTO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageSetDTO:
"""Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at (datetime): TODO: type description here... | stack_v2_sparse_classes_36k_train_033752 | 3,024 | permissive | [
{
"docstring": "Constructor for the LanguageSetDTO class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, created_at=None, updated_at=None, is_active=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary... | 2 | null | Implement the Python class `LanguageSetDTO` described below.
Class description:
Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at ... | Implement the Python class `LanguageSetDTO` described below.
Class description:
Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class LanguageSetDTO:
"""Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at (datetime): TODO: type description here... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageSetDTO:
"""Implementation of the 'LanguageSetDTO' model. TODO: type model description here. Attributes: id (int): TODO: type description here. name (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at (datetime): TODO: type description here. is_active (... | the_stack_v2_python_sparse | idfy_rest_client/models/language_set_dto.py | dealflowteam/Idfy | train | 0 |
c85e8a4b25b2ce3804ea63c29b901eca08782576 | [
"if not heights:\n return 0\nstack = []\nmax_area = heights[0]\nstack.append([0, heights[0]])\nfor i, height in enumerate(heights[1:]):\n a = i + 1\n if height > stack[-1][-1]:\n stack.append([a, height])\n else:\n while stack and stack[-1][-1] >= height:\n b = stack.pop()\n ... | <|body_start_0|>
if not heights:
return 0
stack = []
max_area = heights[0]
stack.append([0, heights[0]])
for i, height in enumerate(heights[1:]):
a = i + 1
if height > stack[-1][-1]:
stack.append([a, height])
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int 82ms"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int 179ms"""
<|body_1|>
def maximalRectangle_1(self, matrix):
... | stack_v2_sparse_classes_36k_train_033753 | 2,591 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int 82ms",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int 179ms",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, mat... | 3 | stack_v2_sparse_classes_30k_train_010383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int 82ms
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int 179ms
- def max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int 82ms
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int 179ms
- def max... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int 82ms"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int 179ms"""
<|body_1|>
def maximalRectangle_1(self, matrix):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int 82ms"""
if not heights:
return 0
stack = []
max_area = heights[0]
stack.append([0, heights[0]])
for i, height in enumerate(heights[1:]):
a = i + 1
... | the_stack_v2_python_sparse | MaximalRectangle_HARD_85.py | 953250587/leetcode-python | train | 2 | |
b3f328e9b5fa748ca55698d1eaeb8e3a9805cb0c | [
"if heading_key > 0:\n return Heading.blogheadings.single_blog_heading(heading_key)\nreturn None",
"try:\n if number_of_days > 0:\n return Heading.blogheadings.get_headings_by_number_of_days(number_of_days)\n else:\n raise InvalidNumberOfDaysError('Number of days must greater than 0', statu... | <|body_start_0|>
if heading_key > 0:
return Heading.blogheadings.single_blog_heading(heading_key)
return None
<|end_body_0|>
<|body_start_1|>
try:
if number_of_days > 0:
return Heading.blogheadings.get_headings_by_number_of_days(number_of_days)
... | Class holds all logic that handles all Heading related information processing operations. | HeadingDataService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeadingDataService:
"""Class holds all logic that handles all Heading related information processing operations."""
def get_heading(self, heading_key: int) -> Heading:
"""Function returns a heading model instance. params: heading_key - heading model id."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_033754 | 4,675 | no_license | [
{
"docstring": "Function returns a heading model instance. params: heading_key - heading model id.",
"name": "get_heading",
"signature": "def get_heading(self, heading_key: int) -> Heading"
},
{
"docstring": "Function returns a queryset of headings delimited by the number_of_days parameter. para... | 5 | stack_v2_sparse_classes_30k_train_011049 | Implement the Python class `HeadingDataService` described below.
Class description:
Class holds all logic that handles all Heading related information processing operations.
Method signatures and docstrings:
- def get_heading(self, heading_key: int) -> Heading: Function returns a heading model instance. params: headi... | Implement the Python class `HeadingDataService` described below.
Class description:
Class holds all logic that handles all Heading related information processing operations.
Method signatures and docstrings:
- def get_heading(self, heading_key: int) -> Heading: Function returns a heading model instance. params: headi... | c08131f1722f2f5b5054cadf6f632d2c18623ecf | <|skeleton|>
class HeadingDataService:
"""Class holds all logic that handles all Heading related information processing operations."""
def get_heading(self, heading_key: int) -> Heading:
"""Function returns a heading model instance. params: heading_key - heading model id."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeadingDataService:
"""Class holds all logic that handles all Heading related information processing operations."""
def get_heading(self, heading_key: int) -> Heading:
"""Function returns a heading model instance. params: heading_key - heading model id."""
if heading_key > 0:
... | the_stack_v2_python_sparse | ENV/root/backend/services/blogservices/dataservices/headingdataservice.py | AcePro-Engineer/JBBlogsv2 | train | 0 |
1dbaa73d1cca7bcb0c64d9eb3fab062abce6113d | [
"for param in params:\n if param not in self.__info__['space']:\n print('Error: not supported parameters {}'.format(param))\nif self.dataset_type == PROBLEM.CLASSIFICATION:\n model = KNeighborsClassifier(n_neighbors=int(params['Num neighbors']), algorithm=params['Algorithm'], p=int(params['Minkowski po... | <|body_start_0|>
for param in params:
if param not in self.__info__['space']:
print('Error: not supported parameters {}'.format(param))
if self.dataset_type == PROBLEM.CLASSIFICATION:
model = KNeighborsClassifier(n_neighbors=int(params['Num neighbors']), algorithm... | Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2) | KNeighbors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params... | stack_v2_sparse_classes_36k_train_033755 | 3,557 | no_license | [
{
"docstring": "Train the model with the given hyper-parameters. Args: :param params: dictionary of hyper-parameters. :return: trained model.",
"name": "train",
"signature": "def train(self, params)"
},
{
"docstring": "Classify the test set of the chosen dataset and produce the result correspond... | 2 | stack_v2_sparse_classes_30k_train_013722 | Implement the Python class `KNeighbors` described below.
Class description:
Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=... | Implement the Python class `KNeighbors` described below.
Class description:
Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=... | 27f861c09615aedfd96cffdebf7d9653f72b4d7b | <|skeleton|>
class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNeighbors:
"""Parameter accepted: - n_neighbors: integer number of nearest neighbors (K). - algorithm: algorithm used to compute the neighbors ('auto', 'ball_tree', 'kd_tree' and 'brute') - dist_power: power parameter for the minkowski metric (p=1 -> L1, P=2 -> L2)"""
def train(self, params):
""... | the_stack_v2_python_sparse | API/Metrics/KNeighbors.py | AndreaCorsini1/Ahmet | train | 1 |
1f8a744a0c5495ded77df7737fd33081dcbf90e7 | [
"filing_effective_date = filing_effective_date.replace(tzinfo=None)\nregistrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.strptime(x['endDate'], '%Y-%m-... | <|body_start_0|>
filing_effective_date = filing_effective_date.replace(tzinfo=None)
registrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.str... | Utility to get the relevant registrar info for a filing. | RegistrarInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
<|body_0|>
def encode_registrar_signature(signature_image) -> str:
"""Return the encoded ... | stack_v2_sparse_classes_36k_train_033756 | 3,514 | permissive | [
{
"docstring": "Return the registrar for a filing.",
"name": "get_registrar_info",
"signature": "def get_registrar_info(filing_effective_date) -> dict"
},
{
"docstring": "Return the encoded registrar signature.",
"name": "encode_registrar_signature",
"signature": "def encode_registrar_si... | 2 | stack_v2_sparse_classes_30k_train_017925 | Implement the Python class `RegistrarInfo` described below.
Class description:
Utility to get the relevant registrar info for a filing.
Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str... | Implement the Python class `RegistrarInfo` described below.
Class description:
Utility to get the relevant registrar info for a filing.
Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
<|body_0|>
def encode_registrar_signature(signature_image) -> str:
"""Return the encoded ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrarInfo:
"""Utility to get the relevant registrar info for a filing."""
def get_registrar_info(filing_effective_date) -> dict:
"""Return the registrar for a filing."""
filing_effective_date = filing_effective_date.replace(tzinfo=None)
registrar = [x for x in RegistrarInfo.re... | the_stack_v2_python_sparse | legal-api/src/legal_api/reports/registrar_meta.py | bcgov/lear | train | 13 |
0234f27a9dd6278123abd331b1b4c8321114316f | [
"self.integ_uplimit = integ_uplimit\nself.integ_dowlimit = integ_dowlimit\nself.func = func",
"t_seq1 = np.zeros(5, 'f')\ns_seq2 = np.zeros(4, 'f')\nc_seq3 = np.zeros(3, 'f')\nr_seq4 = np.zeros(2, 'f')\nprint(r_seq4)\nhm = [(self.integ_uplimit - self.integ_dowlimit) / 2 ** i for i in range(0, 4)]\nt0 = 1 / 2 * (s... | <|body_start_0|>
self.integ_uplimit = integ_uplimit
self.integ_dowlimit = integ_dowlimit
self.func = func
<|end_body_0|>
<|body_start_1|>
t_seq1 = np.zeros(5, 'f')
s_seq2 = np.zeros(4, 'f')
c_seq3 = np.zeros(3, 'f')
r_seq4 = np.zeros(2, 'f')
print(r_seq4)... | Romberg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Romberg:
def __init__(self, integ_uplimit, integ_dowlimit, func):
"""初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分"""
<|body_0|>
def calc(self):
"""计算Richardson外推算法的四个序列"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.integ_uplim... | stack_v2_sparse_classes_36k_train_033757 | 1,677 | no_license | [
{
"docstring": "初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分",
"name": "__init__",
"signature": "def __init__(self, integ_uplimit, integ_dowlimit, func)"
},
{
"docstring": "计算Richardson外推算法的四个序列",
"name": "calc",
"signature": "def calc(self)"
}
] | 2 | null | Implement the Python class `Romberg` described below.
Class description:
Implement the Romberg class.
Method signatures and docstrings:
- def __init__(self, integ_uplimit, integ_dowlimit, func): 初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分
- def calc(self): 计算Richardson外推算法的四个序列 | Implement the Python class `Romberg` described below.
Class description:
Implement the Romberg class.
Method signatures and docstrings:
- def __init__(self, integ_uplimit, integ_dowlimit, func): 初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分
- def calc(self): 计算Richardson外推算法的四个序列
<|skeleton|>
class Ro... | cc3cf0a1411d850e7b4ba75952fe0a5270b17565 | <|skeleton|>
class Romberg:
def __init__(self, integ_uplimit, integ_dowlimit, func):
"""初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分"""
<|body_0|>
def calc(self):
"""计算Richardson外推算法的四个序列"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Romberg:
def __init__(self, integ_uplimit, integ_dowlimit, func):
"""初始化积分上限integ_uplimit和积分下限integ_dowlimit 输入一个函数,输出函数在积分上下限的积分"""
self.integ_uplimit = integ_uplimit
self.integ_dowlimit = integ_dowlimit
self.func = func
def calc(self):
"""计算Richardson外推算法的四个序列"""... | the_stack_v2_python_sparse | python基础代码/Romberg.py | winynfuck/PYdemo | train | 0 | |
183370fde921c6500c31865d9ff4823138b107f8 | [
"args = dict(is_add=True, locator_set_name=name, locator_num=0, locators=[])\ncmd = u'lisp_add_del_locator_set'\nerr_msg = f\"Failed to add locator set on host {node[u'host']}\"\nwith PapiSocketExecutor(node) as papi_exec:\n papi_exec.add(cmd, **args).get_reply(err_msg)",
"args = dict(is_add=False, locator_set... | <|body_start_0|>
args = dict(is_add=True, locator_set_name=name, locator_num=0, locators=[])
cmd = u'lisp_add_del_locator_set'
err_msg = f"Failed to add locator set on host {node[u'host']}"
with PapiSocketExecutor(node) as papi_exec:
papi_exec.add(cmd, **args).get_reply(err_m... | Class for Lisp Locator Set API. | LispLocatorSet | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
<|body_0|>
def vpp_del_lisp_locator_set(node, name):
... | stack_v2_sparse_classes_36k_train_033758 | 14,690 | permissive | [
{
"docstring": "Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str",
"name": "vpp_add_lisp_locator_set",
"signature": "def vpp_add_lisp_locator_set(node, name)"
},
{
"docstring": "Del lisp locator_set on VPP. :param node: VPP node.... | 2 | stack_v2_sparse_classes_30k_train_000308 | Implement the Python class `LispLocatorSet` described below.
Class description:
Class for Lisp Locator Set API.
Method signatures and docstrings:
- def vpp_add_lisp_locator_set(node, name): Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str
- def vpp_de... | Implement the Python class `LispLocatorSet` described below.
Class description:
Class for Lisp Locator Set API.
Method signatures and docstrings:
- def vpp_add_lisp_locator_set(node, name): Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str
- def vpp_de... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
<|body_0|>
def vpp_del_lisp_locator_set(node, name):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
args = dict(is_add=True, locator_set_name=name, locator_num=0, locators... | the_stack_v2_python_sparse | resources/libraries/python/LispSetup.py | FDio/csit | train | 28 |
66f4852fd4f4ffadd33f36f25760bfa23338c89c | [
"sketch = Sketch.query.get_with_acl(sketch_id)\nif not sketch:\n abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')\nquestion = InvestigativeQuestion.query.get(question_id)\nif not question:\n abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question found with this ID')\nconclusions = InvestigativeQuesti... | <|body_start_0|>
sketch = Sketch.query.get_with_acl(sketch_id)
if not sketch:
abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID')
question = InvestigativeQuestion.query.get(question_id)
if not question:
abort(HTTP_STATUS_CODE_NOT_FOUND, 'No question ... | Resource for investigative question conclusion. | QuestionConclusionListResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionConclusionListResource:
"""Resource for investigative question conclusion."""
def get(self, sketch_id, question_id):
"""Handles GET request to the resource. Returns: A list of JSON representations of the conclusions."""
<|body_0|>
def post(self, sketch_id, questi... | stack_v2_sparse_classes_36k_train_033759 | 15,391 | permissive | [
{
"docstring": "Handles GET request to the resource. Returns: A list of JSON representations of the conclusions.",
"name": "get",
"signature": "def get(self, sketch_id, question_id)"
},
{
"docstring": "Handles POST request to the resource. Adds or edits a conclusion. Returns: A JSON representati... | 2 | stack_v2_sparse_classes_30k_train_003801 | Implement the Python class `QuestionConclusionListResource` described below.
Class description:
Resource for investigative question conclusion.
Method signatures and docstrings:
- def get(self, sketch_id, question_id): Handles GET request to the resource. Returns: A list of JSON representations of the conclusions.
- ... | Implement the Python class `QuestionConclusionListResource` described below.
Class description:
Resource for investigative question conclusion.
Method signatures and docstrings:
- def get(self, sketch_id, question_id): Handles GET request to the resource. Returns: A list of JSON representations of the conclusions.
- ... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class QuestionConclusionListResource:
"""Resource for investigative question conclusion."""
def get(self, sketch_id, question_id):
"""Handles GET request to the resource. Returns: A list of JSON representations of the conclusions."""
<|body_0|>
def post(self, sketch_id, questi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionConclusionListResource:
"""Resource for investigative question conclusion."""
def get(self, sketch_id, question_id):
"""Handles GET request to the resource. Returns: A list of JSON representations of the conclusions."""
sketch = Sketch.query.get_with_acl(sketch_id)
if not ... | the_stack_v2_python_sparse | timesketch/api/v1/resources/scenarios.py | google/timesketch | train | 2,263 |
e9d5f911db466574d83bbbdff41d017b178f8281 | [
"if not isinstance(translation_range, (list, tuple)) or len(translation_range) != 2:\n raise ValueError('shear_range argument must be list/tuple with two values!')\nself.translation_range = translation_range\nself.reference = reference\nself.lazy = lazy",
"translation_x = random.gauss(self.translation_range[0]... | <|body_start_0|>
if not isinstance(translation_range, (list, tuple)) or len(translation_range) != 2:
raise ValueError('shear_range argument must be list/tuple with two values!')
self.translation_range = translation_range
self.reference = reference
self.lazy = lazy
<|end_body_... | Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. | RandomTranslate2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomTranslate2D:
"""Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, translation_... | stack_v2_sparse_classes_36k_train_033760 | 21,674 | permissive | [
{
"docstring": "Initialize a RandomTranslate2D object Arguments --------- translation_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. translation_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (option... | 2 | null | Implement the Python class `RandomTranslate2D` described below.
Class description:
Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
... | Implement the Python class `RandomTranslate2D` described below.
Class description:
Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class RandomTranslate2D:
"""Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, translation_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomTranslate2D:
"""Apply a Translate2D transform to an image, but with the parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, translation_range, refere... | the_stack_v2_python_sparse | ants/contrib/sampling/affine2d.py | ANTsX/ANTsPy | train | 483 |
0ab478141249279c398718e0b7c15a11d98d35f6 | [
"if not email:\n raise ValueError(_('The Email must be set'))\nemail = self.normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user",
"extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_fields.set... | <|body_start_0|>
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
extra_fi... | Custom user model manager where email is the unique identifiers for authentication instead of usernames. | CustomUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_36k_train_033761 | 12,722 | permissive | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password, **extra_fields)"
},
{
"docstring": "Create and save a SuperUser with the given email and password.",
"name": "create_superuser",
"signat... | 2 | stack_v2_sparse_classes_30k_train_011588 | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | Implement the Python class `CustomUserManager` described below.
Class description:
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
Method signatures and docstrings:
- def create_user(self, email, password, **extra_fields): Create and save a User with the given ... | ed957485c14aa8831e5a119d14849ddb0e1e6ec8 | <|skeleton|>
class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
"""Custom user model manager where email is the unique identifiers for authentication instead of usernames."""
def create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueEr... | the_stack_v2_python_sparse | LAMBDA_LABS/backend-vbb-portal/vbb_backend/users/models.py | Bryan-Guner-Backup/DOWN_ARCHIVE_V2 | train | 0 |
10e8f8883cd78de109537884913911e9f3c9d758 | [
"self.followers = defaultdict(set)\nself.user_tweets = defaultdict(list)\nself.tweet_count = 0",
"if userId not in self.user_tweets:\n self.user_tweets[userId] = [(tweetId, self.tweet_count)]\nelif tweetId in self.user_tweets[userId]:\n return\nelse:\n self.user_tweets[userId].append((tweetId, self.tweet... | <|body_start_0|>
self.followers = defaultdict(set)
self.user_tweets = defaultdict(list)
self.tweet_count = 0
<|end_body_0|>
<|body_start_1|>
if userId not in self.user_tweets:
self.user_tweets[userId] = [(tweetId, self.tweet_count)]
elif tweetId in self.user_tweets[u... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_36k_train_033762 | 3,059 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 5 | stack_v2_sparse_classes_30k_val_000110 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | ecdc7f8f2ddca0d49ae043c877c184da2112497e | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.followers = defaultdict(set)
self.user_tweets = defaultdict(list)
self.tweet_count = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
if userId ... | the_stack_v2_python_sparse | leetcode/355-design-twitter.py | Knln/online-coding-judge | train | 0 | |
812da1f1a0ef90835445f1ea89070f239586dcd5 | [
"model_params = {'resnet18': {'block': ResidualBlock, 'layers': [2, 2, 2, 2]}, 'resnet34': {'block': ResidualBlock, 'layers': [3, 4, 6, 3]}, 'resnet50': {'block': BottleneckBlock, 'layers': [3, 4, 6, 3]}, 'resnet101': {'block': BottleneckBlock, 'layers': [3, 4, 23, 3]}, 'resnet152': {'block': BottleneckBlock, 'laye... | <|body_start_0|>
model_params = {'resnet18': {'block': ResidualBlock, 'layers': [2, 2, 2, 2]}, 'resnet34': {'block': ResidualBlock, 'layers': [3, 4, 6, 3]}, 'resnet50': {'block': BottleneckBlock, 'layers': [3, 4, 6, 3]}, 'resnet101': {'block': BottleneckBlock, 'layers': [3, 4, 23, 3]}, 'resnet152': {'block': Bo... | Resnet_Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resnet_Model:
def __init__(self, resnet_model, data_format='channels_last', trainable=True, finetune_bn=False, *args, **kwargs):
"""Our actual ResNet network. We return the output of c2, c3,c4,c5 N.B. batch norm is always run with trained parameters, as we use very small batches when tra... | stack_v2_sparse_classes_36k_train_033763 | 21,671 | permissive | [
{
"docstring": "Our actual ResNet network. We return the output of c2, c3,c4,c5 N.B. batch norm is always run with trained parameters, as we use very small batches when training the object layers. Args: resnet_model: model type. Authorized Values: (resnet18, resnet34, resnet50, resnet101, resnet152, resnet200) ... | 2 | null | Implement the Python class `Resnet_Model` described below.
Class description:
Implement the Resnet_Model class.
Method signatures and docstrings:
- def __init__(self, resnet_model, data_format='channels_last', trainable=True, finetune_bn=False, *args, **kwargs): Our actual ResNet network. We return the output of c2, ... | Implement the Python class `Resnet_Model` described below.
Class description:
Implement the Resnet_Model class.
Method signatures and docstrings:
- def __init__(self, resnet_model, data_format='channels_last', trainable=True, finetune_bn=False, *args, **kwargs): Our actual ResNet network. We return the output of c2, ... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class Resnet_Model:
def __init__(self, resnet_model, data_format='channels_last', trainable=True, finetune_bn=False, *args, **kwargs):
"""Our actual ResNet network. We return the output of c2, c3,c4,c5 N.B. batch norm is always run with trained parameters, as we use very small batches when tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resnet_Model:
def __init__(self, resnet_model, data_format='channels_last', trainable=True, finetune_bn=False, *args, **kwargs):
"""Our actual ResNet network. We return the output of c2, c3,c4,c5 N.B. batch norm is always run with trained parameters, as we use very small batches when training the obje... | the_stack_v2_python_sparse | TensorFlow/computer_vision/maskrcnn/mask_rcnn/models/resnet.py | HabanaAI/Model-References | train | 108 | |
36fdd524f9ba903b352a64dbdfaedcd5006b741a | [
"self.__study_database = study_database\nself.__params = params\nif params is None:\n self.__params = SchedulerParams()\nself.proficiency_level_intervals = Config.proficiency_level_intervals\nself.new_card_interval = Config.new_card_interval\nself.min_repeat_interval = Config.min_repeat_interval\nself.__card_inf... | <|body_start_0|>
self.__study_database = study_database
self.__params = params
if params is None:
self.__params = SchedulerParams()
self.proficiency_level_intervals = Config.proficiency_level_intervals
self.new_card_interval = Config.new_card_interval
self.min... | Handles scheduling the order of cards to study. | Scheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scheduler:
"""Handles scheduling the order of cards to study."""
def __init__(self, cards, study_database, params=None):
"""Constructs the scheduler."""
<|body_0|>
def reset(self):
"""Reset the scheduler."""
<|body_1|>
def mark(self, card: Card, knew... | stack_v2_sparse_classes_36k_train_033764 | 5,965 | permissive | [
{
"docstring": "Constructs the scheduler.",
"name": "__init__",
"signature": "def __init__(self, cards, study_database, params=None)"
},
{
"docstring": "Reset the scheduler.",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "Mark a card as \"knew it\" or \"didn'... | 6 | stack_v2_sparse_classes_30k_train_005296 | Implement the Python class `Scheduler` described below.
Class description:
Handles scheduling the order of cards to study.
Method signatures and docstrings:
- def __init__(self, cards, study_database, params=None): Constructs the scheduler.
- def reset(self): Reset the scheduler.
- def mark(self, card: Card, knew_it:... | Implement the Python class `Scheduler` described below.
Class description:
Handles scheduling the order of cards to study.
Method signatures and docstrings:
- def __init__(self, cards, study_database, params=None): Constructs the scheduler.
- def reset(self): Reset the scheduler.
- def mark(self, card: Card, knew_it:... | b073df4694f1ad064a780088cdcb1436e1bde7e9 | <|skeleton|>
class Scheduler:
"""Handles scheduling the order of cards to study."""
def __init__(self, cards, study_database, params=None):
"""Constructs the scheduler."""
<|body_0|>
def reset(self):
"""Reset the scheduler."""
<|body_1|>
def mark(self, card: Card, knew... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scheduler:
"""Handles scheduling the order of cards to study."""
def __init__(self, cards, study_database, params=None):
"""Constructs the scheduler."""
self.__study_database = study_database
self.__params = params
if params is None:
self.__params = SchedulerPa... | the_stack_v2_python_sparse | study_tool/scheduler.py | cubeman99/russian-study-tool | train | 0 |
96183311d01c3e2196e16b3a5dca6f89ac3ec3c7 | [
"asyncnotifier.FileEventHandlerBase.__init__(self, wm)\nself._cb = cb\nself._filename = os.path.basename(path)\nmask = pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'] | pyinotify.EventsCodes.ALL_FLAGS['IN_DELETE'] | pyinotify.EventsCodes.ALL_FLAGS['IN_MOVED_FROM'] | pyinotify.EventsCodes.ALL_FLAGS['IN_MOVED_TO']\... | <|body_start_0|>
asyncnotifier.FileEventHandlerBase.__init__(self, wm)
self._cb = cb
self._filename = os.path.basename(path)
mask = pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'] | pyinotify.EventsCodes.ALL_FLAGS['IN_DELETE'] | pyinotify.EventsCodes.ALL_FLAGS['IN_MOVED_FROM'] | pyinot... | FileEventHandler | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileEventHandler:
def __init__(self, wm, path, cb):
"""Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb: Function called on file change"""
<|body_0|>
def process_default(self, event):
"""C... | stack_v2_sparse_classes_36k_train_033765 | 12,206 | permissive | [
{
"docstring": "Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb: Function called on file change",
"name": "__init__",
"signature": "def __init__(self, wm, path, cb)"
},
{
"docstring": "Called upon inotify event.",
... | 2 | stack_v2_sparse_classes_30k_train_011819 | Implement the Python class `FileEventHandler` described below.
Class description:
Implement the FileEventHandler class.
Method signatures and docstrings:
- def __init__(self, wm, path, cb): Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb:... | Implement the Python class `FileEventHandler` described below.
Class description:
Implement the FileEventHandler class.
Method signatures and docstrings:
- def __init__(self, wm, path, cb): Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb:... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class FileEventHandler:
def __init__(self, wm, path, cb):
"""Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb: Function called on file change"""
<|body_0|>
def process_default(self, event):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileEventHandler:
def __init__(self, wm, path, cb):
"""Initializes this class. @param wm: Inotify watch manager @type path: string @param path: File path @type cb: callable @param cb: Function called on file change"""
asyncnotifier.FileEventHandlerBase.__init__(self, wm)
self._cb = cb
... | the_stack_v2_python_sparse | lib/server/rapi.py | ganeti/ganeti | train | 465 | |
d442ff00e10d07440d5024fcbea84182f52c97a8 | [
"BaseWorkerThread.__init__(self)\nself.wq = queue\nself.config = config\nif reqMgr:\n self.reqMgr = reqMgr\nelse:\n self.reqMgr = WorkQueueReqMgrInterface(**self.config)\nself.previousState = {}",
"t = random.randrange(self.idleTime)\nself.logger.info('Sleeping for %d seconds before 1st loop' % t)\ntime.sle... | <|body_start_0|>
BaseWorkerThread.__init__(self)
self.wq = queue
self.config = config
if reqMgr:
self.reqMgr = reqMgr
else:
self.reqMgr = WorkQueueReqMgrInterface(**self.config)
self.previousState = {}
<|end_body_0|>
<|body_start_1|>
t = r... | Polls for requests | WorkQueueManagerReqMgrPoller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkQueueManagerReqMgrPoller:
"""Polls for requests"""
def __init__(self, queue, config, reqMgr=None):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at once"""
... | stack_v2_sparse_classes_36k_train_033766 | 1,352 | permissive | [
{
"docstring": "Initialise class members",
"name": "__init__",
"signature": "def __init__(self, queue, config, reqMgr=None)"
},
{
"docstring": "Called at startup - introduce random delay to avoid workers all starting at once",
"name": "setup",
"signature": "def setup(self, parameters)"
... | 3 | stack_v2_sparse_classes_30k_train_020734 | Implement the Python class `WorkQueueManagerReqMgrPoller` described below.
Class description:
Polls for requests
Method signatures and docstrings:
- def __init__(self, queue, config, reqMgr=None): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid workers all s... | Implement the Python class `WorkQueueManagerReqMgrPoller` described below.
Class description:
Polls for requests
Method signatures and docstrings:
- def __init__(self, queue, config, reqMgr=None): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid workers all s... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class WorkQueueManagerReqMgrPoller:
"""Polls for requests"""
def __init__(self, queue, config, reqMgr=None):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at once"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkQueueManagerReqMgrPoller:
"""Polls for requests"""
def __init__(self, queue, config, reqMgr=None):
"""Initialise class members"""
BaseWorkerThread.__init__(self)
self.wq = queue
self.config = config
if reqMgr:
self.reqMgr = reqMgr
else:
... | the_stack_v2_python_sparse | src/python/WMComponent/WorkQueueManager/WorkQueueManagerReqMgrPoller.py | vkuznet/WMCore | train | 0 |
72d2ee8a515be65bb5becaa84726c86102dc928c | [
"super(ResizeDetailsMessageBox, self).__init__(*args, **kwargs)\nself.detailsBoxWidth = detailsBoxWidth\nself.detailBoxHeight = detailBoxHeight",
"result = super(ResizeDetailsMessageBox, self).resizeEvent(event)\ndetails_box = self.findChild(QtWidgets.QTextEdit)\nif details_box is not None:\n details_box.setFi... | <|body_start_0|>
super(ResizeDetailsMessageBox, self).__init__(*args, **kwargs)
self.detailsBoxWidth = detailsBoxWidth
self.detailBoxHeight = detailBoxHeight
<|end_body_0|>
<|body_start_1|>
result = super(ResizeDetailsMessageBox, self).resizeEvent(event)
details_box = self.findC... | Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.com/questions/2655354/how-to-allow-resizing-of-qmessagebox-in-pyqt4 | ResizeDetailsMessageBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResizeDetailsMessageBox:
"""Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.com/questions/2655354/how-to-allow-resizi... | stack_v2_sparse_classes_36k_train_033767 | 7,800 | permissive | [
{
"docstring": "Constructor :param detailsBoxWidht: The width of the details text box (default=700) :param detailBoxHeight: The heights of the details text box (default=700)",
"name": "__init__",
"signature": "def __init__(self, detailsBoxWidth=700, detailBoxHeight=300, *args, **kwargs)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_009386 | Implement the Python class `ResizeDetailsMessageBox` described below.
Class description:
Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.co... | Implement the Python class `ResizeDetailsMessageBox` described below.
Class description:
Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.co... | 57a66e2d7030c265f0b5e1d577326cb9e986216f | <|skeleton|>
class ResizeDetailsMessageBox:
"""Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.com/questions/2655354/how-to-allow-resizi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResizeDetailsMessageBox:
"""Message box that enlarges when the 'Show Details' button is clicked. Can be used to better view stack traces. I could't find how to make a resizeable message box but this it the next best thing. Taken from: http://stackoverflow.com/questions/2655354/how-to-allow-resizing-of-qmessag... | the_stack_v2_python_sparse | objbrowser/app.py | titusjan/objbrowser | train | 94 |
47868ab76c3679063561f724b7bd07662a27d5bb | [
"super().__init__(status)\nself._name = name\nself._actions = actions",
"attr = {}\nif self._actions:\n attr['actions_enabled'] = self._actions.enabled\n if self._actions.last_finished != EMPTY_TIME:\n attr['actions_last_finished'] = self._actions.last_finished\n if self._actions.last_run != EMPTY... | <|body_start_0|>
super().__init__(status)
self._name = name
self._actions = actions
<|end_body_0|>
<|body_start_1|>
attr = {}
if self._actions:
attr['actions_enabled'] = self._actions.enabled
if self._actions.last_finished != EMPTY_TIME:
a... | Representation of an ISY994 program base. | ISYProgramEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
<|body_0|>
def extra_state_attributes(self) -> dict:
"""Get the state attributes for t... | stack_v2_sparse_classes_36k_train_033768 | 9,283 | permissive | [
{
"docstring": "Initialize the ISY994 program-based entity.",
"name": "__init__",
"signature": "def __init__(self, name: str, status, actions=None) -> None"
},
{
"docstring": "Get the state attributes for the device.",
"name": "extra_state_attributes",
"signature": "def extra_state_attri... | 2 | null | Implement the Python class `ISYProgramEntity` described below.
Class description:
Representation of an ISY994 program base.
Method signatures and docstrings:
- def __init__(self, name: str, status, actions=None) -> None: Initialize the ISY994 program-based entity.
- def extra_state_attributes(self) -> dict: Get the s... | Implement the Python class `ISYProgramEntity` described below.
Class description:
Representation of an ISY994 program base.
Method signatures and docstrings:
- def __init__(self, name: str, status, actions=None) -> None: Initialize the ISY994 program-based entity.
- def extra_state_attributes(self) -> dict: Get the s... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
<|body_0|>
def extra_state_attributes(self) -> dict:
"""Get the state attributes for t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
super().__init__(status)
self._name = name
self._actions = actions
def extra_state_attribut... | the_stack_v2_python_sparse | homeassistant/components/isy994/entity.py | BenWoodford/home-assistant | train | 11 |
66730ac42d50807b439609c771bd8605a60eca23 | [
"try:\n return self.find_elem('input[name=\"' + self.comp_name + '\"] + div')\nexcept Exception as ex:\n print('调查问卷获取div异常:%s' % ex)\n return 'none'",
"try:\n return self.get_the_div().text\nexcept Exception as ex:\n print('调查问卷获取内容异常:%s' % ex)\n return ''",
"try:\n the_div = self.get_the_... | <|body_start_0|>
try:
return self.find_elem('input[name="' + self.comp_name + '"] + div')
except Exception as ex:
print('调查问卷获取div异常:%s' % ex)
return 'none'
<|end_body_0|>
<|body_start_1|>
try:
return self.get_the_div().text
except Excepti... | SuperSurveyPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperSurveyPage:
def get_the_div(self):
"""获取the div"""
<|body_0|>
def get_the_div_text(self):
"""获取the div 内容"""
<|body_1|>
def the_check_is_enabled(self):
"""复选框是否只读"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_033769 | 1,780 | no_license | [
{
"docstring": "获取the div",
"name": "get_the_div",
"signature": "def get_the_div(self)"
},
{
"docstring": "获取the div 内容",
"name": "get_the_div_text",
"signature": "def get_the_div_text(self)"
},
{
"docstring": "复选框是否只读",
"name": "the_check_is_enabled",
"signature": "def t... | 3 | null | Implement the Python class `SuperSurveyPage` described below.
Class description:
Implement the SuperSurveyPage class.
Method signatures and docstrings:
- def get_the_div(self): 获取the div
- def get_the_div_text(self): 获取the div 内容
- def the_check_is_enabled(self): 复选框是否只读 | Implement the Python class `SuperSurveyPage` described below.
Class description:
Implement the SuperSurveyPage class.
Method signatures and docstrings:
- def get_the_div(self): 获取the div
- def get_the_div_text(self): 获取the div 内容
- def the_check_is_enabled(self): 复选框是否只读
<|skeleton|>
class SuperSurveyPage:
def ... | 78768989a79a14013b983024cf6e4838d51ed595 | <|skeleton|>
class SuperSurveyPage:
def get_the_div(self):
"""获取the div"""
<|body_0|>
def get_the_div_text(self):
"""获取the div 内容"""
<|body_1|>
def the_check_is_enabled(self):
"""复选框是否只读"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperSurveyPage:
def get_the_div(self):
"""获取the div"""
try:
return self.find_elem('input[name="' + self.comp_name + '"] + div')
except Exception as ex:
print('调查问卷获取div异常:%s' % ex)
return 'none'
def get_the_div_text(self):
"""获取the div ... | the_stack_v2_python_sparse | test_case/page_obj/form/survey_page.py | pylk/pythonSelenium | train | 0 | |
9bab21a1131de0de8332b76fa0c72b086c3f92d3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthApplicationPerformance()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'activeDeviceCount': lambda n: setattr(self, 'active_device_count', n.get_i... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthApplicationPerformance()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], N... | The user experience analytics application performance entity contains application performance details. | UserExperienceAnalyticsAppHealthApplicationPerformance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthApplicationPerformance:
"""The user experience analytics application performance entity contains application performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthApplicationPerform... | stack_v2_sparse_classes_36k_train_033770 | 5,222 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsAppHealthApplicationPerformance",
"name": "create_from_discriminator_value",
"signatu... | 3 | stack_v2_sparse_classes_30k_val_000768 | Implement the Python class `UserExperienceAnalyticsAppHealthApplicationPerformance` described below.
Class description:
The user experience analytics application performance entity contains application performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[Pa... | Implement the Python class `UserExperienceAnalyticsAppHealthApplicationPerformance` described below.
Class description:
The user experience analytics application performance entity contains application performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[Pa... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthApplicationPerformance:
"""The user experience analytics application performance entity contains application performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthApplicationPerform... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsAppHealthApplicationPerformance:
"""The user experience analytics application performance entity contains application performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthApplicationPerformance:
... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_application_performance.py | microsoftgraph/msgraph-sdk-python | train | 135 |
33795fb522e68ba325830305dc76aab9e4866567 | [
"cache_key = calendar_year\nif cache_key not in ImplicitPriceDeflators._cache:\n calendar_years = pd.Series(ImplicitPriceDeflators._data.keys())\n if len(calendar_years[calendar_years <= calendar_year]) > 0:\n year = max(calendar_years[calendar_years <= calendar_year])\n ImplicitPriceDeflators._... | <|body_start_0|>
cache_key = calendar_year
if cache_key not in ImplicitPriceDeflators._cache:
calendar_years = pd.Series(ImplicitPriceDeflators._data.keys())
if len(calendar_years[calendar_years <= calendar_year]) > 0:
year = max(calendar_years[calendar_years <= c... | **Loads and provides access to implicit price deflators by calendar year.** | ImplicitPriceDeflators | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImplicitPriceDeflators:
"""**Loads and provides access to implicit price deflators by calendar year.**"""
def get_price_deflator(calendar_year):
"""Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Return... | stack_v2_sparse_classes_36k_train_033771 | 5,369 | no_license | [
{
"docstring": "Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implicit price deflator for the given calendar year.",
"name": "get_price_deflator",
"signature": "def get_price_deflator(calendar_year)"
},
... | 3 | stack_v2_sparse_classes_30k_train_013126 | Implement the Python class `ImplicitPriceDeflators` described below.
Class description:
**Loads and provides access to implicit price deflators by calendar year.**
Method signatures and docstrings:
- def get_price_deflator(calendar_year): Get the implicit price deflator for the given calendar year. Args: calendar_yea... | Implement the Python class `ImplicitPriceDeflators` described below.
Class description:
**Loads and provides access to implicit price deflators by calendar year.**
Method signatures and docstrings:
- def get_price_deflator(calendar_year): Get the implicit price deflator for the given calendar year. Args: calendar_yea... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class ImplicitPriceDeflators:
"""**Loads and provides access to implicit price deflators by calendar year.**"""
def get_price_deflator(calendar_year):
"""Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImplicitPriceDeflators:
"""**Loads and provides access to implicit price deflators by calendar year.**"""
def get_price_deflator(calendar_year):
"""Get the implicit price deflator for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: The implic... | the_stack_v2_python_sparse | omega_model/context/ip_deflators.py | USEPA/EPA_OMEGA_Model | train | 17 |
fbcfee703782feea559cb08ec1bbaf2feb2acd79 | [
"Editeur.__init__(self, pere, objet, attribut)\nself.dictionnaire = dictionnaire or {}\nself.autoriser_none = autoriser_none\nself.feminin = feminin\nself.ajouter_option('s', self.opt_supprimer)",
"objet = getattr(self.objet, self.attribut)\nif objet is None:\n objet = '|att|aucun|ff|'\n if self.feminin:\n ... | <|body_start_0|>
Editeur.__init__(self, pere, objet, attribut)
self.dictionnaire = dictionnaire or {}
self.autoriser_none = autoriser_none
self.feminin = feminin
self.ajouter_option('s', self.opt_supprimer)
<|end_body_0|>
<|body_start_1|>
objet = getattr(self.objet, self... | Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir un joueur, une étendue d'eau, un prototype d'objet ou bien d'autres choses. | ChoixObjet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoixObjet:
"""Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir un joueur, une étendue d'eau, un prototy... | stack_v2_sparse_classes_36k_train_033772 | 4,193 | permissive | [
{
"docstring": "Constructeur de l'éditeur.",
"name": "__init__",
"signature": "def __init__(self, pere, objet=None, attribut=None, dictionnaire=None, autoriser_none=True, feminin=False)"
},
{
"docstring": "Retourne l'aide courte",
"name": "accueil",
"signature": "def accueil(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_009002 | Implement the Python class `ChoixObjet` described below.
Class description:
Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir u... | Implement the Python class `ChoixObjet` described below.
Class description:
Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir u... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class ChoixObjet:
"""Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir un joueur, une étendue d'eau, un prototy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChoixObjet:
"""Contexte-éditeur choix. Ce contexte permet de faire choisir l'utilisateur une option parmi un dictionnaire : les clés doivent être les chaînes de choix et les valeurs sont les objets correspondants. Cet éditeur peut être utilisé pour choisir un joueur, une étendue d'eau, un prototype d'objet ou... | the_stack_v2_python_sparse | src/primaires/interpreteur/editeur/choix_objet.py | vincent-lg/tsunami | train | 5 |
3355d3b7ab3095433eae1b057f3309b7e4ae8a59 | [
"if DOMAIN_NOT_FOUND:\n return HttpResponseNotFound(DOMAIN_NOT_FOUND_MSG)\nreturn Response([{'ruleId': 0, 'ruleZone': 'string', 'ruleDomain': domain, 'ruleTarget': 'string', 'ruleReason': 'string', 'ruleNote': 'string'}])",
"if DOMAIN_NOT_FOUND:\n return HttpResponseNotFound(DOMAIN_NOT_FOUND_MSG)\nif len(re... | <|body_start_0|>
if DOMAIN_NOT_FOUND:
return HttpResponseNotFound(DOMAIN_NOT_FOUND_MSG)
return Response([{'ruleId': 0, 'ruleZone': 'string', 'ruleDomain': domain, 'ruleTarget': 'string', 'ruleReason': 'string', 'ruleNote': 'string'}])
<|end_body_0|>
<|body_start_1|>
if DOMAIN_NOT_FO... | [GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rules for the specified ruleDomain | DnsRuleDomain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DnsRuleDomain:
"""[GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rules for the specified ruleDomain"""
... | stack_v2_sparse_classes_36k_train_033773 | 7,677 | permissive | [
{
"docstring": ":param domain: limited to from one to many non-digit characters, this can be changed in ./urls.py",
"name": "get",
"signature": "def get(self, request, domain, **kwargs)"
},
{
"docstring": "Change a zone or target or reason or note, if not all of these are given, rest of the attr... | 3 | stack_v2_sparse_classes_30k_train_009881 | Implement the Python class `DnsRuleDomain` described below.
Class description:
[GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rule... | Implement the Python class `DnsRuleDomain` described below.
Class description:
[GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rule... | 73e4ac0ced6c3ac46d24ac5c3feb01a1e88bd36b | <|skeleton|>
class DnsRuleDomain:
"""[GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rules for the specified ruleDomain"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DnsRuleDomain:
"""[GET] /dnsfw/{ruleDomain} Get all rules with the specified ruleDomain from a DNS FW [PUT] /dnsfw/{ruleDomain} Change a zone or target or reason or note for all rules with the specified ruleDomain [DELETE] /dnsfw/{ruleDomain} Delete all rules for the specified ruleDomain"""
def get(self,... | the_stack_v2_python_sparse | crusoe_act/act-component/dnsfw-wrapper/dnsfw_wrapper_project/views.py | wumingruiye/CRUSOE | train | 0 |
b20abfa3f5bed7c39e8bdd49ae471838bab7b6a0 | [
"def create_partition(i, j):\n return cls.frame_partition_cls(GPU_MANAGERS[i], partition_ids[i][j], length=row_lengths[i], width=column_widths[j])\nreturn np.array([[create_partition(i, j) for j in range(len(partition_ids[i]))] for i in range(len(partition_ids))])",
"partition_ids = [None] * len(splits)\nindex... | <|body_start_0|>
def create_partition(i, j):
return cls.frame_partition_cls(GPU_MANAGERS[i], partition_ids[i][j], length=row_lengths[i], width=column_widths[j])
return np.array([[create_partition(i, j) for j in range(len(partition_ids[i]))] for i in range(len(partition_ids))])
<|end_body_0|>... | The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files. | cuDFCSVDispatcher | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parame... | stack_v2_sparse_classes_36k_train_033774 | 3,694 | permissive | [
{
"docstring": "Build array with partitions of `cls.frame_partition_cls` class. Parameters ---------- partition_ids : list Array with references to the partitions data. row_lengths : list Partitions rows lengths. column_widths : list Number of columns in each partition. Returns ------- np.ndarray Array with sha... | 2 | stack_v2_sparse_classes_30k_train_003543 | Implement the Python class `cuDFCSVDispatcher` described below.
Class description:
The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files.
Method signatures and docstrings:
- def build_partition(cls, partition_ids, row_lengths, column_widths): Build array w... | Implement the Python class `cuDFCSVDispatcher` described below.
Class description:
The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files.
Method signatures and docstrings:
- def build_partition(cls, partition_ids, row_lengths, column_widths): Build array w... | 8f6e00378e095817deccd25f4140406c5ee6c992 | <|skeleton|>
class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parameters --------... | the_stack_v2_python_sparse | modin/core/execution/ray/implementations/cudf_on_ray/io/text/csv_dispatcher.py | modin-project/modin | train | 9,241 |
4f8f0d23262411d918b4fdf4bd9fa297dcbc58d7 | [
"if not root:\n return '[null]'\nqueue = [root]\ndata = []\nwhile queue:\n curr = queue[0]\n if curr:\n data.append(str(curr.val))\n else:\n data.append('null')\n del queue[0]\n if curr:\n queue.append(curr.left)\n queue.append(curr.right)\nreturn '[' + ','.join(data) +... | <|body_start_0|>
if not root:
return '[null]'
queue = [root]
data = []
while queue:
curr = queue[0]
if curr:
data.append(str(curr.val))
else:
data.append('null')
del queue[0]
if curr:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033775 | 3,196 | 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 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_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"""
if not root:
return '[null]'
queue = [root]
data = []
while queue:
curr = queue[0]
if curr:
data.append(str(cu... | the_stack_v2_python_sparse | python_solution/291_300/SerializeDeserializeBinaryTree.py | CescWang1991/LeetCode-Python | train | 1 | |
f6daa8cc87c715d5e849f60f0d177dda6f684f9e | [
"obj = self.get_object()\nviews.add_like(obj, request.user)\nreturn redirect('com_list')",
"obj = self.get_object()\nviews.remove_like(obj, request.user)\nreturn redirect('com_list')",
"obj = self.get_object()\nfans = views.get_fans(obj)\nserializer = FanSerializer(fans, many=True)\nreturn Response(serializer.d... | <|body_start_0|>
obj = self.get_object()
views.add_like(obj, request.user)
return redirect('com_list')
<|end_body_0|>
<|body_start_1|>
obj = self.get_object()
views.remove_like(obj, request.user)
return redirect('com_list')
<|end_body_1|>
<|body_start_2|>
obj = ... | LikedMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
<|body_0|>
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
<|body_1|>
def fans(self, request, pk=None):
"""Получает всех пользователей, которые лайкнули `obj`."""
... | stack_v2_sparse_classes_36k_train_033776 | 1,034 | no_license | [
{
"docstring": "Лайкает `obj`.",
"name": "like",
"signature": "def like(self, request, pk=None)"
},
{
"docstring": "Удаляет лайк с `obj`.",
"name": "unlike",
"signature": "def unlike(self, request, pk=None)"
},
{
"docstring": "Получает всех пользователей, которые лайкнули `obj`."... | 3 | null | Implement the Python class `LikedMixin` described below.
Class description:
Implement the LikedMixin class.
Method signatures and docstrings:
- def like(self, request, pk=None): Лайкает `obj`.
- def unlike(self, request, pk=None): Удаляет лайк с `obj`.
- def fans(self, request, pk=None): Получает всех пользователей, ... | Implement the Python class `LikedMixin` described below.
Class description:
Implement the LikedMixin class.
Method signatures and docstrings:
- def like(self, request, pk=None): Лайкает `obj`.
- def unlike(self, request, pk=None): Удаляет лайк с `obj`.
- def fans(self, request, pk=None): Получает всех пользователей, ... | bf8d7bf0b0d2e146f3eededc2d1bfa542a897abf | <|skeleton|>
class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
<|body_0|>
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
<|body_1|>
def fans(self, request, pk=None):
"""Получает всех пользователей, которые лайкнули `obj`."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
obj = self.get_object()
views.add_like(obj, request.user)
return redirect('com_list')
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
obj = self.get_object()
views.re... | the_stack_v2_python_sparse | OOP/proj/insta/lenta/mixins.py | killkamad/PC-home | train | 2 | |
959e8db9f9e18ed7ea1a8b6c823cce644608fd77 | [
"if probability_fn is None:\n probability_fn = tf.nn.softmax\nif dtype is None:\n dtype = tf.float32\nwrapped_probability_fn = lambda score, _: probability_fn(score)\nsuper(HyperAttention, self).__init__(query_layer=None, memory_layer=HyperDense(num_units, mem_input=mem_input, hps=hps, use_beam=use_beam, name... | <|body_start_0|>
if probability_fn is None:
probability_fn = tf.nn.softmax
if dtype is None:
dtype = tf.float32
wrapped_probability_fn = lambda score, _: probability_fn(score)
super(HyperAttention, self).__init__(query_layer=None, memory_layer=HyperDense(num_units... | Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based Neural Machine Translation." EMNLP 2015. https://arxiv.org/abs/1508.04025 The sec... | HyperAttention | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperAttention:
"""Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based Neural Machine Translation." EMNLP 2015... | stack_v2_sparse_classes_36k_train_033777 | 20,121 | permissive | [
{
"docstring": "Construct the AttentionMechanism mechanism. Args: num_units: The depth of the attention mechanism. mem_input: mem_input. hps: hyperparameters. memory: The memory to query; usually the output of an RNN encoder. This tensor should be shaped `[batch_size, max_time, ...]`. use_beam: Use beam search ... | 2 | null | Implement the Python class `HyperAttention` described below.
Class description:
Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based ... | Implement the Python class `HyperAttention` described below.
Class description:
Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based ... | ac9447064195e06de48cc91ff642f7fffa28ffe8 | <|skeleton|>
class HyperAttention:
"""Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based Neural Machine Translation." EMNLP 2015... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HyperAttention:
"""Implements Luong-style (multiplicative) attention scoring. This attention has two forms. The first is standard Luong attention, as described in: Minh-Thang Luong, Hieu Pham, Christopher D. Manning. "Effective Approaches to Attention-based Neural Machine Translation." EMNLP 2015. https://arx... | the_stack_v2_python_sparse | language/labs/exemplar_decoding/models/attention.py | google-research/language | train | 1,567 |
55ca6c64435a0e357cd429f6cd6bffaef4e86acc | [
"super(MailMail, self).send(auto_commit, raise_exception)\nfor mail in self.filtered(lambda m: m.state == 'exception'):\n record = self.env[mail.model].browse(mail.res_id)\n reason = mail.failure_reason\n mail.note_delivery_failure(record, reason)\nreturn True",
"message = 'Mail Delivery Failure: %s' % r... | <|body_start_0|>
super(MailMail, self).send(auto_commit, raise_exception)
for mail in self.filtered(lambda m: m.state == 'exception'):
record = self.env[mail.model].browse(mail.res_id)
reason = mail.failure_reason
mail.note_delivery_failure(record, reason)
ret... | MailMail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailMail:
def send(self, auto_commit=False, raise_exception=False):
"""If mail has exception, leave note on record's chatter box"""
<|body_0|>
def note_delivery_failure(self, record, reason):
"""Note mail delivery failure on chatter box"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_033778 | 1,283 | no_license | [
{
"docstring": "If mail has exception, leave note on record's chatter box",
"name": "send",
"signature": "def send(self, auto_commit=False, raise_exception=False)"
},
{
"docstring": "Note mail delivery failure on chatter box",
"name": "note_delivery_failure",
"signature": "def note_deliv... | 2 | stack_v2_sparse_classes_30k_train_007852 | Implement the Python class `MailMail` described below.
Class description:
Implement the MailMail class.
Method signatures and docstrings:
- def send(self, auto_commit=False, raise_exception=False): If mail has exception, leave note on record's chatter box
- def note_delivery_failure(self, record, reason): Note mail d... | Implement the Python class `MailMail` described below.
Class description:
Implement the MailMail class.
Method signatures and docstrings:
- def send(self, auto_commit=False, raise_exception=False): If mail has exception, leave note on record's chatter box
- def note_delivery_failure(self, record, reason): Note mail d... | 7adeceea5c12129baad36c037ff188cbccc98e2f | <|skeleton|>
class MailMail:
def send(self, auto_commit=False, raise_exception=False):
"""If mail has exception, leave note on record's chatter box"""
<|body_0|>
def note_delivery_failure(self, record, reason):
"""Note mail delivery failure on chatter box"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailMail:
def send(self, auto_commit=False, raise_exception=False):
"""If mail has exception, leave note on record's chatter box"""
super(MailMail, self).send(auto_commit, raise_exception)
for mail in self.filtered(lambda m: m.state == 'exception'):
record = self.env[mail.m... | the_stack_v2_python_sparse | mail_delivery_failure_note/models/mail_mail.py | MarcosCommunity/marcos_community_addons | train | 15 | |
0347830fa489e63d8e92f046b3037ef5e2d2cb44 | [
"root = Tree.CreateNode(rootVal)\nfor i in range(0, len(arr)):\n if arr[i]:\n BSTree.Insert(root, arr[i])\nreturn root",
"node = root\nnewNode = Tree.CreateNode(val)\nparent = None\nwhile node:\n parent = node\n if val > parent.val:\n node = node.right\n else:\n node = node.left\n... | <|body_start_0|>
root = Tree.CreateNode(rootVal)
for i in range(0, len(arr)):
if arr[i]:
BSTree.Insert(root, arr[i])
return root
<|end_body_0|>
<|body_start_1|>
node = root
newNode = Tree.CreateNode(val)
parent = None
while node:
... | BSTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTree:
def CreateBSTree(rootVal, arr):
""":type arr: int :type arr: list :rtype: TreeNode"""
<|body_0|>
def Insert(root, val):
""":type root: TreeNode :type val: int :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
root = Tree.CreateNod... | stack_v2_sparse_classes_36k_train_033779 | 946 | no_license | [
{
"docstring": ":type arr: int :type arr: list :rtype: TreeNode",
"name": "CreateBSTree",
"signature": "def CreateBSTree(rootVal, arr)"
},
{
"docstring": ":type root: TreeNode :type val: int :rtype: void",
"name": "Insert",
"signature": "def Insert(root, val)"
}
] | 2 | null | Implement the Python class `BSTree` described below.
Class description:
Implement the BSTree class.
Method signatures and docstrings:
- def CreateBSTree(rootVal, arr): :type arr: int :type arr: list :rtype: TreeNode
- def Insert(root, val): :type root: TreeNode :type val: int :rtype: void | Implement the Python class `BSTree` described below.
Class description:
Implement the BSTree class.
Method signatures and docstrings:
- def CreateBSTree(rootVal, arr): :type arr: int :type arr: list :rtype: TreeNode
- def Insert(root, val): :type root: TreeNode :type val: int :rtype: void
<|skeleton|>
class BSTree:
... | 1e027e7a223bcddd05ddd909b76d537c45da4cc7 | <|skeleton|>
class BSTree:
def CreateBSTree(rootVal, arr):
""":type arr: int :type arr: list :rtype: TreeNode"""
<|body_0|>
def Insert(root, val):
""":type root: TreeNode :type val: int :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTree:
def CreateBSTree(rootVal, arr):
""":type arr: int :type arr: list :rtype: TreeNode"""
root = Tree.CreateNode(rootVal)
for i in range(0, len(arr)):
if arr[i]:
BSTree.Insert(root, arr[i])
return root
def Insert(root, val):
""":type... | the_stack_v2_python_sparse | Helper/Python/BSTree.py | xjz1994/LeetCodeSolution | train | 2 | |
f06e91b3eef30dd7e38b6733f281198e82e595f8 | [
"self.backend = get_backend(backend)\nif backend == 'cython':\n raise NotImplementedError('LocalMem is only meaningful for the opencl/cuda backends.')\nself.size = size\nself._cache = {}",
"key = (c_type, workgroup_size)\nif key in self._cache:\n return self._cache[key]\nelif self.backend == 'opencl':\n ... | <|body_start_0|>
self.backend = get_backend(backend)
if backend == 'cython':
raise NotImplementedError('LocalMem is only meaningful for the opencl/cuda backends.')
self.size = size
self._cache = {}
<|end_body_0|>
<|body_start_1|>
key = (c_type, workgroup_size)
... | A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2`` | LocalMem | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalMem:
"""A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2``"""
def __init__(self, size, backend=None):
"""Constructor Parameter... | stack_v2_sparse_classes_36k_train_033780 | 11,279 | permissive | [
{
"docstring": "Constructor Parameters ---------- size: int: a multiple of the current work group size. baackend: str: one of 'opencl', 'cuda'",
"name": "__init__",
"signature": "def __init__(self, size, backend=None)"
},
{
"docstring": "Return the local memory required given the type and work g... | 2 | stack_v2_sparse_classes_30k_train_012749 | Implement the Python class `LocalMem` described below.
Class description:
A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2``
Method signatures and docstrings:
- def ... | Implement the Python class `LocalMem` described below.
Class description:
A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2``
Method signatures and docstrings:
- def ... | e6584827c2d45b0ee792500a0f9b10b59976782c | <|skeleton|>
class LocalMem:
"""A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2``"""
def __init__(self, size, backend=None):
"""Constructor Parameter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalMem:
"""A local memory specification for a GPU kernel. An example illustrates this best:: >>> l = LocalMem(2) >>> m = l.get('double', 128) >>> m.size 2048 Note that this is basically ``sizeof(double) * 128 * 2``"""
def __init__(self, size, backend=None):
"""Constructor Parameters ---------- ... | the_stack_v2_python_sparse | compyle/low_level.py | pypr/compyle | train | 78 |
4c3eaa2c813dcd7564609ba82e52cc830e36530a | [
"if opt is None:\n opt = ConvCnstrMODMask.Options()\nself.cri = cr.CDU_ConvRepIndexing(dsz, S, dimK=dimK, dimN=dimN)\nif hasattr(W, 'ndim'):\n W = sl.atleast_nd(self.cri.dimN + 3, W)\nif self.cri.Cd == 1 and self.cri.C > 1 and hasattr(W, 'ndim'):\n shpw = list(W.shape)\n swck = shpw[self.cri.axisC] * sh... | <|body_start_0|>
if opt is None:
opt = ConvCnstrMODMask.Options()
self.cri = cr.CDU_ConvRepIndexing(dsz, S, dimK=dimK, dimN=dimN)
if hasattr(W, 'ndim'):
W = sl.atleast_nd(self.cri.dimN + 3, W)
if self.cri.Cd == 1 and self.cri.C > 1 and hasattr(W, 'ndim'):
... | FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{d} \\; (1/2) \\left\\| W \\left(\\sum_m \\mathbf{d}_m * \\mathbf{x}_m - \\mathbf{s}... | ConvCnstrMODMask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvCnstrMODMask:
"""FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{d} \\; (1/2) \\left\\| W \\left(\\sum_m... | stack_v2_sparse_classes_36k_train_033781 | 18,875 | permissive | [
{
"docstring": "| **Call graph** .. image:: ../_static/jonga/ccmodmdfista_init.svg :width: 20% :target: ../_static/jonga/ccmodmdfista_init.svg | Parameters ---------- Z : array_like Coefficient map array S : array_like Signal array W : array_like Mask array. The array shape must be such that the array is compat... | 4 | null | Implement the Python class `ConvCnstrMODMask` described below.
Class description:
FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{... | Implement the Python class `ConvCnstrMODMask` described below.
Class description:
FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{... | 5a64fbe456f3a117275c45ee1f10c60d6e133915 | <|skeleton|>
class ConvCnstrMODMask:
"""FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{d} \\; (1/2) \\left\\| W \\left(\\sum_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvCnstrMODMask:
"""FISTA algorithm for Convolutional Constrained MOD problem with a spatial mask :cite:`garcia-2018-convolutional1`. | .. inheritance-diagram:: ConvCnstrMODMask :parts: 2 | Solve the optimisation problem .. math:: \\mathrm{argmin}_\\mathbf{d} \\; (1/2) \\left\\| W \\left(\\sum_m \\mathbf{d}_... | the_stack_v2_python_sparse | benchmarks/other/sporco/fista/ccmod.py | tomMoral/dicodile | train | 17 |
b767855b52c9b066e4b1200c86b9f8c6f3ab3ff0 | [
"assert df is not None\nassert name is not None\nsuper(Etf, self).__init__('etf ' + name)\ntable = collections.defaultdict(dict)\nfor index, row in df.iterrows():\n timestamp, cusip = index\n date = timestamp.date()\n weight = row['weight_of_cusip_pct']\n assert 0 <= weight <= 100.0\n table[date][cus... | <|body_start_0|>
assert df is not None
assert name is not None
super(Etf, self).__init__('etf ' + name)
table = collections.defaultdict(dict)
for index, row in df.iterrows():
timestamp, cusip = index
date = timestamp.date()
weight = row['weight... | Etf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Etf:
def __init__(self, df=None, name=None):
"""construct"""
<|body_0|>
def make_features(self, trace_index, trace_record):
"""return (None, err) or (DataFrame, None)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert df is not None
asse... | stack_v2_sparse_classes_36k_train_033782 | 47,935 | no_license | [
{
"docstring": "construct",
"name": "__init__",
"signature": "def __init__(self, df=None, name=None)"
},
{
"docstring": "return (None, err) or (DataFrame, None)",
"name": "make_features",
"signature": "def make_features(self, trace_index, trace_record)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004667 | Implement the Python class `Etf` described below.
Class description:
Implement the Etf class.
Method signatures and docstrings:
- def __init__(self, df=None, name=None): construct
- def make_features(self, trace_index, trace_record): return (None, err) or (DataFrame, None) | Implement the Python class `Etf` described below.
Class description:
Implement the Etf class.
Method signatures and docstrings:
- def __init__(self, df=None, name=None): construct
- def make_features(self, trace_index, trace_record): return (None, err) or (DataFrame, None)
<|skeleton|>
class Etf:
def __init__(s... | 3535bd46bff602fc3ba35c080d38b30e75a97fe7 | <|skeleton|>
class Etf:
def __init__(self, df=None, name=None):
"""construct"""
<|body_0|>
def make_features(self, trace_index, trace_record):
"""return (None, err) or (DataFrame, None)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Etf:
def __init__(self, df=None, name=None):
"""construct"""
assert df is not None
assert name is not None
super(Etf, self).__init__('etf ' + name)
table = collections.defaultdict(dict)
for index, row in df.iterrows():
timestamp, cusip = index
... | the_stack_v2_python_sparse | seven/feature_makers.py | rlowrance/test7 | train | 2 | |
22f1a0ed3c8da6e9ed9785349c570c6b6194ca69 | [
"di_eo = (data_container.data_inputs, data_container.expected_outputs)\nnew_data_inputs, new_expected_outputs = self.transform(di_eo)\ndata_container.set_data_inputs((new_data_inputs, new_expected_outputs))\nreturn data_container",
"new_self = self.fit((data_container.data_inputs, data_container.expected_outputs)... | <|body_start_0|>
di_eo = (data_container.data_inputs, data_container.expected_outputs)
new_data_inputs, new_expected_outputs = self.transform(di_eo)
data_container.set_data_inputs((new_data_inputs, new_expected_outputs))
return data_container
<|end_body_0|>
<|body_start_1|>
new_... | Base output transformer step that can modify data inputs, and expected_outputs at the same time. | InputAndOutputTransformerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputAndOutputTransformerMixin:
"""Base output transformer step that can modify data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DataContainer, context: ExecutionContext) -> DataContainer:
"""Handle inverse transform by updati... | stack_v2_sparse_classes_36k_train_033783 | 13,349 | permissive | [
{
"docstring": "Handle inverse transform by updating the data inputs, and expected outputs inside the data container. :param context: execution context :param data_container: :return:",
"name": "_transform_data_container",
"signature": "def _transform_data_container(self, data_container: DataContainer, ... | 3 | stack_v2_sparse_classes_30k_train_003517 | Implement the Python class `InputAndOutputTransformerMixin` described below.
Class description:
Base output transformer step that can modify data inputs, and expected_outputs at the same time.
Method signatures and docstrings:
- def _transform_data_container(self, data_container: DataContainer, context: ExecutionCont... | Implement the Python class `InputAndOutputTransformerMixin` described below.
Class description:
Base output transformer step that can modify data inputs, and expected_outputs at the same time.
Method signatures and docstrings:
- def _transform_data_container(self, data_container: DataContainer, context: ExecutionCont... | 6e9b7b807cd91c370b93c7613b7da3f3313418cc | <|skeleton|>
class InputAndOutputTransformerMixin:
"""Base output transformer step that can modify data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DataContainer, context: ExecutionContext) -> DataContainer:
"""Handle inverse transform by updati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputAndOutputTransformerMixin:
"""Base output transformer step that can modify data inputs, and expected_outputs at the same time."""
def _transform_data_container(self, data_container: DataContainer, context: ExecutionContext) -> DataContainer:
"""Handle inverse transform by updating the data i... | the_stack_v2_python_sparse | neuraxle/steps/output_handlers.py | alexbrillant/Neuraxle | train | 5 |
3bd65855747ce72ddfc2746fb80b12fa7e94d008 | [
"trr_pickle = dir_metadata / f'{tds}.pickle'\ntrr = cls.construct_from_pickle(trr_pickle)\nreturn trr",
"relative_dict = {}\nfor k, v in dataclasses.asdict(self).items():\n if isinstance(v, pathlib.Path) and v.is_relative_to(self.dir_test):\n relative_dict[k] = str(v.relative_to(self.dir_test))\n els... | <|body_start_0|>
trr_pickle = dir_metadata / f'{tds}.pickle'
trr = cls.construct_from_pickle(trr_pickle)
return trr
<|end_body_0|>
<|body_start_1|>
relative_dict = {}
for k, v in dataclasses.asdict(self).items():
if isinstance(v, pathlib.Path) and v.is_relative_to(se... | Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet. | TestRunResult | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRunResult:
"""Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet."""
def construct_from_metadata_dir(cls, dir_metadata: p... | stack_v2_sparse_classes_36k_train_033784 | 4,508 | permissive | [
{
"docstring": "Construct metadata object from exported object using default filenames.",
"name": "construct_from_metadata_dir",
"signature": "def construct_from_metadata_dir(cls, dir_metadata: pathlib.Path, tds: str)"
},
{
"docstring": "Overwrite the default method in scripts_lib.testdata_cls. ... | 2 | null | Implement the Python class `TestRunResult` described below.
Class description:
Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet.
Method signatures an... | Implement the Python class `TestRunResult` described below.
Class description:
Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet.
Method signatures an... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class TestRunResult:
"""Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet."""
def construct_from_metadata_dir(cls, dir_metadata: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRunResult:
"""Holds metadata about a single test and its results. Most of the fields aren't actually optional to running the simulations, but they may be optional in that we haven't yet populated the field or generated the item yet."""
def construct_from_metadata_dir(cls, dir_metadata: pathlib.Path, ... | the_stack_v2_python_sparse | hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/scripts/test_run_result.py | lowRISC/opentitan | train | 2,077 |
8c64b81ccc79bfdc2a88979038b07e72f1ce667a | [
"super().__init__(**kwargs)\nif not self.opt.filetemplate:\n self.opt.filetemplate = i18n.translate(self.site, template_to_the_image)\nelif not re.fullmatch('{{.+}}', self.opt.filetemplate):\n self.opt.filetemplate = '{{%s}}' % self.opt.filetemplate\nif not self.opt.usertemplate:\n self.opt.usertemplate = ... | <|body_start_0|>
super().__init__(**kwargs)
if not self.opt.filetemplate:
self.opt.filetemplate = i18n.translate(self.site, template_to_the_image)
elif not re.fullmatch('{{.+}}', self.opt.filetemplate):
self.opt.filetemplate = '{{%s}}' % self.opt.filetemplate
if n... | Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot | UnusedFilesBot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnusedFilesBot:
"""Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot"""
def __init__(self, **kwargs) -> None:
"""Initializer."""
<|body_0|>
def treat(self, image) -> None:
"""Process one image page."""
<|body_1|>
def appen... | stack_v2_sparse_classes_36k_train_033785 | 6,462 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, **kwargs) -> None"
},
{
"docstring": "Process one image page.",
"name": "treat",
"signature": "def treat(self, image) -> None"
},
{
"docstring": "Append apptext to the page.",
"name": "append_... | 4 | stack_v2_sparse_classes_30k_train_007718 | Implement the Python class `UnusedFilesBot` described below.
Class description:
Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, **kwargs) -> None: Initializer.
- def treat(self, image) -> None: Process one image page.
- def append_te... | Implement the Python class `UnusedFilesBot` described below.
Class description:
Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot
Method signatures and docstrings:
- def __init__(self, **kwargs) -> None: Initializer.
- def treat(self, image) -> None: Process one image page.
- def append_te... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class UnusedFilesBot:
"""Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot"""
def __init__(self, **kwargs) -> None:
"""Initializer."""
<|body_0|>
def treat(self, image) -> None:
"""Process one image page."""
<|body_1|>
def appen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnusedFilesBot:
"""Unused files bot. .. versionchanged:: 7.0 UnusedFilesBot is a ConfigParserBot"""
def __init__(self, **kwargs) -> None:
"""Initializer."""
super().__init__(**kwargs)
if not self.opt.filetemplate:
self.opt.filetemplate = i18n.translate(self.site, templ... | the_stack_v2_python_sparse | scripts/unusedfiles.py | wikimedia/pywikibot | train | 432 |
784853d4e7f89f3f808949c56bb430cdb7f79c39 | [
"if self.request.version == 'v6' or self.request.version == 'v7':\n return self.list_v6(request, dataset_id=dataset_id)\nelse:\n raise Http404",
"try:\n dataset = DataSet.objects.get(pk=dataset_id)\nexcept DataSet.DoesNotExist:\n raise Http404\ndsm = DataSetMember.objects.get_dataset_members(dataset=d... | <|body_start_0|>
if self.request.version == 'v6' or self.request.version == 'v7':
return self.list_v6(request, dataset_id=dataset_id)
else:
raise Http404
<|end_body_0|>
<|body_start_1|>
try:
dataset = DataSet.objects.get(pk=dataset_id)
except DataSet.... | This view is the endpoint for retrieving members of a specific dataset | DataSetMembersView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSetMembersView:
"""This view is the endpoint for retrieving members of a specific dataset"""
def list(self, request, dataset_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.reques... | stack_v2_sparse_classes_36k_train_033786 | 24,544 | permissive | [
{
"docstring": "Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param dataset_id: The dataset id :type dataset_id: int encoded as a str :rtype: :class:`rest_framework.response.Response` :returns: the H... | 2 | null | Implement the Python class `DataSetMembersView` described below.
Class description:
This view is the endpoint for retrieving members of a specific dataset
Method signatures and docstrings:
- def list(self, request, dataset_id): Retrieves the details for a data set and return them in JSON form :param request: the HTTP... | Implement the Python class `DataSetMembersView` described below.
Class description:
This view is the endpoint for retrieving members of a specific dataset
Method signatures and docstrings:
- def list(self, request, dataset_id): Retrieves the details for a data set and return them in JSON form :param request: the HTTP... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class DataSetMembersView:
"""This view is the endpoint for retrieving members of a specific dataset"""
def list(self, request, dataset_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSetMembersView:
"""This view is the endpoint for retrieving members of a specific dataset"""
def list(self, request, dataset_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :p... | the_stack_v2_python_sparse | scale/data/views.py | kfconsultant/scale | train | 0 |
6769edf830f50ab28c5dff313d28e232bb50e6dd | [
"self.n = len(matrix)\nif not self.n:\n return\nself.m = len(matrix[0])\nself.tree = [[0] * 2 * self.m for _ in matrix] + [[0] * self.m + i for i in matrix]\nfor i in range(self.n * 2 - 1, -1, -1):\n for j in range(self.m - 1, -1, -1):\n self.tree[i][j] = self.tree[i][j * 2] + self.tree[i][j * 2 + 1]\n... | <|body_start_0|>
self.n = len(matrix)
if not self.n:
return
self.m = len(matrix[0])
self.tree = [[0] * 2 * self.m for _ in matrix] + [[0] * self.m + i for i in matrix]
for i in range(self.n * 2 - 1, -1, -1):
for j in range(self.m - 1, -1, -1):
... | 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: None"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k_train_033787 | 2,243 | 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: None",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_019270 | 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: None
- 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: None
- def sumRegion(self, row... | 79591962f1e18c4c1f3e0da49c8f85748a5db52f | <|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: None"""
<|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]]"""
self.n = len(matrix)
if not self.n:
return
self.m = len(matrix[0])
self.tree = [[0] * 2 * self.m for _ in matrix] + [[0] * self.m + i for i in matrix]
for i in range(self.n * ... | the_stack_v2_python_sparse | leetcode/308_range_sum_query_2D_mutable/zkj_segment_tree.py | SuanFaRuoJi/coding_exercises | train | 5 | |
3b953875149dd9710aca7dac868373a618172a95 | [
"xx = np.vstack([x for i in range(N)]).T\nyy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T\nself._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)]",
"x = np.atleast_1d(x)\ns = np.vstack([curve(x, *args, **kwargs) for curve in self._splines])\nreturn (np.mean(s, axis=... | <|body_start_0|>
xx = np.vstack([x for i in range(N)]).T
yy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T
self._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)]
<|end_body_0|>
<|body_start_1|>
x = np.atleast_1d(x)
s = np.vstack([cur... | Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slower than a normal spline! | ErrorPropagationSpline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slowe... | stack_v2_sparse_classes_36k_train_033788 | 47,749 | permissive | [
{
"docstring": "See docstring for InterpolatedUnivariateSpline The parameter `N` gives the number of splines to generate for error propagation.",
"name": "__init__",
"signature": "def __init__(self, x, y, yerr, N=1000, *args, **kwargs)"
},
{
"docstring": "Get the spline value and uncertainty at ... | 2 | stack_v2_sparse_classes_30k_train_017076 | Implement the Python class `ErrorPropagationSpline` described below.
Class description:
Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates... | Implement the Python class `ErrorPropagationSpline` described below.
Class description:
Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates... | 8a9f00a6977dad8d4477eef1d664fd62e9ecab75 | <|skeleton|>
class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slowe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorPropagationSpline:
"""Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slower than a norm... | the_stack_v2_python_sparse | kglib/utils/HelperFunctions.py | kgullikson88/gullikson-scripts | train | 4 |
6f486f4ab46ccf2af6904f2b9c05f7314c2d73f6 | [
"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!')",
"conte... | <|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... | EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s). | EventListenerServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1... | stack_v2_sparse_classes_36k_train_033789 | 4,141 | permissive | [
{
"docstring": "Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediate tensors from a debugged graph being executed, which can be sent from DebugIdentity ops configured with grpc URLs. 2) GraphDefs of partition graphs, which can b... | 3 | null | Implement the Python class `EventListenerServicer` described below.
Class description:
EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).
Method signatures and docstrings:
- def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event... | Implement the Python class `EventListenerServicer` described below.
Class description:
EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s).
Method signatures and docstrings:
- def SendEvents(self, request_iterator, context): Client(s) can use this RPC method to send the EventListener Event... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventListenerServicer:
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow runtime(s)."""
def SendEvents(self, request_iterator, context):
"""Client(s) can use this RPC method to send the EventListener Event protos. The Event protos can hold information such as: 1) intermediat... | the_stack_v2_python_sparse | Keras_tensorflow_nightly/source2.7/tensorflow/core/debug/debug_service_pb2_grpc.py | ryfeus/lambda-packs | train | 1,283 |
f91716c61ac0259d4cc5530b872643e7c0b1e07a | [
"if FactoryPattern.check_status(username) == 'nouser':\n messages.error(request, 'No such Customer exists.')\nelse:\n with connection.cursor() as cursor:\n results = cursor.execute(\"DELETE FROM public.auth_user where username = '%s'\" % username)\n connection.commit()\n messages.success(requ... | <|body_start_0|>
if FactoryPattern.check_status(username) == 'nouser':
messages.error(request, 'No such Customer exists.')
else:
with connection.cursor() as cursor:
results = cursor.execute("DELETE FROM public.auth_user where username = '%s'" % username)
... | FactoryPattern | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryPattern:
def deletecustomer(request, username):
"""Delete the customer based on the Username and update the same in the DB"""
<|body_0|>
def enablecustomer(request, username):
"""Check whether the username is in disabled status to proceed with Enabling the cus... | stack_v2_sparse_classes_36k_train_033790 | 2,825 | no_license | [
{
"docstring": "Delete the customer based on the Username and update the same in the DB",
"name": "deletecustomer",
"signature": "def deletecustomer(request, username)"
},
{
"docstring": "Check whether the username is in disabled status to proceed with Enabling the customer based on the Username... | 4 | stack_v2_sparse_classes_30k_val_000024 | Implement the Python class `FactoryPattern` described below.
Class description:
Implement the FactoryPattern class.
Method signatures and docstrings:
- def deletecustomer(request, username): Delete the customer based on the Username and update the same in the DB
- def enablecustomer(request, username): Check whether ... | Implement the Python class `FactoryPattern` described below.
Class description:
Implement the FactoryPattern class.
Method signatures and docstrings:
- def deletecustomer(request, username): Delete the customer based on the Username and update the same in the DB
- def enablecustomer(request, username): Check whether ... | 86f39617d2c71c276deed60d8637e14ce3e5083f | <|skeleton|>
class FactoryPattern:
def deletecustomer(request, username):
"""Delete the customer based on the Username and update the same in the DB"""
<|body_0|>
def enablecustomer(request, username):
"""Check whether the username is in disabled status to proceed with Enabling the cus... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactoryPattern:
def deletecustomer(request, username):
"""Delete the customer based on the Username and update the same in the DB"""
if FactoryPattern.check_status(username) == 'nouser':
messages.error(request, 'No such Customer exists.')
else:
with connection.c... | the_stack_v2_python_sparse | Banker/View/factorydesignpattern_bankeradmin.py | MaduMitha-Ravi/Django-Banking-App | train | 0 | |
e7e58ee798184e27384cbf5291b785b151f5b413 | [
"ct = 0\nchunks = {}\nfor i, n in enumerate(nums):\n if n:\n ct += 1\n else:\n chunks[i - ct] = ct\n ct = 0\nreturn max((l + int(i + l < len(nums)) + chunks.get(i + l + 1, 0) for i, l in chunks.items()))",
"res = l = ct = 0\nfor r, num in enumerate(nums):\n if not num:\n ct +=... | <|body_start_0|>
ct = 0
chunks = {}
for i, n in enumerate(nums):
if n:
ct += 1
else:
chunks[i - ct] = ct
ct = 0
return max((l + int(i + l < len(nums)) + chunks.get(i + l + 1, 0) for i, l in chunks.items()))
<|end_bod... | @param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s"""
def findMaxConsecutiveOnes(self, nums):
"""DP using chunking: O(N) time O(N) space"""
<|body_0|>
def findMaxConsecutiveOnes(self, nums):
"""Two-p... | stack_v2_sparse_classes_36k_train_033791 | 989 | no_license | [
{
"docstring": "DP using chunking: O(N) time O(N) space",
"name": "findMaxConsecutiveOnes",
"signature": "def findMaxConsecutiveOnes(self, nums)"
},
{
"docstring": "Two-pointer: O(N) time O(1) space",
"name": "findMaxConsecutiveOnes",
"signature": "def findMaxConsecutiveOnes(self, nums)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
@param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): DP using chunking: O(N) time O(N) space
- def findMaxConsecutiveOn... | Implement the Python class `Solution` described below.
Class description:
@param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): DP using chunking: O(N) time O(N) space
- def findMaxConsecutiveOn... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Solution:
"""@param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s"""
def findMaxConsecutiveOnes(self, nums):
"""DP using chunking: O(N) time O(N) space"""
<|body_0|>
def findMaxConsecutiveOnes(self, nums):
"""Two-p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""@param nums: a list of integer @return: return a integer, denote the maximum number of consecutive 1s"""
def findMaxConsecutiveOnes(self, nums):
"""DP using chunking: O(N) time O(N) space"""
ct = 0
chunks = {}
for i, n in enumerate(nums):
if n:
... | the_stack_v2_python_sparse | 487.Max_Consecutive_Ones_II.py | welsny/solutions | train | 1 |
0be9499ef9674a05fdf0e4f206d5f952878cdc5a | [
"month = self.kwargs.get('month')\nyear = self.kwargs.get('year')\nday = self.kwargs.get('day')\nif month and year and day:\n date = datetime.date(year=int(year), month=int(month), day=int(day))\nelse:\n date = datetime.date.today()\nfor week in self._calendar.monthdatescalendar(date.year, date.month):\n i... | <|body_start_0|>
month = self.kwargs.get('month')
year = self.kwargs.get('year')
day = self.kwargs.get('day')
if month and year and day:
date = datetime.date(year=int(year), month=int(month), day=int(day))
else:
date = datetime.date.today()
for wee... | 週間カレンダーの機能を提供するMixin | WeekCalendarMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeekCalendarMixin:
"""週間カレンダーの機能を提供するMixin"""
def get_week_days(self):
"""その週の日を全て返す"""
<|body_0|>
def get_week_calendar(self):
"""週間カレンダー情報の入った辞書を返す"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
month = self.kwargs.get('month')
year =... | stack_v2_sparse_classes_36k_train_033792 | 9,760 | permissive | [
{
"docstring": "その週の日を全て返す",
"name": "get_week_days",
"signature": "def get_week_days(self)"
},
{
"docstring": "週間カレンダー情報の入った辞書を返す",
"name": "get_week_calendar",
"signature": "def get_week_calendar(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020125 | Implement the Python class `WeekCalendarMixin` described below.
Class description:
週間カレンダーの機能を提供するMixin
Method signatures and docstrings:
- def get_week_days(self): その週の日を全て返す
- def get_week_calendar(self): 週間カレンダー情報の入った辞書を返す | Implement the Python class `WeekCalendarMixin` described below.
Class description:
週間カレンダーの機能を提供するMixin
Method signatures and docstrings:
- def get_week_days(self): その週の日を全て返す
- def get_week_calendar(self): 週間カレンダー情報の入った辞書を返す
<|skeleton|>
class WeekCalendarMixin:
"""週間カレンダーの機能を提供するMixin"""
def get_week_days... | 46d66f0c1cc479b70111754e2b49ad601e7be108 | <|skeleton|>
class WeekCalendarMixin:
"""週間カレンダーの機能を提供するMixin"""
def get_week_days(self):
"""その週の日を全て返す"""
<|body_0|>
def get_week_calendar(self):
"""週間カレンダー情報の入った辞書を返す"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeekCalendarMixin:
"""週間カレンダーの機能を提供するMixin"""
def get_week_days(self):
"""その週の日を全て返す"""
month = self.kwargs.get('month')
year = self.kwargs.get('year')
day = self.kwargs.get('day')
if month and year and day:
date = datetime.date(year=int(year), month=in... | the_stack_v2_python_sparse | smarm.com/wakeup/mixins.py | jphacks/E_2002 | train | 1 |
005213e4ea10be41792854becc2956c5004be635 | [
"SplitFeaturewiseMeasure.__init__(self, sensana, splitter, combiner=N.array, **kwargs)\nself.__noise_level = noise_level\n'Output of the sensitivity analyzer when there is no signal.'",
"maps = SplitFeaturewiseMeasure._call(self, dataset)\nm = N.mean(maps, axis=0)\nv = N.var(maps, axis=0)\ndf = maps.shape[0] - 1\... | <|body_start_0|>
SplitFeaturewiseMeasure.__init__(self, sensana, splitter, combiner=N.array, **kwargs)
self.__noise_level = noise_level
'Output of the sensitivity analyzer when there is no signal.'
<|end_body_0|>
<|body_start_1|>
maps = SplitFeaturewiseMeasure._call(self, dataset)
... | `SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits. | TScoredFeaturewiseMeasure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TScoredFeaturewiseMeasure:
"""`SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits."""
def __init__(self, sensana, splitter, noise_level=0.0, **kwargs):
"""Cheap initialization. :Parameters: sensana : SensitivityAnalyzer that shall be run on the `Dat... | stack_v2_sparse_classes_36k_train_033793 | 5,848 | permissive | [
{
"docstring": "Cheap initialization. :Parameters: sensana : SensitivityAnalyzer that shall be run on the `Dataset` splits. splitter : Splitter used to split the `Dataset`. By convention the first dataset in the tuple returned by the splitter on each iteration is used to compute the sensitivity map. noise_level... | 2 | stack_v2_sparse_classes_30k_train_014636 | Implement the Python class `TScoredFeaturewiseMeasure` described below.
Class description:
`SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits.
Method signatures and docstrings:
- def __init__(self, sensana, splitter, noise_level=0.0, **kwargs): Cheap initialization. :Parameters: se... | Implement the Python class `TScoredFeaturewiseMeasure` described below.
Class description:
`SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits.
Method signatures and docstrings:
- def __init__(self, sensana, splitter, noise_level=0.0, **kwargs): Cheap initialization. :Parameters: se... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class TScoredFeaturewiseMeasure:
"""`SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits."""
def __init__(self, sensana, splitter, noise_level=0.0, **kwargs):
"""Cheap initialization. :Parameters: sensana : SensitivityAnalyzer that shall be run on the `Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TScoredFeaturewiseMeasure:
"""`SplitFeaturewiseMeasure` computing featurewise t-score of sensitivities across splits."""
def __init__(self, sensana, splitter, noise_level=0.0, **kwargs):
"""Cheap initialization. :Parameters: sensana : SensitivityAnalyzer that shall be run on the `Dataset` splits.... | the_stack_v2_python_sparse | mvpa/measures/splitmeasure.py | gorlins/PyMVPA | train | 0 |
53c915539e58e2e50d7efc0cec9cb7e7344b37b2 | [
"self.fds = fds\nself.polling = select.poll()\nfor fd in fds:\n self.polling.register(fd, select.POLLIN)",
"for fd in fds:\n self.polling.unregister(fd)\n self.fds.remove(fd)",
"changed = self.polling.poll(timeout * 1000)\nfor fd, event in changed:\n log.debug('event on fd %i is %#o', fd, event)\n ... | <|body_start_0|>
self.fds = fds
self.polling = select.poll()
for fd in fds:
self.polling.register(fd, select.POLLIN)
<|end_body_0|>
<|body_start_1|>
for fd in fds:
self.polling.unregister(fd)
self.fds.remove(fd)
<|end_body_1|>
<|body_start_2|>
... | Read from file descriptors with timeout. | PollingReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PollingReader:
"""Read from file descriptors with timeout."""
def __init__(self, fds):
"""Initialize."""
<|body_0|>
def unregister(self, fds):
"""Unregister descriptors."""
<|body_1|>
def read(self, timeout=-1):
"""Read with an optional timeo... | stack_v2_sparse_classes_36k_train_033794 | 8,473 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, fds)"
},
{
"docstring": "Unregister descriptors.",
"name": "unregister",
"signature": "def unregister(self, fds)"
},
{
"docstring": "Read with an optional timeout.",
"name": "read",
"signat... | 3 | null | Implement the Python class `PollingReader` described below.
Class description:
Read from file descriptors with timeout.
Method signatures and docstrings:
- def __init__(self, fds): Initialize.
- def unregister(self, fds): Unregister descriptors.
- def read(self, timeout=-1): Read with an optional timeout. | Implement the Python class `PollingReader` described below.
Class description:
Read from file descriptors with timeout.
Method signatures and docstrings:
- def __init__(self, fds): Initialize.
- def unregister(self, fds): Unregister descriptors.
- def read(self, timeout=-1): Read with an optional timeout.
<|skeleton... | 79e5ac3a6f267dcdc2179fc1a7c49504bafb6e0f | <|skeleton|>
class PollingReader:
"""Read from file descriptors with timeout."""
def __init__(self, fds):
"""Initialize."""
<|body_0|>
def unregister(self, fds):
"""Unregister descriptors."""
<|body_1|>
def read(self, timeout=-1):
"""Read with an optional timeo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PollingReader:
"""Read from file descriptors with timeout."""
def __init__(self, fds):
"""Initialize."""
self.fds = fds
self.polling = select.poll()
for fd in fds:
self.polling.register(fd, select.POLLIN)
def unregister(self, fds):
"""Unregister de... | the_stack_v2_python_sparse | src/python/cargo/unix/accounting.py | borg-project/cargo | train | 1 |
36bea736905f0277ad12805247592c226c75f683 | [
"if not root:\n return ''\ncur_list = [root]\nval_list = [str(root.val)]\nwhile len(cur_list):\n pointer = cur_list.pop(0)\n if pointer.left:\n cur_list.append(pointer.left)\n val_list.append(str(pointer.left.val))\n else:\n val_list.append('NA')\n if pointer.right:\n cur_... | <|body_start_0|>
if not root:
return ''
cur_list = [root]
val_list = [str(root.val)]
while len(cur_list):
pointer = cur_list.pop(0)
if pointer.left:
cur_list.append(pointer.left)
val_list.append(str(pointer.left.val))
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033795 | 3,830 | 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_014565 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9387c1cbf1cac2db1aebf5ad196230705ab0fcc7 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_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"""
if not root:
return ''
cur_list = [root]
val_list = [str(root.val)]
while len(cur_list):
pointer = cur_list.pop(0)
if pointer.... | the_stack_v2_python_sparse | serialize_and_deserialize_binary_tree.py | lightening0907/algorithm | train | 0 | |
cf451ca487aad058e094699c4823c50274f84efb | [
"self._context = context or google.datalab.Context.default()\nself._client = _utils.make_client(self._context)\nself._group_dict = None",
"if self._group_dict is None:\n self._group_dict = collections.OrderedDict(((group.name, group) for group in self._client.list_groups()))\nreturn [group for group in self._g... | <|body_start_0|>
self._context = context or google.datalab.Context.default()
self._client = _utils.make_client(self._context)
self._group_dict = None
<|end_body_0|>
<|body_start_1|>
if self._group_dict is None:
self._group_dict = collections.OrderedDict(((group.name, group) ... | Represents a list of Stackdriver groups for a project. | Groups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Groups:
"""Represents a list of Stackdriver groups for a project."""
def __init__(self, context=None):
"""Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global default."""
<|body_0|>
def list(self, patter... | stack_v2_sparse_classes_36k_train_033796 | 2,940 | permissive | [
{
"docstring": "Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global default.",
"name": "__init__",
"signature": "def __init__(self, context=None)"
},
{
"docstring": "Returns a list of groups that match the filters. Args: patter... | 3 | stack_v2_sparse_classes_30k_train_005852 | Implement the Python class `Groups` described below.
Class description:
Represents a list of Stackdriver groups for a project.
Method signatures and docstrings:
- def __init__(self, context=None): Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global ... | Implement the Python class `Groups` described below.
Class description:
Represents a list of Stackdriver groups for a project.
Method signatures and docstrings:
- def __init__(self, context=None): Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global ... | 8bf007da3e43096aa3a3dca158fc56b286ba6f5c | <|skeleton|>
class Groups:
"""Represents a list of Stackdriver groups for a project."""
def __init__(self, context=None):
"""Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global default."""
<|body_0|>
def list(self, patter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Groups:
"""Represents a list of Stackdriver groups for a project."""
def __init__(self, context=None):
"""Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global default."""
self._context = context or google.datalab.Context.... | the_stack_v2_python_sparse | google/datalab/stackdriver/monitoring/_group.py | googledatalab/pydatalab | train | 200 |
056629e6cace475c5b447e2e7bea8e4c6dcb8b19 | [
"assert elem_size > 0, elem_size\nassert elem_count > 0, elem_count\nself.elem_size = elem_size\nself.elem_count = elem_count\nself.buffer = bytearray(elem_size * elem_count)\nself.used = 0",
"if self.used < 1:\n return None\nself.used -= 1\ni = self.used\nreturn self.buffer[i * self.elem_size:(i + 1) * self.e... | <|body_start_0|>
assert elem_size > 0, elem_size
assert elem_count > 0, elem_count
self.elem_size = elem_size
self.elem_count = elem_count
self.buffer = bytearray(elem_size * elem_count)
self.used = 0
<|end_body_0|>
<|body_start_1|>
if self.used < 1:
... | ShuffleBuffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShuffleBuffer:
def __init__(self, elem_size, elem_count):
"""A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' bytes."""
<|body_0|>
def extract(self):
"""Return an item from the shuffle buffer... | stack_v2_sparse_classes_36k_train_033797 | 4,461 | no_license | [
{
"docstring": "A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' bytes.",
"name": "__init__",
"signature": "def __init__(self, elem_size, elem_count)"
},
{
"docstring": "Return an item from the shuffle buffer. If the buf... | 3 | stack_v2_sparse_classes_30k_val_000307 | Implement the Python class `ShuffleBuffer` described below.
Class description:
Implement the ShuffleBuffer class.
Method signatures and docstrings:
- def __init__(self, elem_size, elem_count): A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' ... | Implement the Python class `ShuffleBuffer` described below.
Class description:
Implement the ShuffleBuffer class.
Method signatures and docstrings:
- def __init__(self, elem_size, elem_count): A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' ... | 44fc71f8f03a00b11431fbc3d937f071317ac3db | <|skeleton|>
class ShuffleBuffer:
def __init__(self, elem_size, elem_count):
"""A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' bytes."""
<|body_0|>
def extract(self):
"""Return an item from the shuffle buffer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShuffleBuffer:
def __init__(self, elem_size, elem_count):
"""A shuffle buffer for fixed sized elements. Manages 'elem_count' items in a fixed buffer, each item being exactly 'elem_size' bytes."""
assert elem_size > 0, elem_size
assert elem_count > 0, elem_count
self.elem_size =... | the_stack_v2_python_sparse | tf/shufflebuffer.py | ScallyBag/lczero-training | train | 2 | |
16729f3a38b91c6e75c33555acb2b2a9eb74db9f | [
"sources = db_session.query(models.Sources).all()\nresults = [service_detail_from_source(source) for source in sources]\nreturn results",
"variables = db_session.query(models.Variables).all()\nresults = [parameter_info_from_variable(variable) for variable in variables]\nreturn results",
"variable = db_session.q... | <|body_start_0|>
sources = db_session.query(models.Sources).all()
results = [service_detail_from_source(source) for source in sources]
return results
<|end_body_0|>
<|body_start_1|>
variables = db_session.query(models.Variables).all()
results = [parameter_info_from_variable(vari... | CentralRegistryService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CentralRegistryService:
def GetSourcesGEMSS(self):
"""Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @param the number of times to say hello @return the completed array"""
<|body_0|>
def GetTXHISParamet... | stack_v2_sparse_classes_36k_train_033798 | 5,465 | no_license | [
{
"docstring": "Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @param the number of times to say hello @return the completed array",
"name": "GetSourcesGEMSS",
"signature": "def GetSourcesGEMSS(self)"
},
{
"docstring": "Doc... | 4 | stack_v2_sparse_classes_30k_train_011997 | Implement the Python class `CentralRegistryService` described below.
Class description:
Implement the CentralRegistryService class.
Method signatures and docstrings:
- def GetSourcesGEMSS(self): Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @pa... | Implement the Python class `CentralRegistryService` described below.
Class description:
Implement the CentralRegistryService class.
Method signatures and docstrings:
- def GetSourcesGEMSS(self): Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @pa... | bc2e2bc0a347599a5dee127be9d03d6d082e7001 | <|skeleton|>
class CentralRegistryService:
def GetSourcesGEMSS(self):
"""Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @param the number of times to say hello @return the completed array"""
<|body_0|>
def GetTXHISParamet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CentralRegistryService:
def GetSourcesGEMSS(self):
"""Docstrings for service methods appear as documentation in the wsdl <b>what fun</b> @param name the name to say hello to @param the number of times to say hello @return the completed array"""
sources = db_session.query(models.Sources).all()
... | the_stack_v2_python_sparse | wdft_central/wdft_central/service.py | twdb/txhis | train | 0 | |
83bde25c6618f933d4026a8c091850c2fd9ee257 | [
"params = kwarg['params']\ncmd = '/lib/platform-config/current/onl/bin/onlpdump -S'\nreturn cmd",
"sfps_info = []\nrecord = output\nif '\\\\n' in record:\n records = record.split('\\\\n')[:-1]\nelse:\n records = record.split('\\n')[:-1]\nsfp = {}\nkeys = RE_SPACES.sub(' ', records[0].lower()).strip().split(... | <|body_start_0|>
params = kwarg['params']
cmd = '/lib/platform-config/current/onl/bin/onlpdump -S'
return cmd
<|end_body_0|>
<|body_start_1|>
sfps_info = []
record = output
if '\\n' in record:
records = record.split('\\n')[:-1]
else:
recor... | ONLP SFP details by running onlpdump -S | LinuxOnlpSfpInfoImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinuxOnlpSfpInfoImpl:
"""ONLP SFP details by running onlpdump -S"""
def format_show(self, command, *argv, **kwarg):
"""Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- ---------------- ---------------- 49 10GBASE-CR Copper 2m FS SFP... | stack_v2_sparse_classes_36k_train_033799 | 2,109 | permissive | [
{
"docstring": "Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- ---------------- ---------------- 49 10GBASE-CR Copper 2m FS SFP-10G-DAC G1807081119-1 50 10GBASE-CR Copper 1m FCI Electronics 10110818-2010LF 0009",
"name": "format_show",
"signature": "... | 2 | null | Implement the Python class `LinuxOnlpSfpInfoImpl` described below.
Class description:
ONLP SFP details by running onlpdump -S
Method signatures and docstrings:
- def format_show(self, command, *argv, **kwarg): Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- -------... | Implement the Python class `LinuxOnlpSfpInfoImpl` described below.
Class description:
ONLP SFP details by running onlpdump -S
Method signatures and docstrings:
- def format_show(self, command, *argv, **kwarg): Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- -------... | e4c8221e18cd94e7424c30e12eb0fb82f7767267 | <|skeleton|>
class LinuxOnlpSfpInfoImpl:
"""ONLP SFP details by running onlpdump -S"""
def format_show(self, command, *argv, **kwarg):
"""Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- ---------------- ---------------- 49 10GBASE-CR Copper 2m FS SFP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinuxOnlpSfpInfoImpl:
"""ONLP SFP details by running onlpdump -S"""
def format_show(self, command, *argv, **kwarg):
"""Port Type Media Status Len Vendor Model S/N ---- -------------- ------ ------ ----- ---------------- ---------------- ---------------- 49 10GBASE-CR Copper 2m FS SFP-10G-DAC G180... | the_stack_v2_python_sparse | Amazon_Framework/DentOsTestbedLib/src/dent_os_testbed/lib/onlp/linux/linux_onlp_sfp_info_impl.py | tld3daniel/testing | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.