blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
040cac117559b65f873a0d687f0241cdd66465f6 | [
"left = []\nmaxv = 0\nv = [(-1, -2)]\nfor j, pt in enumerate(s):\n if pt == '(':\n left.append(j)\n if pt == ')' and left:\n l = left.pop()\n r = j\n pl, pr = v[-1]\n if r > pr and l < pl:\n v.pop()\n if l == v[-1][1] + 1:\n l = v[-1][0]\n ... | <|body_start_0|>
left = []
maxv = 0
v = [(-1, -2)]
for j, pt in enumerate(s):
if pt == '(':
left.append(j)
if pt == ')' and left:
l = left.pop()
r = j
pl, pr = v[-1]
if r > pr and l < ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = []
maxv = 0
v = [(-1,... | stack_v2_sparse_classes_10k_train_005800 | 1,288 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses1",
"signature": "def longestValidParentheses1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006753 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestVal... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
left = []
maxv = 0
v = [(-1, -2)]
for j, pt in enumerate(s):
if pt == '(':
left.append(j)
if pt == ')' and left:
l = left.pop()
... | the_stack_v2_python_sparse | q32_Longest_Valid_Parentheses.py | Ryuya1995/leetcode | train | 0 | |
3bebf16c316320c3646a4f90dcb238cd5e8bd28c | [
"cpu_stats = psutil.cpu_times_percent(percpu=False)\ncpu_stats_dict = {StatsKeys.CPU: {StatsKeys.IDLE: cpu_stats.idle, StatsKeys.SYSTEM: cpu_stats.system, StatsKeys.USER: cpu_stats.user, StatsKeys.COUNT: len(psutil.cpu_times(percpu=True))}}\nlogger.debug('CPU stats: {}'.format(cpu_stats_dict))\nreturn cpu_stats_dic... | <|body_start_0|>
cpu_stats = psutil.cpu_times_percent(percpu=False)
cpu_stats_dict = {StatsKeys.CPU: {StatsKeys.IDLE: cpu_stats.idle, StatsKeys.SYSTEM: cpu_stats.system, StatsKeys.USER: cpu_stats.user, StatsKeys.COUNT: len(psutil.cpu_times(percpu=True))}}
logger.debug('CPU stats: {}'.format(cpu_... | SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any. | SystemManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemManager:
"""SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any."""
def get_cpu_usage(cls):
"""Discovers CPU usage on this node. Retu... | stack_v2_sparse_classes_10k_train_005801 | 5,532 | permissive | [
{
"docstring": "Discovers CPU usage on this node. Returns: A dictionary containing the idle, system and user percentages.",
"name": "get_cpu_usage",
"signature": "def get_cpu_usage(cls)"
},
{
"docstring": "Discovers disk usage per mount point on this node. Returns: A dictionary containing free b... | 6 | stack_v2_sparse_classes_30k_train_003540 | Implement the Python class `SystemManager` described below.
Class description:
SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any.
Method signatures and docstrings:
- def g... | Implement the Python class `SystemManager` described below.
Class description:
SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any.
Method signatures and docstrings:
- def g... | 4940c719df1b50ad4af5af4adf675414e225e5a6 | <|skeleton|>
class SystemManager:
"""SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any."""
def get_cpu_usage(cls):
"""Discovers CPU usage on this node. Retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SystemManager:
"""SystemManager class is the entry point for queries regarding system stats. This service reports statistics about disk, memory and CPU usage, Monit summary, and number of running appservers, if any."""
def get_cpu_usage(cls):
"""Discovers CPU usage on this node. Returns: A dictio... | the_stack_v2_python_sparse | InfrastructureManager/appscale/infrastructure/system_manager.py | whoarethebritons/appscale | train | 0 |
4d4cc436fa8f2879a95af087499b7e241e0f9ae3 | [
"masks = {}\nfor (x, y), value in np.ndenumerate(mask_array):\n if value != 0:\n if value not in masks:\n masks[value] = np.zeros(mask_array.shape)\n dummy_array = masks[value]\n dummy_array[x, y] = 1\n masks[value] = dummy_array\nreturn masks",
"self.add_class('cells', 1... | <|body_start_0|>
masks = {}
for (x, y), value in np.ndenumerate(mask_array):
if value != 0:
if value not in masks:
masks[value] = np.zeros(mask_array.shape)
dummy_array = masks[value]
dummy_array[x, y] = 1
ma... | Generates a cells dataset for training. Dataset consists of microscope images. | CellsDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array... | stack_v2_sparse_classes_10k_train_005802 | 15,173 | permissive | [
{
"docstring": "Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array: numpy array of size [H,W]. 0 represents the background. Any non zero integer represents a individual instance Returns: Mask dictionary {instance... | 5 | stack_v2_sparse_classes_30k_train_004549 | Implement the Python class `CellsDataset` described below.
Class description:
Generates a cells dataset for training. Dataset consists of microscope images.
Method signatures and docstrings:
- def generate_masks(mask_array): Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the va... | Implement the Python class `CellsDataset` described below.
Class description:
Generates a cells dataset for training. Dataset consists of microscope images.
Method signatures and docstrings:
- def generate_masks(mask_array): Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the va... | 2f825cbcba92ff2fdffac60de56604578f31e937 | <|skeleton|>
class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array: numpy array... | the_stack_v2_python_sparse | framework-nucleus-segmentation/mrcnn/samples/cell/cell.py | CBIIT/nci-hitif | train | 1 |
f019c4222049d7857e9a1f484e0e87656b0ea85c | [
"self.check_type = check_type\nself.result_type = result_type\nself.user_message = user_message",
"if dictionary is None:\n return None\ncheck_type = dictionary.get('checkType')\nresult_type = dictionary.get('resultType')\nuser_message = dictionary.get('userMessage')\nreturn cls(check_type, result_type, user_m... | <|body_start_0|>
self.check_type = check_type
self.result_type = result_type
self.user_message = user_message
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
check_type = dictionary.get('checkType')
result_type = dictionary.get('resultType'... | Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies the type of the host check performed internally. 'kIsAgentPortAccessible' indicates the chec... | HostSettingsCheckResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostSettingsCheckResult:
"""Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies the type of the host check performed inte... | stack_v2_sparse_classes_10k_train_005803 | 3,246 | permissive | [
{
"docstring": "Constructor for the HostSettingsCheckResult class",
"name": "__init__",
"signature": "def __init__(self, check_type=None, result_type=None, user_message=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repre... | 2 | null | Implement the Python class `HostSettingsCheckResult` described below.
Class description:
Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies th... | Implement the Python class `HostSettingsCheckResult` described below.
Class description:
Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HostSettingsCheckResult:
"""Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies the type of the host check performed inte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HostSettingsCheckResult:
"""Implementation of the 'HostSettingsCheckResult' model. Specifies the result of various checks performed internally on host. Attributes: check_type (CheckTypeEnum): Specifies the type of the check internally performed. Specifies the type of the host check performed internally. 'kIsA... | the_stack_v2_python_sparse | cohesity_management_sdk/models/host_settings_check_result.py | cohesity/management-sdk-python | train | 24 |
318101eff679c209f53cd1c542452e51b3cd0b3d | [
"self._command = None\nif 'command' in kw:\n self._command = kw.pop('command')\nkw['command'] = self.choosecolour\n_style = 'TButton'\nif 'style' in kw:\n _style = kw.pop('style')\nself._style = 'CB%i.%s' % (len(self._instance_styles), _style)\nkw['style'] = self._style\nttk.Button.__init__(self, master, **kw... | <|body_start_0|>
self._command = None
if 'command' in kw:
self._command = kw.pop('command')
kw['command'] = self.choosecolour
_style = 'TButton'
if 'style' in kw:
_style = kw.pop('style')
self._style = 'CB%i.%s' % (len(self._instance_styles), _styl... | Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face | ColourTtkButton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name t... | stack_v2_sparse_classes_10k_train_005804 | 3,242 | permissive | [
{
"docstring": "provide a name to save between script runs. a command callback can be provided.",
"name": "__init__",
"signature": "def __init__(self, master, **kw)"
},
{
"docstring": "invoked when button pushed to prompt user to select a colour",
"name": "choosecolour",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_007158 | Implement the Python class `ColourTtkButton` described below.
Class description:
Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face
Method signatures and docstri... | Implement the Python class `ColourTtkButton` described below.
Class description:
Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face
Method signatures and docstri... | c4e178b33f24e609c812b20bddfff7448782a192 | <|skeleton|>
class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name to save betwee... | the_stack_v2_python_sparse | memtkinter/megawidgets/colourbutton.py | JamesGKent/memtkinter | train | 0 |
de250f911303a04e513d36855fb60a2bf0e3338c | [
"n = len(graph)\ng = [[float('inf')] * n for _ in range(n)]\nfor i, js in enumerate(graph):\n for j in js:\n g[i][j] = 1\nfor k in range(n):\n for i in range(n):\n for j in range(n):\n if i == j:\n g[i][j] = 0\n else:\n g[i][j] = min(g[i][j], g... | <|body_start_0|>
n = len(graph)
g = [[float('inf')] * n for _ in range(n)]
for i, js in enumerate(graph):
for j in js:
g[i][j] = 1
for k in range(n):
for i in range(n):
for j in range(n):
if i == j:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
"""1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse distance Time complexity: O(n^3) (max of FW and n times of DFS) Floyd-Warshall: O(n^3) DFS: O(V+E) ... | stack_v2_sparse_classes_10k_train_005805 | 3,565 | no_license | [
{
"docstring": "1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse distance Time complexity: O(n^3) (max of FW and n times of DFS) Floyd-Warshall: O(n^3) DFS: O(V+E) = O(n + n^2) Space complexity: O(n*2^n)",
"name": "shortestPathLength",
"s... | 2 | stack_v2_sparse_classes_30k_train_000818 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPathLength(self, graph: List[List[int]]) -> int: 1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse di... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPathLength(self, graph: List[List[int]]) -> int: 1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse di... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
"""1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse distance Time complexity: O(n^3) (max of FW and n times of DFS) Floyd-Warshall: O(n^3) DFS: O(V+E) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
"""1. Convert the graph to a bidirectional weighted graph whose all pairs are connected 2. Return the minium traverse distance Time complexity: O(n^3) (max of FW and n times of DFS) Floyd-Warshall: O(n^3) DFS: O(V+E) = O(n + n^2) S... | the_stack_v2_python_sparse | leetcode/solved/877_Shortest_Path_Visiting_All_Nodes/solution.py | sungminoh/algorithms | train | 0 | |
3085c74c4ec045d8afd05324f7931e3155871a40 | [
"parser.add_argument('-show', dest='show', type=bool, default=True, help='show all the entries in category')\nparser.add_argument('-add', '--a', dest='add', type=str, help=\"Add a new category if it's possible\")\nparser.add_argument('-delete', '--d', dest='del', type=str, help=\"Delete a category if it's possible\... | <|body_start_0|>
parser.add_argument('-show', dest='show', type=bool, default=True, help='show all the entries in category')
parser.add_argument('-add', '--a', dest='add', type=str, help="Add a new category if it's possible")
parser.add_argument('-delete', '--d', dest='del', type=str, help="Dele... | this class manages the parameters you can pass to python manage.py | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""this class manages the parameters you can pass to python manage.py"""
def add_arguments(self, parser):
"""manages the args to pass to category"""
<|body_0|>
def _show(self):
"""shows the cat from the list"""
<|body_1|>
def _add(self, new_... | stack_v2_sparse_classes_10k_train_005806 | 3,635 | no_license | [
{
"docstring": "manages the args to pass to category",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "shows the cat from the list",
"name": "_show",
"signature": "def _show(self)"
},
{
"docstring": "add a category to the list if it exis... | 5 | stack_v2_sparse_classes_30k_train_001872 | Implement the Python class `Command` described below.
Class description:
this class manages the parameters you can pass to python manage.py
Method signatures and docstrings:
- def add_arguments(self, parser): manages the args to pass to category
- def _show(self): shows the cat from the list
- def _add(self, new_cat)... | Implement the Python class `Command` described below.
Class description:
this class manages the parameters you can pass to python manage.py
Method signatures and docstrings:
- def add_arguments(self, parser): manages the args to pass to category
- def _show(self): shows the cat from the list
- def _add(self, new_cat)... | 378244474186a2fe25f91377f3628a1479329f99 | <|skeleton|>
class Command:
"""this class manages the parameters you can pass to python manage.py"""
def add_arguments(self, parser):
"""manages the args to pass to category"""
<|body_0|>
def _show(self):
"""shows the cat from the list"""
<|body_1|>
def _add(self, new_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""this class manages the parameters you can pass to python manage.py"""
def add_arguments(self, parser):
"""manages the args to pass to category"""
parser.add_argument('-show', dest='show', type=bool, default=True, help='show all the entries in category')
parser.add_argu... | the_stack_v2_python_sparse | products/management/commands/category.py | blingstand/projet8 | train | 0 |
760b969fe36b47e6d3ed46d2248849b5cf74baaf | [
"with sqlite3.connect('example.db') as conn:\n c = conn.cursor()\n try:\n c.execute('create table stocks\\n (date text, trans text, symbol text, qty real, price real)')\n except sqlite3.OperationalError:\n pass\n timestamp = time()\n date = datetime.fromtimestamp(timestamp).str... | <|body_start_0|>
with sqlite3.connect('example.db') as conn:
c = conn.cursor()
try:
c.execute('create table stocks\n (date text, trans text, symbol text, qty real, price real)')
except sqlite3.OperationalError:
pass
timesta... | A simplified class to buy stock in Amazon | Amazon | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Amazon:
"""A simplified class to buy stock in Amazon"""
def buy_amazon(self, quantity, purchase_price):
"""Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s... | stack_v2_sparse_classes_10k_train_005807 | 2,429 | no_license | [
{
"docstring": "Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were purchased",
"name": "buy_amazon",
"signature": "def buy_amazon(self, quantity, purchase_price)"
},... | 4 | stack_v2_sparse_classes_30k_train_005619 | Implement the Python class `Amazon` described below.
Class description:
A simplified class to buy stock in Amazon
Method signatures and docstrings:
- def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p... | Implement the Python class `Amazon` described below.
Class description:
A simplified class to buy stock in Amazon
Method signatures and docstrings:
- def buy_amazon(self, quantity, purchase_price): Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to p... | fb2d1a903fd287e0dbc963963f322eccdc1546bb | <|skeleton|>
class Amazon:
"""A simplified class to buy stock in Amazon"""
def buy_amazon(self, quantity, purchase_price):
"""Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Amazon:
"""A simplified class to buy stock in Amazon"""
def buy_amazon(self, quantity, purchase_price):
"""Allows a user to purchase Amazon stock Method arguments ---------------- quantity -- (integer) The number of stocks to purchase purchase_price -- (real) The price at which the stocks were pu... | the_stack_v2_python_sparse | NSS/practice/python_and_sql/amazon.py | megducharme/Python_Exercises | train | 0 |
06168fde5d6f3b95bf8e9547aaf02cd0d350bfb3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AttendanceRecord()",
"from .attendance_interval import AttendanceInterval\nfrom .entity import Entity\nfrom .identity import Identity\nfrom .attendance_interval import AttendanceInterval\nfrom .entity import Entity\nfrom .identity impo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AttendanceRecord()
<|end_body_0|>
<|body_start_1|>
from .attendance_interval import AttendanceInterval
from .entity import Entity
from .identity import Identity
from .att... | AttendanceRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttendanceRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttendanceRecord:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k_train_005808 | 3,500 | 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: AttendanceRecord",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_004717 | Implement the Python class `AttendanceRecord` described below.
Class description:
Implement the AttendanceRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttendanceRecord: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `AttendanceRecord` described below.
Class description:
Implement the AttendanceRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttendanceRecord: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AttendanceRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttendanceRecord:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttendanceRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttendanceRecord:
"""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: Attend... | the_stack_v2_python_sparse | msgraph/generated/models/attendance_record.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
dd3667b8278cde9b75c7b766a3e77aa47b0409e9 | [
"self.id = id\nself.is_max_snapshots_config_enabled = is_max_snapshots_config_enabled\nself.is_max_space_config_enabled = is_max_space_config_enabled\nself.max_snapshot_config = max_snapshot_config\nself.max_space_config = max_space_config",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nis_... | <|body_start_0|>
self.id = id
self.is_max_snapshots_config_enabled = is_max_snapshots_config_enabled
self.is_max_space_config_enabled = is_max_space_config_enabled
self.max_snapshot_config = max_snapshot_config
self.max_space_config = max_space_config
<|end_body_0|>
<|body_start... | Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or not. is_max_space_c... | StorageArraySnapshotThrottlingPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorageArraySnapshotThrottlingPolicy:
"""Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled (bool): Specifies if the storage array... | stack_v2_sparse_classes_10k_train_005809 | 3,740 | permissive | [
{
"docstring": "Constructor for the StorageArraySnapshotThrottlingPolicy class",
"name": "__init__",
"signature": "def __init__(self, id=None, is_max_snapshots_config_enabled=None, is_max_space_config_enabled=None, max_snapshot_config=None, max_space_config=None)"
},
{
"docstring": "Creates an i... | 2 | stack_v2_sparse_classes_30k_train_007209 | Implement the Python class `StorageArraySnapshotThrottlingPolicy` described below.
Class description:
Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled... | Implement the Python class `StorageArraySnapshotThrottlingPolicy` described below.
Class description:
Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class StorageArraySnapshotThrottlingPolicy:
"""Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled (bool): Specifies if the storage array... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StorageArraySnapshotThrottlingPolicy:
"""Implementation of the 'StorageArraySnapshotThrottlingPolicy' model. TODO: type description here. Attributes: id (long|int): Specifies the volume id of the storage array snapshot config. is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max... | the_stack_v2_python_sparse | cohesity_management_sdk/models/storage_array_snapshot_throttling_policy.py | cohesity/management-sdk-python | train | 24 |
0c7c9de4560db0fccf184b397d08108338ce5e53 | [
"for meeting in self._parse_meetings(response, upcoming=True):\n yield meeting\nyield scrapy.Request('https://ssa42.org/minutes-of-meetings/', callback=self._parse_meetings)",
"today = datetime.now().replace(hour=0, minute=0)\nlast_year = today.replace(year=today.year - 1)\nfor item in response.css('article.en... | <|body_start_0|>
for meeting in self._parse_meetings(response, upcoming=True):
yield meeting
yield scrapy.Request('https://ssa42.org/minutes-of-meetings/', callback=self._parse_meetings)
<|end_body_0|>
<|body_start_1|>
today = datetime.now().replace(hour=0, minute=0)
last_ye... | ChiSsa42Spider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiSsa42Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_meetings(self, response, upcoming=False):
"""Parse meetings on upcom... | stack_v2_sparse_classes_10k_train_005810 | 3,867 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse meetings on upcoming and minutes pages",
"name": "_parse_meetin... | 5 | stack_v2_sparse_classes_30k_train_004680 | Implement the Python class `ChiSsa42Spider` described below.
Class description:
Implement the ChiSsa42Spider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _pars... | Implement the Python class `ChiSsa42Spider` described below.
Class description:
Implement the ChiSsa42Spider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _pars... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiSsa42Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_meetings(self, response, upcoming=False):
"""Parse meetings on upcom... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChiSsa42Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
for meeting in self._parse_meetings(response, upcoming=True):
yield meeting
yield scrapy.Request(... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_ssa_42.py | City-Bureau/city-scrapers | train | 308 | |
82662211c6a35edc85fbd4c5cb5e1b9f699d9bff | [
"_, accounts = BaseAccount.search()\nif ROLE_ADMIN not in session['user'].roles:\n accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))\nif accounts:\n return self.make_response({'message': None, 'accounts': [x.to_json(is_admin=ROLE_ADMIN in session['user'].roles or False) fo... | <|body_start_0|>
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))
if accounts:
return self.make_response({'message': None, 'accounts': [x.to_json(is_admin=... | AccountList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_0|>
def post(self):
"""Create a new account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
... | stack_v2_sparse_classes_10k_train_005811 | 9,518 | permissive | [
{
"docstring": "List all accounts",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new account",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000320 | Implement the Python class `AccountList` described below.
Class description:
Implement the AccountList class.
Method signatures and docstrings:
- def get(self): List all accounts
- def post(self): Create a new account | Implement the Python class `AccountList` described below.
Class description:
Implement the AccountList class.
Method signatures and docstrings:
- def get(self): List all accounts
- def post(self): Create a new account
<|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_... | 29a26c705381fdba3538b4efedb25b9e09b387ed | <|skeleton|>
class AccountList:
def get(self):
"""List all accounts"""
<|body_0|>
def post(self):
"""Create a new account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountList:
def get(self):
"""List all accounts"""
_, accounts = BaseAccount.search()
if ROLE_ADMIN not in session['user'].roles:
accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts))
if accounts:
return self.make_respon... | the_stack_v2_python_sparse | backend/cloud_inquisitor/plugins/views/accounts.py | RiotGames/cloud-inquisitor | train | 468 | |
cc4bada5b88553ed0a9586fcbd3f2b6f4cdea9bf | [
"super(Encoder, self).__init__()\ninitialW = chainer.initializers.Uniform if initialW is None else initialW\ninitial_bias = chainer.initializers.Uniform if initial_bias is None else initial_bias\nself.do_history_mask = False\nwith self.init_scope():\n self.conv_subsampling_factor = 1\n channels = 64\n if i... | <|body_start_0|>
super(Encoder, self).__init__()
initialW = chainer.initializers.Uniform if initialW is None else initialW
initial_bias = chainer.initializers.Uniform if initial_bias is None else initial_bias
self.do_history_mask = False
with self.init_scope():
self.c... | Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h ... | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidd... | stack_v2_sparse_classes_10k_train_005812 | 4,911 | permissive | [
{
"docstring": "Initialize Encoder. Args: idim (int): Input dimension. args (Namespace): Training config. initialW (int, optional): Initializer to initialize the weight. initial_bias (bool, optional): Initializer to initialize the bias.",
"name": "__init__",
"signature": "def __init__(self, idim, attent... | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer.... | Implement the Python class `Encoder` described below.
Class description:
Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer.... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidd... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a... | the_stack_v2_python_sparse | espnet/nets/chainer_backend/transformer/encoder.py | espnet/espnet | train | 7,242 |
e7d2f9012327c1c672276c1d1a029975a36b1f19 | [
"if self.attr_def.editable:\n self.make_edited(edited_state)\ncurrent_value = self.attribute.getvalue(acm_portfolio_swap)\nif self.attr_def.data_type == AttributeDefinition.BOOL_TYPE:\n bool_value = get_bool_value(str(current_value))\n set_checked_state(self.w_input, bool_value)\nelif is_choice_list(self.a... | <|body_start_0|>
if self.attr_def.editable:
self.make_edited(edited_state)
current_value = self.attribute.getvalue(acm_portfolio_swap)
if self.attr_def.data_type == AttributeDefinition.BOOL_TYPE:
bool_value = get_bool_value(str(current_value))
set_checked_stat... | A GUI representation of the portfolio-swap-based quirk attribute. | GUIPortfolioSwapQuirkAttribute | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUIPortfolioSwapQuirkAttribute:
"""A GUI representation of the portfolio-swap-based quirk attribute."""
def load_attribute(self, acm_portfolio_swap, edited_state=False):
"""Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap.... | stack_v2_sparse_classes_10k_train_005813 | 21,608 | no_license | [
{
"docstring": "Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap.",
"name": "load_attribute",
"signature": "def load_attribute(self, acm_portfolio_swap, edited_state=False)"
},
{
"docstring": "Make the portfolio-swap-based quirk's val... | 3 | null | Implement the Python class `GUIPortfolioSwapQuirkAttribute` described below.
Class description:
A GUI representation of the portfolio-swap-based quirk attribute.
Method signatures and docstrings:
- def load_attribute(self, acm_portfolio_swap, edited_state=False): Load the current value of the underlying portfolio-swa... | Implement the Python class `GUIPortfolioSwapQuirkAttribute` described below.
Class description:
A GUI representation of the portfolio-swap-based quirk attribute.
Method signatures and docstrings:
- def load_attribute(self, acm_portfolio_swap, edited_state=False): Load the current value of the underlying portfolio-swa... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class GUIPortfolioSwapQuirkAttribute:
"""A GUI representation of the portfolio-swap-based quirk attribute."""
def load_attribute(self, acm_portfolio_swap, edited_state=False):
"""Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GUIPortfolioSwapQuirkAttribute:
"""A GUI representation of the portfolio-swap-based quirk attribute."""
def load_attribute(self, acm_portfolio_swap, edited_state=False):
"""Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap."""
i... | the_stack_v2_python_sparse | Python modules/pb_gui_attribute.py | webclinic017/fa-absa-py3 | train | 0 |
446f93db141f6f425732417fb84e211bbd69465d | [
"super().__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.ffn = point_wise_feed_forward_network(dm, hidden)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.dropout1 = tf.keras.layers.Dropout(drop_rate)\nself.dropou... | <|body_start_0|>
super().__init__()
self.mha = MultiHeadAttention(dm, h)
self.ffn = point_wise_feed_forward_network(dm, hidden)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
self.dro... | class Encoder block | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public in... | stack_v2_sparse_classes_10k_train_005814 | 18,002 | no_license | [
{
"docstring": "* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attributes: * mha - a MultiHeadAttention layer * dense_hidden - the hidden dense layer with hidden... | 2 | stack_v2_sparse_classes_30k_train_007084 | Implement the Python class `EncoderBlock` described below.
Class description:
class Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * ... | Implement the Python class `EncoderBlock` described below.
Class description:
class Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * ... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""class Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attrib... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
670668abdddc2dd770e06293ba3a94900b38cf06 | [
"nd_names = states_df.columns\nord_nodes = [BayesNode(k, nd_names[k]) for k in range(len(nd_names))]\nbnet = BayesNet(set(ord_nodes))\nself.is_quantum = is_quantum\nself.bnet = bnet\nself.states_df = states_df\nself.ord_nodes = ord_nodes\nif not vtx_to_states:\n bnet.learn_nd_state_names(states_df)\nelse:\n b... | <|body_start_0|>
nd_names = states_df.columns
ord_nodes = [BayesNode(k, nd_names[k]) for k in range(len(nd_names))]
bnet = BayesNet(set(ord_nodes))
self.is_quantum = is_quantum
self.bnet = bnet
self.states_df = states_df
self.ord_nodes = ord_nodes
if not v... | Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn the structure of a net based on empirical data about states given in a pandas d... | NetStrucLner | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetStrucLner:
"""Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn the structure of a net based on empiric... | stack_v2_sparse_classes_10k_train_005815 | 3,273 | permissive | [
{
"docstring": "Constructor Parameters ---------- is_quantum : bool states_df : pandas.DataFrame vtx_to_states : dict[str, list[str]] A dictionary mapping each node name to a list of its state names. This information will be stored in self.bnet. If vtx_to_states=None, constructor will learn vtx_to_states from s... | 2 | stack_v2_sparse_classes_30k_train_002990 | Implement the Python class `NetStrucLner` described below.
Class description:
Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn ... | Implement the Python class `NetStrucLner` described below.
Class description:
Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn ... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class NetStrucLner:
"""Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn the structure of a net based on empiric... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetStrucLner:
"""Learning a Bayesian Network is usually done in two steps (1) learning the structure (i.e. the graph or skeleton) (2) learning the parameters ( i.e., the pots). NetStrucLner (Net Structure Learner) is a super class for all classes that learn the structure of a net based on empirical data about... | the_stack_v2_python_sparse | learning/NetStrucLner.py | artiste-qb-net/quantum-fog | train | 95 |
88d76a539b2cd4ad58c9520517732161b909e668 | [
"if uri == DOMAIN_UNIPROT:\n return KeywordType.DOMAIN\nelif uri == BIOLOGICAL_PROCESS_UNIPROT:\n return KeywordType.BIOLOGICAL_PROCESS\nelif uri == CELLULAR_COMPONENT_UNIPROT:\n return KeywordType.CELLULAR_COMPONENT\nelif uri == CODING_SEQUENCE_DIVERSITY_UNIPROT:\n return KeywordType.CODING_SEQUENCE_DI... | <|body_start_0|>
if uri == DOMAIN_UNIPROT:
return KeywordType.DOMAIN
elif uri == BIOLOGICAL_PROCESS_UNIPROT:
return KeywordType.BIOLOGICAL_PROCESS
elif uri == CELLULAR_COMPONENT_UNIPROT:
return KeywordType.CELLULAR_COMPONENT
elif uri == CODING_SEQUENCE... | Enum specifying the category of a Keyword. | KeywordType | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
<|body_0|>
def from_obo_ns(obo_namespace: str):
"""Helper function that retur... | stack_v2_sparse_classes_10k_train_005816 | 5,246 | permissive | [
{
"docstring": "Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.",
"name": "from_uniprot_uri",
"signature": "def from_uniprot_uri(uri: str)"
},
{
"docstring": "Helper function that returns a `KeywordType` (Keyword Category) from the Ontobee URL.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_003049 | Implement the Python class `KeywordType` described below.
Class description:
Enum specifying the category of a Keyword.
Method signatures and docstrings:
- def from_uniprot_uri(uri: str): Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.
- def from_obo_ns(obo_namespace: str): Helpe... | Implement the Python class `KeywordType` described below.
Class description:
Enum specifying the category of a Keyword.
Method signatures and docstrings:
- def from_uniprot_uri(uri: str): Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL.
- def from_obo_ns(obo_namespace: str): Helpe... | 40bab526af6562653c42dbb32b174524c44ce2ba | <|skeleton|>
class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
<|body_0|>
def from_obo_ns(obo_namespace: str):
"""Helper function that retur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeywordType:
"""Enum specifying the category of a Keyword."""
def from_uniprot_uri(uri: str):
"""Helper function that returns a `KeywordType` (Keyword Category) from the UniProt URL."""
if uri == DOMAIN_UNIPROT:
return KeywordType.DOMAIN
elif uri == BIOLOGICAL_PROCESS_... | the_stack_v2_python_sparse | PyStationB/libraries/UniProt/uniProt/keyword.py | mebristo/station-b-libraries | train | 0 |
ef67cb7ddd6a739eaf553b30cf2bfe82fc573c92 | [
"total_n = factorial(len(nums))\nresult = []\nperm_idxs = list(range(len(nums)))\nfor i in range(total_n):\n next_perm = [nums[i] for i in perm_idxs]\n result.append(next_perm)\n perm_idxs = self.next_permute(perm_idxs)\nreturn result",
"first_idx = len(nums) - 2\nsecond_idx = len(nums) - 1\nwhile first_... | <|body_start_0|>
total_n = factorial(len(nums))
result = []
perm_idxs = list(range(len(nums)))
for i in range(total_n):
next_perm = [nums[i] for i in perm_idxs]
result.append(next_perm)
perm_idxs = self.next_permute(perm_idxs)
return result
<|e... | Solution_B1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List[int]:
"""Herlper for B1, B2 From Leetcode LC0... | stack_v2_sparse_classes_10k_train_005817 | 5,911 | permissive | [
{
"docstring": "Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]",
"name": "permute",
"signature": "def permute(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new... | 2 | null | Implement the Python class `Solution_B1` described below.
Class description:
Implement the Solution_B1 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]
- def next_permute(self, num... | Implement the Python class `Solution_B1` described below.
Class description:
Implement the Solution_B1 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]
- def next_permute(self, num... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List[int]:
"""Herlper for B1, B2 From Leetcode LC0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
total_n = factorial(len(nums))
result = []
perm_idxs = list(range(len(nums)))
for i in range(total_n):
... | the_stack_v2_python_sparse | LeetCode/LC046_permutations.py | jxie0755/Learning_Python | train | 0 | |
2f581623e699f61794ce8bebce58ac1b5fd32d1b | [
"if not root:\n return ''\nstack, res = ([root], '')\nwhile stack:\n node = stack.pop()\n if node:\n tmp = str(node.val) + '!'\n stack.append(node.right)\n stack.append(node.left)\n else:\n tmp = '#!'\n res += tmp\nreturn res[:-1]",
"if not data:\n return None\nstore ... | <|body_start_0|>
if not root:
return ''
stack, res = ([root], '')
while stack:
node = stack.pop()
if node:
tmp = str(node.val) + '!'
stack.append(node.right)
stack.append(node.left)
else:
... | 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_10k_train_005818 | 2,501 | 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_003433 | 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:... | 507ed2efeff7818ca9cf53a8ee7fb80d3c530d67 | <|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_10k | 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 ''
stack, res = ([root], '')
while stack:
node = stack.pop()
if node:
tmp = str(node.val) + '!'
... | the_stack_v2_python_sparse | Leetcode/Tree/#449-Serialize and Deserialize BST/main.py | qizongjun/Algorithms-1 | train | 0 | |
7dce4b3c567b0d7994063c20572be4f103f2d391 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessReviewScheduleDefinition()",
"from .access_review_instance import AccessReviewInstance\nfrom .access_review_notification_recipient_item import AccessReviewNotificationRecipientItem\nfrom .access_review_reviewer_scope import Acces... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessReviewScheduleDefinition()
<|end_body_0|>
<|body_start_1|>
from .access_review_instance import AccessReviewInstance
from .access_review_notification_recipient_item import AccessRev... | AccessReviewScheduleDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessReviewScheduleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewScheduleDefinition:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k_train_005819 | 11,054 | 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: AccessReviewScheduleDefinition",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | stack_v2_sparse_classes_30k_train_001724 | Implement the Python class `AccessReviewScheduleDefinition` described below.
Class description:
Implement the AccessReviewScheduleDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewScheduleDefinition: Creates a new instance of... | Implement the Python class `AccessReviewScheduleDefinition` described below.
Class description:
Implement the AccessReviewScheduleDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewScheduleDefinition: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessReviewScheduleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewScheduleDefinition:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccessReviewScheduleDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewScheduleDefinition:
"""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 creat... | the_stack_v2_python_sparse | msgraph/generated/models/access_review_schedule_definition.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d4bcebc479d874819dcd1810a104354f9cc52b10 | [
"show_in_tkinter.__init__(self)\nif testing:\n self.books_names = None\n self.x = None\n self.y = None\n self.y_mean = None\n self.y_mean_c1 = None\n self.y_mean_c2 = None\n self.label = None\n self.asymmetric_y_error = None\n self._generate_sample_data()\nelse:\n self.books_names = bo... | <|body_start_0|>
show_in_tkinter.__init__(self)
if testing:
self.books_names = None
self.x = None
self.y = None
self.y_mean = None
self.y_mean_c1 = None
self.y_mean_c2 = None
self.label = None
self.asymmetric... | A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter. | Error_bar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Error_bar:
"""A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter."""
def __init__(self, books_names, x, y, y_mean, y_mean_c1, y_mean_c2, label: str, asymmetric_y_error: [[float]... | stack_v2_sparse_classes_10k_train_005820 | 4,519 | no_license | [
{
"docstring": "There is two ways to init, the default is receiving the data, and the other is generating random samples when testing is True (for testing purposes). Receive : books_names:[string] array of books names x: for book index or books names y: is the y value for the specific book y_mean: float the mea... | 5 | stack_v2_sparse_classes_30k_train_003472 | Implement the Python class `Error_bar` described below.
Class description:
A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter.
Method signatures and docstrings:
- def __init__(self, books_names, x, y, y_... | Implement the Python class `Error_bar` described below.
Class description:
A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter.
Method signatures and docstrings:
- def __init__(self, books_names, x, y, y_... | c7349dd0501e9a0d47a8f1024762ee15b225c6e0 | <|skeleton|>
class Error_bar:
"""A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter."""
def __init__(self, books_names, x, y, y_mean, y_mean_c1, y_mean_c2, label: str, asymmetric_y_error: [[float]... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Error_bar:
"""A Class that store and handle showing the data in Error bar graph of all the books . The Class extend show_in_tkinter Class to implement showing the graph in tkniter."""
def __init__(self, books_names, x, y, y_mean, y_mean_c1, y_mean_c2, label: str, asymmetric_y_error: [[float], [float]], t... | the_stack_v2_python_sparse | Show_results/Error_bar.py | saleems11/Final_Project_B | train | 0 |
0329b116613b73aa527f20fbdef65445aa406030 | [
"super(EncoderRNN, self).__init__()\nself.vocab_size = vocab_size\nself.embedding_size = embedding_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.dropout = dropout\nself.batch_first = batch_first\nself.bidirectional = bidirectional\nif bidirectional:\n self.num_directions = 2\nelse:\n ... | <|body_start_0|>
super(EncoderRNN, self).__init__()
self.vocab_size = vocab_size
self.embedding_size = embedding_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.dropout = dropout
self.batch_first = batch_first
self.bidirectional = bid... | EncoderRNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderRNN:
def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weights_matrix=None):
"""Sentence-level Encoder"""
<|body_0|>
def forward(self, inputs, input... | stack_v2_sparse_classes_10k_train_005821 | 8,492 | permissive | [
{
"docstring": "Sentence-level Encoder",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weights_matrix=None)"
},
{
"docstring": "Args: inpu... | 2 | stack_v2_sparse_classes_30k_train_004085 | Implement the Python class `EncoderRNN` described below.
Class description:
Implement the EncoderRNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weig... | Implement the Python class `EncoderRNN` described below.
Class description:
Implement the EncoderRNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weig... | 8851bbde8bedd0fe07beec72d74b3b3624c9c729 | <|skeleton|>
class EncoderRNN:
def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weights_matrix=None):
"""Sentence-level Encoder"""
<|body_0|>
def forward(self, inputs, input... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncoderRNN:
def __init__(self, vocab_size, embedding_size, hidden_size, rnn=nn.GRU, num_layers=1, bidirectional=False, dropout=0.0, bias=True, batch_first=True, train_emb=False, emb_weights_matrix=None):
"""Sentence-level Encoder"""
super(EncoderRNN, self).__init__()
self.vocab_size = ... | the_stack_v2_python_sparse | TL-ERC/bert_model/layer/encoder.py | declare-lab/conv-emotion | train | 791 | |
e3dc829c466922d1f15e0a197797c8dde2d4500f | [
"self.key2valfreq = {}\nself.count2node = defaultdict(OrderedDict)\nself.capacity = capacity\nself.min_freq = 1",
"if key not in self.key2valfreq:\n return -1\nval, freq = self.key2valfreq.pop(key)\nself.count2node[freq].pop(key)\nif len(self.count2node[freq]) == 0 and freq == self.min_freq:\n self.min_freq... | <|body_start_0|>
self.key2valfreq = {}
self.count2node = defaultdict(OrderedDict)
self.capacity = capacity
self.min_freq = 1
<|end_body_0|>
<|body_start_1|>
if key not in self.key2valfreq:
return -1
val, freq = self.key2valfreq.pop(key)
self.count2nod... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_005822 | 1,656 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_006632 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 2dde64842ecd73a581d7605d05a07fda4e3774bf | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.key2valfreq = {}
self.count2node = defaultdict(OrderedDict)
self.capacity = capacity
self.min_freq = 1
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.key... | the_stack_v2_python_sparse | Design/460.LFU_Cache/LFU_Cache.py | zach96guan/Stupid_LeetCoder | train | 8 | |
c20d2ccf360e6cb1a94ca8ae25e1b272f6706ba0 | [
"pygame.sprite.Sprite.__init__(self)\nself.image = pygame.image.load('Image/Trafico.png')\nself.rect = self.image.get_rect()\nself.image_orig = self.image\nself.speed = 2\nself.direction = angle\nself.steering = 90\nself.x = x\nself.y = y",
"self.direction = self.direction + self.steering\nif self.direction > 360... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Image/Trafico.png')
self.rect = self.image.get_rect()
self.image_orig = self.image
self.speed = 2
self.direction = angle
self.steering = 90
self.x = x
self.y = y
<... | Esta es la clase para los drones | Dummy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
<|body_0|>
def steerleft(self):
"""Giros hacia la izquierda"""
<|body_... | stack_v2_sparse_classes_10k_train_005823 | 2,190 | no_license | [
{
"docstring": "Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros",
"name": "__init__",
"signature": "def __init__(self, angle, x, y)"
},
{
"docstring": "Giros hacia la izquierda",
"name": "steerleft",
"signature": "def steerleft(self)"
... | 4 | stack_v2_sparse_classes_30k_train_002997 | Implement the Python class `Dummy` described below.
Class description:
Esta es la clase para los drones
Method signatures and docstrings:
- def __init__(self, angle, x, y): Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros
- def steerleft(self): Giros hacia la izquier... | Implement the Python class `Dummy` described below.
Class description:
Esta es la clase para los drones
Method signatures and docstrings:
- def __init__(self, angle, x, y): Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros
- def steerleft(self): Giros hacia la izquier... | b5c61e38224746fe4e9af65a7ef432aa4f431f29 | <|skeleton|>
class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
<|body_0|>
def steerleft(self):
"""Giros hacia la izquierda"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Image/Trafico.png')
... | the_stack_v2_python_sparse | Intro y Taller Progra- TEC/Proyectos/achacon-proyecto2/trafico.py | AdrChacon/ChaCa-Progra | train | 2 |
f83c5044464f3c76105c28de94fd65a88fac4c6e | [
"self.v_init = np.array([v_0 * np.cos(alpha_0), v_0 * np.sin(alpha_0)])\nself.r_init = np.array([x_init, y_init])\nself.delta = time\nself.gamma = gamma\nself.g = 9.81\nself.v_old = []\nself.v_new = []",
"fx = -self.gamma * v_vec[0]\nfy = -self.g - self.gamma * v_vec[1]\nreturn np.array([fx, fy])",
"fpx = self.... | <|body_start_0|>
self.v_init = np.array([v_0 * np.cos(alpha_0), v_0 * np.sin(alpha_0)])
self.r_init = np.array([x_init, y_init])
self.delta = time
self.gamma = gamma
self.g = 9.81
self.v_old = []
self.v_new = []
<|end_body_0|>
<|body_start_1|>
fx = -self.... | Euler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Euler:
def __init__(self, v_0, alpha_0, time, gamma=1, x_init=0, y_init=0):
"""@param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction coefficient @param x_init initial position (x-coorinate) @param y_init initial position (y_coo... | stack_v2_sparse_classes_10k_train_005824 | 4,088 | no_license | [
{
"docstring": "@param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction coefficient @param x_init initial position (x-coorinate) @param y_init initial position (y_coordinate)",
"name": "__init__",
"signature": "def __init__(self, v_0, alpha_0, t... | 4 | stack_v2_sparse_classes_30k_train_002810 | Implement the Python class `Euler` described below.
Class description:
Implement the Euler class.
Method signatures and docstrings:
- def __init__(self, v_0, alpha_0, time, gamma=1, x_init=0, y_init=0): @param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction ... | Implement the Python class `Euler` described below.
Class description:
Implement the Euler class.
Method signatures and docstrings:
- def __init__(self, v_0, alpha_0, time, gamma=1, x_init=0, y_init=0): @param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction ... | ef046c0f0219d805f1a529483820090a3f3e604e | <|skeleton|>
class Euler:
def __init__(self, v_0, alpha_0, time, gamma=1, x_init=0, y_init=0):
"""@param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction coefficient @param x_init initial position (x-coorinate) @param y_init initial position (y_coo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Euler:
def __init__(self, v_0, alpha_0, time, gamma=1, x_init=0, y_init=0):
"""@param v_0 initial velocity @param alpha_0 initial angel @param time size of the timesteps @param gamma=1 friction coefficient @param x_init initial position (x-coorinate) @param y_init initial position (y_coordinate)"""
... | the_stack_v2_python_sparse | ex10_baumgartner_marion/inclinedTrow.py | marionb/CompPhysics | train | 0 | |
e8c33b338d28408766bf49f47f6ccf72f4acebf5 | [
"cache_key = str(calendar_year)\nif cache_key not in UtilityFactorMethods._cache:\n start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])\n if len(start_years[start_years <= calendar_year]) > 0:\n calendar_year = max(start_years[start_years <= calendar_year])\n method = UtilityFa... | <|body_start_0|>
cache_key = str(calendar_year)
if cache_key not in UtilityFactorMethods._cache:
start_years = np.atleast_1d(UtilityFactorMethods._data['start_year'])
if len(start_years[start_years <= calendar_year]) > 0:
calendar_year = max(start_years[start_year... | **Loads and provides access to upstream calculation methods by start year.** | UtilityFactorMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_10k_train_005825 | 11,165 | no_license | [
{
"docstring": "Calculate \"city\" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled in charge-depleting driving, scalar or pandas Series Returns: A callable python function used to calculate upstream cert emissions for the given calendar ye... | 3 | stack_v2_sparse_classes_30k_train_005022 | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | Implement the Python class `UtilityFactorMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def calc_city_utility_factor(calendar_year, miles): Calculate "city" PHEV fleet utility factor Args: calendar_year (int... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: dista... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UtilityFactorMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def calc_city_utility_factor(calendar_year, miles):
"""Calculate "city" PHEV fleet utility factor Args: calendar_year (int): the calendar year to get the function for miles: distance travelled... | the_stack_v2_python_sparse | omega_model/policy/utility_factors.py | USEPA/EPA_OMEGA_Model | train | 17 |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(Conv1dStatic, self).__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.conv = nn.Conv1d(4 * in_channels, 4 * out_channels, kernel_size, stride, padding, dilation, 4 * groups, bias)",
"batch_size = x.shape[0]\nx = x.view(batch_size, 4 * self.in_channels, -1)\nx = self.conv(x)... | <|body_start_0|>
super(Conv1dStatic, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = nn.Conv1d(4 * in_channels, 4 * out_channels, kernel_size, stride, padding, dilation, 4 * groups, bias)
<|end_body_0|>
<|body_start_1|>
batch_size = x... | 1D convolution with an independent kernel for each instrument | Conv1dStatic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels ... | stack_v2_sparse_classes_10k_train_005826 | 37,269 | no_license | [
{
"docstring": "Arguments: in_channels {int} -- Number of channels of the input out_channels {int} -- Number of channels of the output kernel_size {int} -- Kernel size of the convolution Keyword Arguments: stride {int} -- Stride of the convolution (default: {1}) padding {int} -- Padding of the convolution (defa... | 2 | stack_v2_sparse_classes_30k_train_006189 | Implement the Python class `Conv1dStatic` described below.
Class description:
1D convolution with an independent kernel for each instrument
Method signatures and docstrings:
- def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): Arguments: in_channe... | Implement the Python class `Conv1dStatic` described below.
Class description:
1D convolution with an independent kernel for each instrument
Method signatures and docstrings:
- def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): Arguments: in_channe... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Conv1dStatic:
"""1D convolution with an independent kernel for each instrument"""
def __init__(self, _, __, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
"""Arguments: in_channels {int} -- Number of channels of the input out_channels {int} -- Numb... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
9ca24f0e1499c623fd774e66e967d1c854e0aff9 | [
"\"\"\"\n insert the tree..\n it has the links we dont have to link it again.\n \"\"\"\nself.list = []\nself.list.append(root)\nfor item in self.list:\n if item.left != None:\n self.list.append(item.left)\n if item.right != None:\n self.list.append(item.right)",
"\"\"\"\n ... | <|body_start_0|>
"""
insert the tree..
it has the links we dont have to link it again.
"""
self.list = []
self.list.append(root)
for item in self.list:
if item.left != None:
self.list.append(item.left)
... | CBTInserter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBTInserter:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def insert(self, v):
""":type v: int :rtype: int"""
<|body_1|>
def get_root(self):
""":rtype: TreeNode"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005827 | 2,522 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":type v: int :rtype: int",
"name": "insert",
"signature": "def insert(self, v)"
},
{
"docstring": ":rtype: TreeNode",
"name": "get_root",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_002206 | Implement the Python class `CBTInserter` described below.
Class description:
Implement the CBTInserter class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def insert(self, v): :type v: int :rtype: int
- def get_root(self): :rtype: TreeNode | Implement the Python class `CBTInserter` described below.
Class description:
Implement the CBTInserter class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def insert(self, v): :type v: int :rtype: int
- def get_root(self): :rtype: TreeNode
<|skeleton|>
class CBTInserter:
... | 11c81645893fd65f585c3f558ea837c7dd3cb654 | <|skeleton|>
class CBTInserter:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def insert(self, v):
""":type v: int :rtype: int"""
<|body_1|>
def get_root(self):
""":rtype: TreeNode"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CBTInserter:
def __init__(self, root):
""":type root: TreeNode"""
"""
insert the tree..
it has the links we dont have to link it again.
"""
self.list = []
self.list.append(root)
for item in self.list:
if item.l... | the_stack_v2_python_sparse | LC_Complete_Binary_Tree_Inserter.py | venkatsvpr/Problems_Solved | train | 5 | |
c1d4a26575d358c48d735b1e40bca87c08efb349 | [
"self.cookie = cookie\nself.quota_and_usage_in_all_views = quota_and_usage_in_all_views\nself.summary_for_user = summary_for_user\nself.summary_for_view = summary_for_view\nself.user_quota_settings = user_quota_settings\nself.users_quota_and_usage = users_quota_and_usage",
"if dictionary is None:\n return None... | <|body_start_0|>
self.cookie = cookie
self.quota_and_usage_in_all_views = quota_and_usage_in_all_views
self.summary_for_user = summary_for_user
self.summary_for_view = summary_for_view
self.user_quota_settings = user_quota_settings
self.users_quota_and_usage = users_quota... | Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of user quota overrides. If set to nil, it means that there's no more results that t... | ViewUserQuotas | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewUserQuotas:
"""Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of user quota overrides. If set to nil, it... | stack_v2_sparse_classes_10k_train_005828 | 4,761 | permissive | [
{
"docstring": "Constructor for the ViewUserQuotas class",
"name": "__init__",
"signature": "def __init__(self, cookie=None, quota_and_usage_in_all_views=None, summary_for_user=None, summary_for_view=None, user_quota_settings=None, users_quota_and_usage=None)"
},
{
"docstring": "Creates an insta... | 2 | stack_v2_sparse_classes_30k_train_001942 | Implement the Python class `ViewUserQuotas` described below.
Class description:
Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of ... | Implement the Python class `ViewUserQuotas` described below.
Class description:
Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewUserQuotas:
"""Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of user quota overrides. If set to nil, it... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ViewUserQuotas:
"""Implementation of the 'ViewUserQuotas' model. Specifies the Result parameters for all user quotas of a view. Attributes: cookie (string): This cookie can be used in the succeeding call to list user quotas and usages to get the next set of user quota overrides. If set to nil, it means that t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_user_quotas.py | cohesity/management-sdk-python | train | 24 |
51ef5aef183d3d9518cb0325c7b68ee765aac927 | [
"self.treeName = 'SixJetTreeProducer'\nself.selComps = selComps\nself.varName = varName\nself.cut = cut\nself.bins = bins\nself.xmin = xmin\nself.xmax = xmax\nsuper(StackPlot, self).__init__(varName, directory, weights)\nself.legendBorders = (0.651, 0.463, 0.895, 0.892)",
"if not hasattr(comp, 'tree'):\n comp.... | <|body_start_0|>
self.treeName = 'SixJetTreeProducer'
self.selComps = selComps
self.varName = varName
self.cut = cut
self.bins = bins
self.xmin = xmin
self.xmax = xmax
super(StackPlot, self).__init__(varName, directory, weights)
self.legendBorders ... | StackPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackPlot:
def __init__(self, varName, directory, selComps, weights, bins=None, xmin=None, xmax=None, cut=''):
"""Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection of trees in input. The trees are found according to the dictionary of selected components selComp... | stack_v2_sparse_classes_10k_train_005829 | 4,059 | no_license | [
{
"docstring": "Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection of trees in input. The trees are found according to the dictionary of selected components selComps. The global weighting information for each component is read from the weights dictionary.",
"name": "__init__",
... | 4 | null | Implement the Python class `StackPlot` described below.
Class description:
Implement the StackPlot class.
Method signatures and docstrings:
- def __init__(self, varName, directory, selComps, weights, bins=None, xmin=None, xmax=None, cut=''): Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection... | Implement the Python class `StackPlot` described below.
Class description:
Implement the StackPlot class.
Method signatures and docstrings:
- def __init__(self, varName, directory, selComps, weights, bins=None, xmin=None, xmax=None, cut=''): Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection... | 7bec46d27e491397c4e13a52b34cf414a692d867 | <|skeleton|>
class StackPlot:
def __init__(self, varName, directory, selComps, weights, bins=None, xmin=None, xmax=None, cut=''):
"""Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection of trees in input. The trees are found according to the dictionary of selected components selComp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StackPlot:
def __init__(self, varName, directory, selComps, weights, bins=None, xmin=None, xmax=None, cut=''):
"""Data/MC plotter adapted to the LEP3 analysis. The plotter takes a collection of trees in input. The trees are found according to the dictionary of selected components selComps. The global ... | the_stack_v2_python_sparse | CMGTools/LEP3/python/plotter/StackPlot.py | HemantAHK/CMG | train | 0 | |
448cdc16360c560a94c53289a18ea83413bb1e6f | [
"term1 = tokens[indeks_token_pertama]\nterm2 = tokens[indeks_token_pertama + 1]\nreturn ' '.join([term1, term2])",
"vektor_tf_bigram = {}\nsz = len(tokens) - 1\nfor i in range(sz):\n bigram_token = self.__get_term_bigram(i, tokens)\n if bigram_token in vektor_tf_bigram:\n vektor_tf_bigram[bigram_toke... | <|body_start_0|>
term1 = tokens[indeks_token_pertama]
term2 = tokens[indeks_token_pertama + 1]
return ' '.join([term1, term2])
<|end_body_0|>
<|body_start_1|>
vektor_tf_bigram = {}
sz = len(tokens) - 1
for i in range(sz):
bigram_token = self.__get_term_bigram... | Bertugas Menghitung TF pada term Bigram | TfBigram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TfBigram:
"""Bertugas Menghitung TF pada term Bigram"""
def __get_term_bigram(self, indeks_token_pertama: int, tokens: list):
"""Menggabungkan Dua String (Bigram)"""
<|body_0|>
def calculate(self, tokens: list):
"""Mengembalikan Vektor TF-Bigram (Tipe data dictio... | stack_v2_sparse_classes_10k_train_005830 | 1,423 | no_license | [
{
"docstring": "Menggabungkan Dua String (Bigram)",
"name": "__get_term_bigram",
"signature": "def __get_term_bigram(self, indeks_token_pertama: int, tokens: list)"
},
{
"docstring": "Mengembalikan Vektor TF-Bigram (Tipe data dictionary)",
"name": "calculate",
"signature": "def calculate... | 2 | stack_v2_sparse_classes_30k_train_004493 | Implement the Python class `TfBigram` described below.
Class description:
Bertugas Menghitung TF pada term Bigram
Method signatures and docstrings:
- def __get_term_bigram(self, indeks_token_pertama: int, tokens: list): Menggabungkan Dua String (Bigram)
- def calculate(self, tokens: list): Mengembalikan Vektor TF-Big... | Implement the Python class `TfBigram` described below.
Class description:
Bertugas Menghitung TF pada term Bigram
Method signatures and docstrings:
- def __get_term_bigram(self, indeks_token_pertama: int, tokens: list): Menggabungkan Dua String (Bigram)
- def calculate(self, tokens: list): Mengembalikan Vektor TF-Big... | 9742c193251303334ef805c8c94eb075afad777f | <|skeleton|>
class TfBigram:
"""Bertugas Menghitung TF pada term Bigram"""
def __get_term_bigram(self, indeks_token_pertama: int, tokens: list):
"""Menggabungkan Dua String (Bigram)"""
<|body_0|>
def calculate(self, tokens: list):
"""Mengembalikan Vektor TF-Bigram (Tipe data dictio... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TfBigram:
"""Bertugas Menghitung TF pada term Bigram"""
def __get_term_bigram(self, indeks_token_pertama: int, tokens: list):
"""Menggabungkan Dua String (Bigram)"""
term1 = tokens[indeks_token_pertama]
term2 = tokens[indeks_token_pertama + 1]
return ' '.join([term1, term2... | the_stack_v2_python_sparse | ujian_app/penilaian/pemrosesan_teks/ngram.py | anh4rs/Aplikasi-Penilaian-Otomatis-Esai-BI | train | 0 |
e01d79ea55a7a7667092d85dc0dc249867207720 | [
"self.xint = xint\nself.yint = yint\nself.n = len(xint)\nw = np.ones(self.n)\nself.C = (np.max(xint) - np.min(xint)) / 4\nshuffle = np.random.permutation(self.n - 1)\nfor j in range(self.n):\n temp = (xint[j] - np.delete(xint, j)) / self.C\n temp = temp[shuffle]\n w[j] /= np.product(temp)\nself.weights = w... | <|body_start_0|>
self.xint = xint
self.yint = yint
self.n = len(xint)
w = np.ones(self.n)
self.C = (np.max(xint) - np.min(xint)) / 4
shuffle = np.random.permutation(self.n - 1)
for j in range(self.n):
temp = (xint[j] - np.delete(xint, j)) / self.C
... | Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points. | Barycentric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_10k_train_005831 | 6,344 | no_license | [
{
"docstring": "Calculate the Barycentric weights using initial interpolating points. Parameters: xint ((n,) ndarray): x values of interpolating points. yint ((n,) ndarray): y values of interpolating points.",
"name": "__init__",
"signature": "def __init__(self, xint, yint)"
},
{
"docstring": "U... | 3 | stack_v2_sparse_classes_30k_test_000371 | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | Implement the Python class `Barycentric` described below.
Class description:
Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of in... | 6e969de3a8337b0bd9bb4ba7abac722ab5c065ab | <|skeleton|>
class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Barycentric:
"""Class for performing Barycentric Lagrange interpolation. Attributes: w ((n,) ndarray): Array of Barycentric weights. n (int): Number of interpolation points. x ((n,) ndarray): x values of interpolating points. y ((n,) ndarray): y values of interpolating points."""
def __init__(self, xint,... | the_stack_v2_python_sparse | Class/ACME_Volume_2-Python/PolynomialInterpolation/polynomial_interpolation.py | scj1420/Class-Projects-Research | train | 0 |
bebd3689ed2b3dc361d1b32344dcff8391ea2af4 | [
"if isinstance(item, ChinazWebinfoItem):\n image_url = item['CoverImage']\n yield scrapy.Request(image_url)",
"paths = [result['path'] for status, result in results if status]\nprint('图片下载结果:', results)\nif len(paths) > 0:\n print('图片下载成功')\n os.rename(images_store + '/' + paths[0], images_store + '/f... | <|body_start_0|>
if isinstance(item, ChinazWebinfoItem):
image_url = item['CoverImage']
yield scrapy.Request(image_url)
<|end_body_0|>
<|body_start_1|>
paths = [result['path'] for status, result in results if status]
print('图片下载结果:', results)
if len(paths) > 0:
... | ChinazImagesPipeline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
<|body_0|>
def item_completed(self, results, item, info):
"""图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckeck... | stack_v2_sparse_classes_10k_train_005832 | 6,372 | no_license | [
{
"docstring": "根据图片url地址发起请求 :param item: :param info: :return:",
"name": "get_media_requests",
"signature": "def get_media_requests(self, item, info)"
},
{
"docstring": "图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckecksum':'经过hash加密的一个字符串'} :param item: :... | 2 | stack_v2_sparse_classes_30k_train_002127 | Implement the Python class `ChinazImagesPipeline` described below.
Class description:
Implement the ChinazImagesPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): 根据图片url地址发起请求 :param item: :param info: :return:
- def item_completed(self, results, item, info): 图片下载 :param re... | Implement the Python class `ChinazImagesPipeline` described below.
Class description:
Implement the ChinazImagesPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): 根据图片url地址发起请求 :param item: :param info: :return:
- def item_completed(self, results, item, info): 图片下载 :param re... | 841cad4bf84c6e3af98a32f4f33ebda62055680c | <|skeleton|>
class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
<|body_0|>
def item_completed(self, results, item, info):
"""图片下载 :param results: 响应结果,True是成功,False是失败。{'path':'图片下载后的存储路径','url':'图片的url地址','ckeck... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChinazImagesPipeline:
def get_media_requests(self, item, info):
"""根据图片url地址发起请求 :param item: :param info: :return:"""
if isinstance(item, ChinazWebinfoItem):
image_url = item['CoverImage']
yield scrapy.Request(image_url)
def item_completed(self, results, item, inf... | the_stack_v2_python_sparse | scrapy_Spider/Chinaz/Chinaz/pipelines.py | aini626204777/spider | train | 0 | |
987960badf80458cb3cde7066c2171e61b49b579 | [
"nn.Module.__init__(self)\nself.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}\nself.num_inputs = num_inputs\nif b_values is None:\n self.a_... | <|body_start_0|>
nn.Module.__init__(self)
self.params = {'num_inputs': num_inputs, 'num_outputs': num_outputs, 'a_values': None if a_values is None else a_values.tolist(), 'b_values': None if b_values is None else b_values.tolist(), 'layer_channels': layer_channels}
self.num_inputs = num_inputs
... | MLP which uses Fourier features as a preprocessing step. | BaseFourierFeatureMLP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number o... | stack_v2_sparse_classes_10k_train_005833 | 8,060 | permissive | [
{
"docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output a_values (torch.Tensor): a values for encoding b_values (torch.Tensor): b values for encoding layer_channels (List[int]): Number of channels per layer.",
"name": "__in... | 3 | stack_v2_sparse_classes_30k_train_005019 | Implement the Python class `BaseFourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: ... | Implement the Python class `BaseFourierFeatureMLP` described below.
Class description:
MLP which uses Fourier features as a preprocessing step.
Method signatures and docstrings:
- def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: ... | 94a402cab47a2bd6241608308371490079af4d53 | <|skeleton|>
class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseFourierFeatureMLP:
"""MLP which uses Fourier features as a preprocessing step."""
def __init__(self, num_inputs: int, num_outputs: int, a_values: Optional[torch.Tensor], b_values: Optional[torch.Tensor], layer_channels: List[int]):
"""Constructor. Args: num_inputs (int): Number of dimensions ... | the_stack_v2_python_sparse | draugr/torch_utilities/architectures/mlp_variants/fourier.py | cnheider/draugr | train | 4 |
5a5333ae12496d1ff99033ec928eb96fd66cf6bc | [
"m = len(s1)\nn = len(s2)\nif m + n != len(s3):\n return False\ndp = [[False for _ in xrange(n + 1)] for _ in xrange(m + 1)]\ndp[0][0] = True\nfor i in xrange(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s3[i + 0 - 1] == s1[i - 1]\nfor j in xrange(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s3[0 + j - 1] == s2[j ... | <|body_start_0|>
m = len(s1)
n = len(s2)
if m + n != len(s3):
return False
dp = [[False for _ in xrange(n + 1)] for _ in xrange(m + 1)]
dp[0][0] = True
for i in xrange(1, m + 1):
dp[i][0] = dp[i - 1][0] and s3[i + 0 - 1] == s1[i - 1]
for j ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
"""dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T c F F F T F T notice the boundary condition Thought: dfs, easy to come up, but high space complex... | stack_v2_sparse_classes_10k_train_005834 | 2,718 | permissive | [
{
"docstring": "dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T c F F F T F T notice the boundary condition Thought: dfs, easy to come up, but high space complexity thus, dp f[i][j] represents s3[:i+j] comes from s1[:i... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
"""dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T c F F F T F T notice the boundary condition Thought: dfs, easy to come up, but high space complex... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isInterleave(self, s1, s2, s3):
"""dfs dp dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j] - d b b c a - T F F F F F a T F F F F F a T T T T T F b F T T F T F c F F T T T T c F F F T F T notice the boundary condition Thought: dfs, easy to come up, but high space complexity thus, dp f... | the_stack_v2_python_sparse | 097 Interleaving String.py | Aminaba123/LeetCode | train | 1 | |
2b94cbf99366f4b45eb4aafad676506442ab8e06 | [
"self.queueLinks = Queue.Queue()\nself.queueTexts = Queue.Queue()\nself.monitoring = False\nself.texts = ''\nself.fileName = None",
"print('Flushing texts ...')\nwhile not self.queueTexts.empty():\n self.texts += self.queueTexts.get()\n self.queueTexts.task_done()\nopen(self.fileName, 'w').write(self.texts)... | <|body_start_0|>
self.queueLinks = Queue.Queue()
self.queueTexts = Queue.Queue()
self.monitoring = False
self.texts = ''
self.fileName = None
<|end_body_0|>
<|body_start_1|>
print('Flushing texts ...')
while not self.queueTexts.empty():
self.texts += ... | Скачивает текст по списку ссылок | TextsDownloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextsDownloader:
"""Скачивает текст по списку ссылок"""
def __init__(self):
"""Инициализация"""
<|body_0|>
def Flush(self):
"""Сохраняем текст"""
<|body_1|>
def Process(self, linksList, fileName):
"""Скачиваем текст"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k_train_005835 | 14,806 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Сохраняем текст",
"name": "Flush",
"signature": "def Flush(self)"
},
{
"docstring": "Скачиваем текст",
"name": "Process",
"signature": "def Process(self, linksList, fi... | 3 | stack_v2_sparse_classes_30k_train_002665 | Implement the Python class `TextsDownloader` described below.
Class description:
Скачивает текст по списку ссылок
Method signatures and docstrings:
- def __init__(self): Инициализация
- def Flush(self): Сохраняем текст
- def Process(self, linksList, fileName): Скачиваем текст | Implement the Python class `TextsDownloader` described below.
Class description:
Скачивает текст по списку ссылок
Method signatures and docstrings:
- def __init__(self): Инициализация
- def Flush(self): Сохраняем текст
- def Process(self, linksList, fileName): Скачиваем текст
<|skeleton|>
class TextsDownloader:
... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class TextsDownloader:
"""Скачивает текст по списку ссылок"""
def __init__(self):
"""Инициализация"""
<|body_0|>
def Flush(self):
"""Сохраняем текст"""
<|body_1|>
def Process(self, linksList, fileName):
"""Скачиваем текст"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TextsDownloader:
"""Скачивает текст по списку ссылок"""
def __init__(self):
"""Инициализация"""
self.queueLinks = Queue.Queue()
self.queueTexts = Queue.Queue()
self.monitoring = False
self.texts = ''
self.fileName = None
def Flush(self):
"""Сох... | the_stack_v2_python_sparse | tools/textparser.py | cash2one/doorscenter | train | 0 |
669ba5d3ddcb833f1e01465ccec198b7daee4b80 | [
"super(PosOutputLayer, self).__init__()\nself.linear_1 = Linear(linear_weight_shape=linear_weight_shape, linear_bias_shape=linear_bias_shape)\nself.bert_layer_norm = BertLayerNorm(bert_layer_norm_weight_shape=bert_layer_norm_weight_shape, bert_layer_norm_bias_shape=bert_layer_norm_bias_shape)\nself.matmul = nn.MatM... | <|body_start_0|>
super(PosOutputLayer, self).__init__()
self.linear_1 = Linear(linear_weight_shape=linear_weight_shape, linear_bias_shape=linear_bias_shape)
self.bert_layer_norm = BertLayerNorm(bert_layer_norm_weight_shape=bert_layer_norm_weight_shape, bert_layer_norm_bias_shape=bert_layer_norm_... | module of reader downstream | PosOutputLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosOutputLayer:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape):
"""init function"""
<|body_0|>
def construct(self, state):
"""construct function"""
<|b... | stack_v2_sparse_classes_10k_train_005836 | 9,011 | permissive | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape)"
},
{
"docstring": "construct function",
"name": "construct",
"signature": "def construct(self, state)"
... | 2 | stack_v2_sparse_classes_30k_train_000825 | Implement the Python class `PosOutputLayer` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape): init function
- def construct(self, state): construct fu... | Implement the Python class `PosOutputLayer` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape): init function
- def construct(self, state): construct fu... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class PosOutputLayer:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape):
"""init function"""
<|body_0|>
def construct(self, state):
"""construct function"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PosOutputLayer:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape):
"""init function"""
super(PosOutputLayer, self).__init__()
self.linear_1 = Linear(linear_weight_shape=linear_weig... | the_stack_v2_python_sparse | research/nlp/tprr/src/reader_downstream.py | mindspore-ai/models | train | 301 |
8f67d59da3bc32ceb80cb28e394e6aca85cb7f3c | [
"rc, stdout, stderr = IpNeighbour.showNeighboursByDevice(logger, device, version)\nif rc != 0:\n return None\nif logger:\n logger('neigh-table-get').debug2('retrieving device %s neighbor table', device, stdout)\noutput = stdout.splitlines()\nreturn output",
"output = NeighbourUtils.getNeighbourTable(logger,... | <|body_start_0|>
rc, stdout, stderr = IpNeighbour.showNeighboursByDevice(logger, device, version)
if rc != 0:
return None
if logger:
logger('neigh-table-get').debug2('retrieving device %s neighbor table', device, stdout)
output = stdout.splitlines()
return... | This class holds neighbour utilities | NeighbourUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighbourUtils:
"""This class holds neighbour utilities"""
def getNeighbourTable(logger, device, version=4):
"""This function returns the neighbour table"""
<|body_0|>
def getNeighbourMacAddress(logger, device, dstIp, version=4):
"""This function returns the neig... | stack_v2_sparse_classes_10k_train_005837 | 10,343 | no_license | [
{
"docstring": "This function returns the neighbour table",
"name": "getNeighbourTable",
"signature": "def getNeighbourTable(logger, device, version=4)"
},
{
"docstring": "This function returns the neighbour mac address",
"name": "getNeighbourMacAddress",
"signature": "def getNeighbourMa... | 2 | stack_v2_sparse_classes_30k_train_004759 | Implement the Python class `NeighbourUtils` described below.
Class description:
This class holds neighbour utilities
Method signatures and docstrings:
- def getNeighbourTable(logger, device, version=4): This function returns the neighbour table
- def getNeighbourMacAddress(logger, device, dstIp, version=4): This func... | Implement the Python class `NeighbourUtils` described below.
Class description:
This class holds neighbour utilities
Method signatures and docstrings:
- def getNeighbourTable(logger, device, version=4): This function returns the neighbour table
- def getNeighbourMacAddress(logger, device, dstIp, version=4): This func... | 81bcc74fe7c0ca036ec483f634d7be0bab19a6d0 | <|skeleton|>
class NeighbourUtils:
"""This class holds neighbour utilities"""
def getNeighbourTable(logger, device, version=4):
"""This function returns the neighbour table"""
<|body_0|>
def getNeighbourMacAddress(logger, device, dstIp, version=4):
"""This function returns the neig... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NeighbourUtils:
"""This class holds neighbour utilities"""
def getNeighbourTable(logger, device, version=4):
"""This function returns the neighbour table"""
rc, stdout, stderr = IpNeighbour.showNeighboursByDevice(logger, device, version)
if rc != 0:
return None
... | the_stack_v2_python_sparse | oscar/a/sys/net/lnx/neighbour.py | afeset/miner2-tools | train | 0 |
870d845c3f4d1670dc5e4050ae2a98d1e7d833c3 | [
"if len(A) < 3:\n return False\nfor i in range(1, len(A) - 1):\n if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):\n return True\nreturn False",
"if len(A) < 3:\n return False\nif A[-1] > A[-2] or A[0] > A[1]:\n return False\nflag = 'gr... | <|body_start_0|>
if len(A) < 3:
return False
for i in range(1, len(A) - 1):
if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):
return True
return False
<|end_body_0|>
<|body_start_1|>
if le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_10k_train_005838 | 1,335 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A)"
},
{
"docstring": ":typ... | 3 | stack_v2_sparse_classes_30k_train_003108 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: List[int] :rtype: bool
- def validMountainArray(self, A): :type A: Li... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_0|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def validMountainArray(self, A):
""":type A: List[int] :rtype: bool"""
if len(A) < 3:
return False
for i in range(1, len(A) - 1):
if all((A[m] > A[m - 1] for m in range(1, i + 1))) and all((A[n] > A[n + 1] for n in range(i, len(A) - 1))):
... | the_stack_v2_python_sparse | 0941_Valid_Mountain_Array.py | bingli8802/leetcode | train | 0 | |
91c784c600d4cc4d5d4293f798e5a5830cc12c73 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceManagementExportJob()",
"from .device_management_export_job_localization_type import DeviceManagementExportJobLocalizationType\nfrom .device_management_report_file_format import DeviceManagementReportFileFormat\nfrom .device_mana... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceManagementExportJob()
<|end_body_0|>
<|body_start_1|>
from .device_management_export_job_localization_type import DeviceManagementExportJobLocalizationType
from .device_management_... | Entity representing a job to export a report | DeviceManagementExportJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceManagementExportJob:
"""Entity representing a job to export a report"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceManagementExportJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The ... | stack_v2_sparse_classes_10k_train_005839 | 5,612 | 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: DeviceManagementExportJob",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `DeviceManagementExportJob` described below.
Class description:
Entity representing a job to export a report
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceManagementExportJob: Creates a new instance of the appropriate ... | Implement the Python class `DeviceManagementExportJob` described below.
Class description:
Entity representing a job to export a report
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceManagementExportJob: Creates a new instance of the appropriate ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceManagementExportJob:
"""Entity representing a job to export a report"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceManagementExportJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeviceManagementExportJob:
"""Entity representing a job to export a report"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceManagementExportJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to... | the_stack_v2_python_sparse | msgraph/generated/models/device_management_export_job.py | microsoftgraph/msgraph-sdk-python | train | 135 |
4618037b377dd3e668621132eaa33124aec08071 | [
"self.id = id\nself.name = name\nself.mtype = mtype\nself.usage_bytes = usage_bytes",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nname = dictionary.get('name')\nmtype = dictionary.get('type')\nusage_bytes = dictionary.get('usageBytes')\nreturn cls(id, name, mtype, usage_bytes)"
] | <|body_start_0|>
self.id = id
self.name = name
self.mtype = mtype
self.usage_bytes = usage_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
name = dictionary.get('name')
mtype = dictionary.get(... | Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_bytes (long|int): Specifies the bytes used by the Vault. | VaultStatsInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultStatsInfo:
"""Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_bytes (long|int): Specifies the bytes us... | stack_v2_sparse_classes_10k_train_005840 | 1,885 | permissive | [
{
"docstring": "Constructor for the VaultStatsInfo class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, mtype=None, usage_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of ... | 2 | stack_v2_sparse_classes_30k_train_005522 | Implement the Python class `VaultStatsInfo` described below.
Class description:
Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_b... | Implement the Python class `VaultStatsInfo` described below.
Class description:
Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_b... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultStatsInfo:
"""Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_bytes (long|int): Specifies the bytes us... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VaultStatsInfo:
"""Implementation of the 'VaultStatsInfo' model. Specifies the stats for each vault. Attributes: id (long|int): Specifies the Vault Id. name (string): Specifies the Vault name. mtype (TypeVaultStatsInfoEnum): Specifies the Vault type. usage_bytes (long|int): Specifies the bytes used by the Vau... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_stats_info.py | cohesity/management-sdk-python | train | 24 |
3eaf42276629e55a2632c84547234fab76f8d879 | [
"g = Pipeline.__call__(self, *args, **kwargs)\ngs = g.glyph.glyph_source\nif not 'mode' in kwargs:\n gs.glyph_source = gs.glyph_list[-1]\ngs.glyph_position = 'tail'\ngs.glyph_source.center = (0.0, 0.0, 0.5)\ng.glyph.glyph.orient = False\nif not 'color' in kwargs:\n g.glyph.color_mode = 'color_by_scalar'\nif n... | <|body_start_0|>
g = Pipeline.__call__(self, *args, **kwargs)
gs = g.glyph.glyph_source
if not 'mode' in kwargs:
gs.glyph_source = gs.glyph_list[-1]
gs.glyph_position = 'tail'
gs.glyph_source.center = (0.0, 0.0, 0.5)
g.glyph.glyph.orient = False
if not... | 2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of inputs, with positions given in 2-D or in 3... | CustomBarChart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of i... | stack_v2_sparse_classes_10k_train_005841 | 5,432 | no_license | [
{
"docstring": "Override the call to be able to scale automaticaly the axis.",
"name": "__call__",
"signature": "def __call__(self, *args, **kwargs)"
},
{
"docstring": "2012.2.21 this function determines the set of possible keys in kwargs. add two keywords, x_scale, y_scale. Returns all the trai... | 2 | null | Implement the Python class `CustomBarChart` described below.
Class description:
2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. Thi... | Implement the Python class `CustomBarChart` described below.
Class description:
2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. Thi... | b9333b85daed71032a1cba766585d0be1986ffdb | <|skeleton|>
class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of inputs, with p... | the_stack_v2_python_sparse | pymodule/plot/yh_mayavi.py | polyactis/gwasmodules | train | 0 |
64d3f550cdc895467fe1943c9fd6ca4a34b53f37 | [
"if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):\n user = User.query.filter_by(id=user_id).first()\n if not user:\n return jsonify({'message': 'No User'})\n user_data = {}\n user_data['username'] = user.username\n a = Group.query.get(user.group_... | <|body_start_0|>
if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):
user = User.query.filter_by(id=user_id).first()
if not user:
return jsonify({'message': 'No User'})
user_data = {}
user_data['username... | Resource for managing User details | UserApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
<|body_0|>
def delete(cls, user_id):
"""Method for deleting the User"""
<|body_1|>
def put(cls, user_id):
"""Method f... | stack_v2_sparse_classes_10k_train_005842 | 5,619 | no_license | [
{
"docstring": "Method for retrieving details about the User",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Method for deleting the User",
"name": "delete",
"signature": "def delete(cls, user_id)"
},
{
"docstring": "Method for partial updating details a... | 3 | stack_v2_sparse_classes_30k_train_000068 | Implement the Python class `UserApi` described below.
Class description:
Resource for managing User details
Method signatures and docstrings:
- def get(self, user_id): Method for retrieving details about the User
- def delete(cls, user_id): Method for deleting the User
- def put(cls, user_id): Method for partial upda... | Implement the Python class `UserApi` described below.
Class description:
Resource for managing User details
Method signatures and docstrings:
- def get(self, user_id): Method for retrieving details about the User
- def delete(cls, user_id): Method for deleting the User
- def put(cls, user_id): Method for partial upda... | 4e5e1b390ba55f714792895cb358f7cf17854a13 | <|skeleton|>
class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
<|body_0|>
def delete(cls, user_id):
"""Method for deleting the User"""
<|body_1|>
def put(cls, user_id):
"""Method f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):
user = User.query.filter_by(id=user_id).first()
... | the_stack_v2_python_sparse | flask_project/views/user.py | vladkost43/flask_demo3 | train | 0 |
3f3f6b9f7ab67b729d50d1d582af0be1282b608c | [
"vals = []\n\ndef to_str(node):\n if node:\n vals.append(str(node.val))\n to_str(node.left)\n to_str(node.right)\n else:\n vals.append('#')\nto_str(root)\nreturn ','.join(vals)",
"vals = iter(data.split(','))\n\ndef to_node():\n c = vals.next()\n if c == '#':\n retur... | <|body_start_0|>
vals = []
def to_str(node):
if node:
vals.append(str(node.val))
to_str(node.left)
to_str(node.right)
else:
vals.append('#')
to_str(root)
return ','.join(vals)
<|end_body_0|>
<|body_... | 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_10k_train_005843 | 1,706 | 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_005646 | 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:... | f2bf9b13508cd01c8f383789569e55a438f77202 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
vals = []
def to_str(node):
if node:
vals.append(str(node.val))
to_str(node.left)
to_str(node.right)
else... | the_stack_v2_python_sparse | version1/449_Serialize_And_Deserialize_BST.py | moontree/leetcode | train | 1 | |
2253945e78d2af5578497bb51b23cc8d9f441bb7 | [
"data = deque()\n\ndef code(node):\n if node is None:\n data.appendleft(None)\n return\n data.appendleft(node.val)\n code(node.left)\n code(node.right)\ncode(root)\nreturn data",
"def decode():\n value = data.pop()\n if value is None:\n return None\n node = TreeNode(value... | <|body_start_0|>
data = deque()
def code(node):
if node is None:
data.appendleft(None)
return
data.appendleft(node.val)
code(node.left)
code(node.right)
code(root)
return data
<|end_body_0|>
<|body_start_1|... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_005844 | 1,564 | 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_002585 | 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:... | 97246c26483637b95198ed2ef76e234d3c0194dc | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
data = deque()
def code(node):
if node is None:
data.appendleft(None)
return
data.appendleft(node.val)
code(n... | the_stack_v2_python_sparse | coding/leetcode/fb/serialize_and_deserialize_binary_treev1.py | baites/examples | train | 4 | |
bb079f4259e17cd96abdf91270557d437c874948 | [
"seconds = int(3600 * hours)\ndays, seconds = divmod(seconds, 86400)\nhours, seconds = divmod(seconds, 3600)\nminutes, seconds = divmod(seconds, 60)\nif days > 0:\n return '%dd %dh %dm' % (days, hours, minutes)\nif hours > 0:\n return '%dh %dm' % (hours, minutes)\nreturn '%dm' % minutes",
"if len(period) !=... | <|body_start_0|>
seconds = int(3600 * hours)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
return '%dd %dh %dm' % (days, hours, minutes)
if hours > 0:
return '%dh %... | Static methods to make the HistoryStatsSensor code lighter. | HistoryStatsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistoryStatsHelper:
"""Static methods to make the HistoryStatsSensor code lighter."""
def pretty_duration(hours):
"""Format a duration in days, hours, minutes, seconds."""
<|body_0|>
def pretty_ratio(value, period):
"""Format the ratio of value / period duration.... | stack_v2_sparse_classes_10k_train_005845 | 11,604 | permissive | [
{
"docstring": "Format a duration in days, hours, minutes, seconds.",
"name": "pretty_duration",
"signature": "def pretty_duration(hours)"
},
{
"docstring": "Format the ratio of value / period duration.",
"name": "pretty_ratio",
"signature": "def pretty_ratio(value, period)"
},
{
... | 3 | null | Implement the Python class `HistoryStatsHelper` described below.
Class description:
Static methods to make the HistoryStatsSensor code lighter.
Method signatures and docstrings:
- def pretty_duration(hours): Format a duration in days, hours, minutes, seconds.
- def pretty_ratio(value, period): Format the ratio of val... | Implement the Python class `HistoryStatsHelper` described below.
Class description:
Static methods to make the HistoryStatsSensor code lighter.
Method signatures and docstrings:
- def pretty_duration(hours): Format a duration in days, hours, minutes, seconds.
- def pretty_ratio(value, period): Format the ratio of val... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class HistoryStatsHelper:
"""Static methods to make the HistoryStatsSensor code lighter."""
def pretty_duration(hours):
"""Format a duration in days, hours, minutes, seconds."""
<|body_0|>
def pretty_ratio(value, period):
"""Format the ratio of value / period duration.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HistoryStatsHelper:
"""Static methods to make the HistoryStatsSensor code lighter."""
def pretty_duration(hours):
"""Format a duration in days, hours, minutes, seconds."""
seconds = int(3600 * hours)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3... | the_stack_v2_python_sparse | homeassistant/components/history_stats/sensor.py | BenWoodford/home-assistant | train | 11 |
2eabf0c8d916c2c52158cb59b755dab3fda09f07 | [
"self.args = args\nself.kubeconfig = '/tmp/admin.kubeconfig'\nself.oc = OCUtil(namespace=self.args.namespace, config_file=self.kubeconfig)",
"result = 1\nzabbix_data_sync_inventory_hosts_names = []\nfor host in zabbix_data_sync_inventory_hosts:\n zabbix_data_sync_inventory_hosts_names.append(host['name'])\ndes... | <|body_start_0|>
self.args = args
self.kubeconfig = '/tmp/admin.kubeconfig'
self.oc = OCUtil(namespace=self.args.namespace, config_file=self.kubeconfig)
<|end_body_0|>
<|body_start_1|>
result = 1
zabbix_data_sync_inventory_hosts_names = []
for host in zabbix_data_sync_in... | this will check the zabbix data and compare it with the real world | ZabbixInfo | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
<|body_0|>
def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):
"""check the situation"... | stack_v2_sparse_classes_10k_train_005846 | 4,174 | permissive | [
{
"docstring": "initial for the InfraNodePodStatus",
"name": "__init__",
"signature": "def __init__(self, args=None)"
},
{
"docstring": "check the situation",
"name": "check_all_hosts",
"signature": "def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_004245 | Implement the Python class `ZabbixInfo` described below.
Class description:
this will check the zabbix data and compare it with the real world
Method signatures and docstrings:
- def __init__(self, args=None): initial for the InfraNodePodStatus
- def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):... | Implement the Python class `ZabbixInfo` described below.
Class description:
this will check the zabbix data and compare it with the real world
Method signatures and docstrings:
- def __init__(self, args=None): initial for the InfraNodePodStatus
- def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
<|body_0|>
def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):
"""check the situation"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
self.args = args
self.kubeconfig = '/tmp/admin.kubeconfig'
self.oc = OCUtil(namespace=self.args.namespace, config_fi... | the_stack_v2_python_sparse | scripts/monitoring/cron-send-zabbix-inventory-check.py | openshift/openshift-tools | train | 170 |
cf603d1c032ffc9d726595322cf4115167caa7c5 | [
"if N == 1:\n return 10\ntemp = 10 ** 9 + 7\ndp = [[0] * 10 for _ in range(N)]\nfor i in range(10):\n dp[0][i] = 1\nfor i in range(1, N):\n dp[i][0] = (dp[i - 1][4] + dp[i - 1][6]) % temp\n dp[i][1] = (dp[i - 1][6] + dp[i - 1][8]) % temp\n dp[i][2] = (dp[i - 1][7] + dp[i - 1][9]) % temp\n dp[i][3]... | <|body_start_0|>
if N == 1:
return 10
temp = 10 ** 9 + 7
dp = [[0] * 10 for _ in range(N)]
for i in range(10):
dp[0][i] = 1
for i in range(1, N):
dp[i][0] = (dp[i - 1][4] + dp[i - 1][6]) % temp
dp[i][1] = (dp[i - 1][6] + dp[i - 1][8... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
<|body_0|>
def knightDialer_1(self, N):
""":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N == 1:
return 10
... | stack_v2_sparse_classes_10k_train_005847 | 2,749 | no_license | [
{
"docstring": ":type N: int :rtype: int 552 ms",
"name": "knightDialer",
"signature": "def knightDialer(self, N)"
},
{
"docstring": ":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!",
"name": "knightDialer_1",
"signature": "def knightDialer_1(self, N)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005720 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightDialer(self, N): :type N: int :rtype: int 552 ms
- def knightDialer_1(self, N): :type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!! | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def knightDialer(self, N): :type N: int :rtype: int 552 ms
- def knightDialer_1(self, N): :type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!
<|skeleton|>
class Solution:
def ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
<|body_0|>
def knightDialer_1(self, N):
""":type N: int :rtype: int 80ms 矩阵乘法,斐波那契数列的方法!!!!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def knightDialer(self, N):
""":type N: int :rtype: int 552 ms"""
if N == 1:
return 10
temp = 10 ** 9 + 7
dp = [[0] * 10 for _ in range(N)]
for i in range(10):
dp[0][i] = 1
for i in range(1, N):
dp[i][0] = (dp[i - 1][... | the_stack_v2_python_sparse | KnightDialer_MID_935.py | 953250587/leetcode-python | train | 2 | |
97b2ba3de09fe1975cbba11a4e8bc609f6a23c5f | [
"self.max_atoms = max_atoms\nself.flatten = flatten\nself.scm: Any = None",
"if 'struct' in kwargs and datapoint is None:\n datapoint = kwargs.get('struct')\n raise DeprecationWarning('Struct is being phased out as a parameter, please pass \"datapoint\" instead.')\nif self.scm is None:\n try:\n fr... | <|body_start_0|>
self.max_atoms = max_atoms
self.flatten = flatten
self.scm: Any = None
<|end_body_0|>
<|body_start_1|>
if 'struct' in kwargs and datapoint is None:
datapoint = kwargs.get('struct')
raise DeprecationWarning('Struct is being phased out as a paramet... | Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are periodic in the dimensions of the crystal lattic... | SineCoulombMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are per... | stack_v2_sparse_classes_10k_train_005848 | 3,823 | permissive | [
{
"docstring": "Parameters ---------- max_atoms: int (default 100) Maximum number of atoms for any crystal in the dataset. Used to pad the Coulomb matrix. flatten: bool (default True) Return flattened vector of matrix eigenvalues.",
"name": "__init__",
"signature": "def __init__(self, max_atoms: int=100... | 2 | null | Implement the Python class `SineCoulombMatrix` described below.
Class description:
Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of... | Implement the Python class `SineCoulombMatrix` described below.
Class description:
Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are per... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are periodic in the ... | the_stack_v2_python_sparse | deepchem/feat/material_featurizers/sine_coulomb_matrix.py | deepchem/deepchem | train | 4,876 |
3a2ced9752c0b22fbe9aa932b6084bd88f543a93 | [
"try:\n return settings.DATABASE_APP_MAPPING[model._meta.app_label]\nexcept KeyError:\n return None",
"try:\n return settings.DATABASE_APP_MAPPING[model._meta.app_label]\nexcept KeyError:\n return None",
"ffball_obj = settings.DATABASE_APP_MAPPING.get(obj1._meta.app_label)\nyahoo_obj = settings.DATA... | <|body_start_0|>
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError:
return None
<|end_body_0|>
<|body_start_1|>
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError:
return None
<|... | A router to control all database operations on models in the auth application. | DbRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write au... | stack_v2_sparse_classes_10k_train_005849 | 1,484 | no_license | [
{
"docstring": "Attempts to read yahoo info, read from mongo_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
... | 4 | stack_v2_sparse_classes_30k_train_003745 | Implement the Python class `DbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read yahoo info, read from mongo_db.
- def db_for_write(self, model, **hints):... | Implement the Python class `DbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read yahoo info, read from mongo_db.
- def db_for_write(self, model, **hints):... | e1e40558282cc671f26a04bdafc54536c28f47a4 | <|skeleton|>
class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write au... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read yahoo info, read from mongo_db."""
try:
return settings.DATABASE_APP_MAPPING[model._meta.app_label]
except KeyError... | the_stack_v2_python_sparse | ffball/db_router.py | rchatterjee/moneyball | train | 1 |
0fdc22174c851eae455e155342136a58e8714159 | [
"try:\n if altura == '':\n raise custom_exceptions.ErrorDeNegocio(origen='neogocio_direccion.alta_pd()', msj_adicional='Error al validar una dirección. La altura no puede quedar vacía.')\n elif not isinstance(int(altura), int):\n raise custom_exceptions.ErrorDeNegocio(origen='neogocio_direccion.... | <|body_start_0|>
try:
if altura == '':
raise custom_exceptions.ErrorDeNegocio(origen='neogocio_direccion.alta_pd()', msj_adicional='Error al validar una dirección. La altura no puede quedar vacía.')
elif not isinstance(int(altura), int):
raise custom_excep... | NegocioDireccion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NegocioDireccion:
def valida_direccion(cls, calle, altura, ciudad, provincia, pais):
"""Realiza las validaciones de negocio de una direccion."""
<|body_0|>
def alta_direccion(cls, calle, altura, ciudad, provincia, pais, validar=False):
"""Añade una dirección a la BD.... | stack_v2_sparse_classes_10k_train_005850 | 4,578 | no_license | [
{
"docstring": "Realiza las validaciones de negocio de una direccion.",
"name": "valida_direccion",
"signature": "def valida_direccion(cls, calle, altura, ciudad, provincia, pais)"
},
{
"docstring": "Añade una dirección a la BD.",
"name": "alta_direccion",
"signature": "def alta_direccio... | 3 | stack_v2_sparse_classes_30k_train_007093 | Implement the Python class `NegocioDireccion` described below.
Class description:
Implement the NegocioDireccion class.
Method signatures and docstrings:
- def valida_direccion(cls, calle, altura, ciudad, provincia, pais): Realiza las validaciones de negocio de una direccion.
- def alta_direccion(cls, calle, altura, ... | Implement the Python class `NegocioDireccion` described below.
Class description:
Implement the NegocioDireccion class.
Method signatures and docstrings:
- def valida_direccion(cls, calle, altura, ciudad, provincia, pais): Realiza las validaciones de negocio de una direccion.
- def alta_direccion(cls, calle, altura, ... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class NegocioDireccion:
def valida_direccion(cls, calle, altura, ciudad, provincia, pais):
"""Realiza las validaciones de negocio de una direccion."""
<|body_0|>
def alta_direccion(cls, calle, altura, ciudad, provincia, pais, validar=False):
"""Añade una dirección a la BD.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NegocioDireccion:
def valida_direccion(cls, calle, altura, ciudad, provincia, pais):
"""Realiza las validaciones de negocio de una direccion."""
try:
if altura == '':
raise custom_exceptions.ErrorDeNegocio(origen='neogocio_direccion.alta_pd()', msj_adicional='Error ... | the_stack_v2_python_sparse | negocio/negocio_direccion.py | JoaquinCardonaRuiz/proyecto-final | train | 0 | |
09222643100a3693261a4aa64611fff7bd981946 | [
"try:\n return Comment.objects.get(id=id)\nexcept Comment.DoesNotExist:\n raise Http404",
"comment_object = self.get_object(id)\nresponse = self.serializer_class(comment_object)\nreturn Response(response.data)",
"comments = self.get_object(id)\ncomments.delete()\nreturn Response(status=status.HTTP_204_NO_... | <|body_start_0|>
try:
return Comment.objects.get(id=id)
except Comment.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
comment_object = self.get_object(id)
response = self.serializer_class(comment_object)
return Response(response.data)
<|end_b... | This class is an API for geting comment of post detail. | CommentViewDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentViewDetail:
"""This class is an API for geting comment of post detail."""
def get_object(self, id):
"""Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web APIs. Return: comment object."""
<|body_0|>
de... | stack_v2_sparse_classes_10k_train_005851 | 17,464 | no_license | [
{
"docstring": "Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web APIs. Return: comment object.",
"name": "get_object",
"signature": "def get_object(self, id)"
},
{
"docstring": "Get single comment object. Args: request: Django Res... | 3 | stack_v2_sparse_classes_30k_val_000006 | Implement the Python class `CommentViewDetail` described below.
Class description:
This class is an API for geting comment of post detail.
Method signatures and docstrings:
- def get_object(self, id): Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web AP... | Implement the Python class `CommentViewDetail` described below.
Class description:
This class is an API for geting comment of post detail.
Method signatures and docstrings:
- def get_object(self, id): Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web AP... | 1d01b8133669208cdd35d4aa61a41521ecd52720 | <|skeleton|>
class CommentViewDetail:
"""This class is an API for geting comment of post detail."""
def get_object(self, id):
"""Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web APIs. Return: comment object."""
<|body_0|>
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentViewDetail:
"""This class is an API for geting comment of post detail."""
def get_object(self, id):
"""Get comment by id. Args: request: Django Rest Framework request object. id: id of comment. format: pattern for Web APIs. Return: comment object."""
try:
return Comment... | the_stack_v2_python_sparse | newsfeed/views.py | whsatku/social | train | 10 |
fecb3e22946d38845977e65758ca3ade8bc44058 | [
"super().__init__()\nrequire_grad = False\nself.leak = leak\nself.competition = competition\nself.self_excitation = self_excitation\nself.noise = noise\nself.time_step_size = time_step_size\nself.non_decision_time = non_decision_time\nself._sqrt_step_size = torch.sqrt(torch.tensor(0.001, requires_grad=require_grad)... | <|body_start_0|>
super().__init__()
require_grad = False
self.leak = leak
self.competition = competition
self.self_excitation = self_excitation
self.noise = noise
self.time_step_size = time_step_size
self.non_decision_time = non_decision_time
self.... | LCALayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decisi... | stack_v2_sparse_classes_10k_train_005852 | 11,741 | permissive | [
{
"docstring": "An implementation of a Leaky Competing Accumulator as a layer. Each call to forward of this module only implements one time step of the integration. See module LCAModel if you want to simulate an LCA to completion. Args: threshold: The threshold that accumulators must reach to stop integration. ... | 2 | stack_v2_sparse_classes_30k_train_003225 | Implement the Python class `LCALayer` described below.
Class description:
Implement the LCALayer class.
Method signatures and docstrings:
- def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTens... | Implement the Python class `LCALayer` described below.
Class description:
Implement the LCALayer class.
Method signatures and docstrings:
- def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTens... | 424971b04d55a2cddbae4c05a0aae2d7b3502c20 | <|skeleton|>
class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decisi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decision_time: Union... | the_stack_v2_python_sparse | Scripts/Debug/lca/onnx_lca.py | PrincetonUniversity/PsyNeuLink | train | 79 | |
217a341aee4b7786ca130dac10d7d26db2465c58 | [
"ext = []\nif self._is_position(global_step, 'start'):\n ext.append(self._start_search_dir_projection_info())\nif self._is_position(global_step, 'end'):\n ext.append(self._end_search_dir_projection_info())\nreturn ext",
"info = {}\ninfo['params'] = {id(p): p.data.clone().detach() for p in params}\ninfo['f']... | <|body_start_0|>
ext = []
if self._is_position(global_step, 'start'):
ext.append(self._start_search_dir_projection_info())
if self._is_position(global_step, 'end'):
ext.append(self._end_search_dir_projection_info())
return ext
<|end_body_0|>
<|body_start_1|>
... | Optimized α Quantity Class. Does not require storing individual gradients. | AlphaOptimized | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlphaOptimized:
"""Optimized α Quantity Class. Does not require storing individual gradients."""
def extensions(self, global_step):
"""Return list of BackPACK extensions required for the computation. Args: global_step (int): The current iteration number. Returns: list: (Potentially e... | stack_v2_sparse_classes_10k_train_005853 | 16,011 | permissive | [
{
"docstring": "Return list of BackPACK extensions required for the computation. Args: global_step (int): The current iteration number. Returns: list: (Potentially empty) list with required BackPACK quantities.",
"name": "extensions",
"signature": "def extensions(self, global_step)"
},
{
"docstr... | 5 | stack_v2_sparse_classes_30k_train_002844 | Implement the Python class `AlphaOptimized` described below.
Class description:
Optimized α Quantity Class. Does not require storing individual gradients.
Method signatures and docstrings:
- def extensions(self, global_step): Return list of BackPACK extensions required for the computation. Args: global_step (int): Th... | Implement the Python class `AlphaOptimized` described below.
Class description:
Optimized α Quantity Class. Does not require storing individual gradients.
Method signatures and docstrings:
- def extensions(self, global_step): Return list of BackPACK extensions required for the computation. Args: global_step (int): Th... | 5bd5ab3cda03eda0b0bf276f29d5c28b83d70b06 | <|skeleton|>
class AlphaOptimized:
"""Optimized α Quantity Class. Does not require storing individual gradients."""
def extensions(self, global_step):
"""Return list of BackPACK extensions required for the computation. Args: global_step (int): The current iteration number. Returns: list: (Potentially e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlphaOptimized:
"""Optimized α Quantity Class. Does not require storing individual gradients."""
def extensions(self, global_step):
"""Return list of BackPACK extensions required for the computation. Args: global_step (int): The current iteration number. Returns: list: (Potentially empty) list wi... | the_stack_v2_python_sparse | cockpit/quantities/alpha.py | MeNicefellow/cockpit | train | 0 |
953d30b4e14a697e78887ebe837ff05bdda87a1d | [
"if xml is None:\n self.defaultInit()\nelse:\n self.fromXml(xml)",
"self.GPU = Size(XYstr='256x256')\nself.CPU = Size(XYstr='32x32')\nself.BI = Size(XYstr='256x256')",
"self.GPU = Size(xml=xml.find('GPU'))\nself.CPU = Size(xml=xml.find('CPU'))\nself.BI = Size(xml=xml.find('BI'))",
"txt = '<tilesSet>\\n'... | <|body_start_0|>
if xml is None:
self.defaultInit()
else:
self.fromXml(xml)
<|end_body_0|>
<|body_start_1|>
self.GPU = Size(XYstr='256x256')
self.CPU = Size(XYstr='32x32')
self.BI = Size(XYstr='256x256')
<|end_body_1|>
<|body_start_2|>
self.GPU =... | class to manage tiles sizes | Tiles | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tiles:
"""class to manage tiles sizes"""
def __init__(self, xml=None):
"""initialize tiles sizes with default value or values extracted from an xml object"""
<|body_0|>
def defaultInit(self):
"""initialize tiles sizes with default value"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005854 | 2,352 | permissive | [
{
"docstring": "initialize tiles sizes with default value or values extracted from an xml object",
"name": "__init__",
"signature": "def __init__(self, xml=None)"
},
{
"docstring": "initialize tiles sizes with default value",
"name": "defaultInit",
"signature": "def defaultInit(self)"
... | 6 | stack_v2_sparse_classes_30k_train_004116 | Implement the Python class `Tiles` described below.
Class description:
class to manage tiles sizes
Method signatures and docstrings:
- def __init__(self, xml=None): initialize tiles sizes with default value or values extracted from an xml object
- def defaultInit(self): initialize tiles sizes with default value
- def... | Implement the Python class `Tiles` described below.
Class description:
class to manage tiles sizes
Method signatures and docstrings:
- def __init__(self, xml=None): initialize tiles sizes with default value or values extracted from an xml object
- def defaultInit(self): initialize tiles sizes with default value
- def... | 39082e7833383bbe7dd414381f1b295e3b778439 | <|skeleton|>
class Tiles:
"""class to manage tiles sizes"""
def __init__(self, xml=None):
"""initialize tiles sizes with default value or values extracted from an xml object"""
<|body_0|>
def defaultInit(self):
"""initialize tiles sizes with default value"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tiles:
"""class to manage tiles sizes"""
def __init__(self, xml=None):
"""initialize tiles sizes with default value or values extracted from an xml object"""
if xml is None:
self.defaultInit()
else:
self.fromXml(xml)
def defaultInit(self):
"""i... | the_stack_v2_python_sparse | Preferences/Tiles.py | chankeh/Blender-Render-Manager | train | 0 |
dc77d866df98cac34dc54f350b08e3835b31220e | [
"status = _SpawnChild(exit_code=0)\nret = process_util.GetExitStatus(status)\nself.assertEqual(ret, 0)",
"status = _SpawnChild(exit_code=10)\nret = process_util.GetExitStatus(status)\nself.assertEqual(ret, 10)",
"status = _SpawnChild(exit_code=150)\nret = process_util.GetExitStatus(status)\nself.assertEqual(ret... | <|body_start_0|>
status = _SpawnChild(exit_code=0)
ret = process_util.GetExitStatus(status)
self.assertEqual(ret, 0)
<|end_body_0|>
<|body_start_1|>
status = _SpawnChild(exit_code=10)
ret = process_util.GetExitStatus(status)
self.assertEqual(ret, 10)
<|end_body_1|>
<|bo... | Tests for GetExitStatus() | GetExitStatusTests | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetExitStatusTests:
"""Tests for GetExitStatus()"""
def testExitNormal(self):
"""Verify normal exits get decoded."""
<|body_0|>
def testExitError(self):
"""Verify error exits (>0 && <128) get decoded."""
<|body_1|>
def testExitWeird(self):
""... | stack_v2_sparse_classes_10k_train_005855 | 3,622 | permissive | [
{
"docstring": "Verify normal exits get decoded.",
"name": "testExitNormal",
"signature": "def testExitNormal(self)"
},
{
"docstring": "Verify error exits (>0 && <128) get decoded.",
"name": "testExitError",
"signature": "def testExitError(self)"
},
{
"docstring": "Verify weird e... | 5 | null | Implement the Python class `GetExitStatusTests` described below.
Class description:
Tests for GetExitStatus()
Method signatures and docstrings:
- def testExitNormal(self): Verify normal exits get decoded.
- def testExitError(self): Verify error exits (>0 && <128) get decoded.
- def testExitWeird(self): Verify weird e... | Implement the Python class `GetExitStatusTests` described below.
Class description:
Tests for GetExitStatus()
Method signatures and docstrings:
- def testExitNormal(self): Verify normal exits get decoded.
- def testExitError(self): Verify error exits (>0 && <128) get decoded.
- def testExitWeird(self): Verify weird e... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class GetExitStatusTests:
"""Tests for GetExitStatus()"""
def testExitNormal(self):
"""Verify normal exits get decoded."""
<|body_0|>
def testExitError(self):
"""Verify error exits (>0 && <128) get decoded."""
<|body_1|>
def testExitWeird(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetExitStatusTests:
"""Tests for GetExitStatus()"""
def testExitNormal(self):
"""Verify normal exits get decoded."""
status = _SpawnChild(exit_code=0)
ret = process_util.GetExitStatus(status)
self.assertEqual(ret, 0)
def testExitError(self):
"""Verify error ex... | the_stack_v2_python_sparse | third_party/chromite/lib/process_util_unittest.py | metux/chromium-suckless | train | 5 |
88d5991c97626355b1ed549915a34bf8198cbaab | [
"self.maxheap = []\nself.maxsize = 0\nself.minheap = []\nself.minsize = 0\nself.size = 0",
"if not self.size:\n heapq.heappush(self.maxheap, (-num, self.maxsize))\n self.maxsize = 1\n self.size = 1\n return\nif num <= -self.maxheap[0][0]:\n heapq.heappush(self.maxheap, (-num, self.maxsize))\n se... | <|body_start_0|>
self.maxheap = []
self.maxsize = 0
self.minheap = []
self.minsize = 0
self.size = 0
<|end_body_0|>
<|body_start_1|>
if not self.size:
heapq.heappush(self.maxheap, (-num, self.maxsize))
self.maxsize = 1
self.size = 1
... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_005856 | 2,913 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_004429 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: void
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 786e1597b18cf5f16df0a3d7dfa0b80c1435de4d | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.maxheap = []
self.maxsize = 0
self.minheap = []
self.minsize = 0
self.size = 0
def addNum(self, num):
""":type num: int :rtype: void"""
if not self.size:
... | the_stack_v2_python_sparse | No_295_Find_Median_from_Data_Stream.py | georgewashingturd/leetcode | train | 0 | |
6ff7792f69a1898b65fd697cd4ab6587985b835c | [
"try:\n return IngressReports.objects.filter(source=source)\nexcept IngressReports.DoesNotExist:\n return None",
"source = kwargs['source']\ntry:\n UUID(source)\nexcept ValueError:\n return Response({'Error': 'Invalid source uuid.'}, status=status.HTTP_400_BAD_REQUEST)\nreport_instance = self.get_obje... | <|body_start_0|>
try:
return IngressReports.objects.filter(source=source)
except IngressReports.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
source = kwargs['source']
try:
UUID(source)
except ValueError:
return Respons... | View to fetch report details for specific source | IngressReportsDetailView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngressReportsDetailView:
"""View to fetch report details for specific source"""
def get_object(self, source):
"""Helper method to get reports with given source"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return reports for source."""
<|body... | stack_v2_sparse_classes_10k_train_005857 | 3,418 | permissive | [
{
"docstring": "Helper method to get reports with given source",
"name": "get_object",
"signature": "def get_object(self, source)"
},
{
"docstring": "Return reports for source.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `IngressReportsDetailView` described below.
Class description:
View to fetch report details for specific source
Method signatures and docstrings:
- def get_object(self, source): Helper method to get reports with given source
- def get(self, request, *args, **kwargs): Return reports for sour... | Implement the Python class `IngressReportsDetailView` described below.
Class description:
View to fetch report details for specific source
Method signatures and docstrings:
- def get_object(self, source): Helper method to get reports with given source
- def get(self, request, *args, **kwargs): Return reports for sour... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class IngressReportsDetailView:
"""View to fetch report details for specific source"""
def get_object(self, source):
"""Helper method to get reports with given source"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return reports for source."""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IngressReportsDetailView:
"""View to fetch report details for specific source"""
def get_object(self, source):
"""Helper method to get reports with given source"""
try:
return IngressReports.objects.filter(source=source)
except IngressReports.DoesNotExist:
... | the_stack_v2_python_sparse | koku/api/ingress/reports/view.py | project-koku/koku | train | 225 |
c011335626f3e816981972ae5e7c596725e139b7 | [
"counter = Counter(nums)\nres = []\nfor num, count in counter.items():\n if count > len(nums) // 3:\n res.append(num)\nreturn res",
"res = []\ncount1, count2 = (0, 0)\ncand1, cand2 = (int(1e+20), int(1e+30))\nfor num in nums:\n if num == cand1:\n count1 += 1\n elif num == cand2:\n co... | <|body_start_0|>
counter = Counter(nums)
res = []
for num, count in counter.items():
if count > len(nums) // 3:
res.append(num)
return res
<|end_body_0|>
<|body_start_1|>
res = []
count1, count2 = (0, 0)
cand1, cand2 = (int(1e+20), int... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
"""counter肯定是最直接的 O(n)"""
<|body_0|>
def majorityElement2(self, nums: List[int]) -> List[int]:
"""摩尔投票法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
counter = Counter(nums)
... | stack_v2_sparse_classes_10k_train_005858 | 1,368 | no_license | [
{
"docstring": "counter肯定是最直接的 O(n)",
"name": "majorityElement",
"signature": "def majorityElement(self, nums: List[int]) -> List[int]"
},
{
"docstring": "摩尔投票法",
"name": "majorityElement2",
"signature": "def majorityElement2(self, nums: List[int]) -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_003466 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums: List[int]) -> List[int]: counter肯定是最直接的 O(n)
- def majorityElement2(self, nums: List[int]) -> List[int]: 摩尔投票法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums: List[int]) -> List[int]: counter肯定是最直接的 O(n)
- def majorityElement2(self, nums: List[int]) -> List[int]: 摩尔投票法
<|skeleton|>
class Solution:
... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
"""counter肯定是最直接的 O(n)"""
<|body_0|>
def majorityElement2(self, nums: List[int]) -> List[int]:
"""摩尔投票法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
"""counter肯定是最直接的 O(n)"""
counter = Counter(nums)
res = []
for num, count in counter.items():
if count > len(nums) // 3:
res.append(num)
return res
def majorityElement2(s... | the_stack_v2_python_sparse | 19_数学/众数/229. 求众数 II.py | 981377660LMT/algorithm-study | train | 225 | |
2583d285110e1a6627b591a3b3e788d35173cd3a | [
"num_theta = 6\nnum_phi = 4\nexpected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))\ntheta = jnp.linspace(0, math.pi, num_theta)\nphi = jnp.linspace(0, 2.0 * math.pi, num_phi)\nsph_harm = spherical_harmonics.SphericalHarmonics(l_max=0, theta=theta, phi=phi)\nactual = jnp.real(sph_harm.harmo... | <|body_start_0|>
num_theta = 6
num_phi = 4
expected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))
theta = jnp.linspace(0, math.pi, num_theta)
phi = jnp.linspace(0, 2.0 * math.pi, num_phi)
sph_harm = spherical_harmonics.SphericalHarmonics(l_max=0, ... | SphericalHarmonicsTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
<|body_0|>
def testOrderOneDegreeZero(self):
"""Tests the spherical harmonics of order one and degree zero."""
<|body_1|>
def te... | stack_v2_sparse_classes_10k_train_005859 | 4,604 | permissive | [
{
"docstring": "Tests the spherical harmonics of order zero and degree zero.",
"name": "testOrderZeroDegreeZero",
"signature": "def testOrderZeroDegreeZero(self)"
},
{
"docstring": "Tests the spherical harmonics of order one and degree zero.",
"name": "testOrderOneDegreeZero",
"signature... | 5 | stack_v2_sparse_classes_30k_train_004306 | Implement the Python class `SphericalHarmonicsTest` described below.
Class description:
Implement the SphericalHarmonicsTest class.
Method signatures and docstrings:
- def testOrderZeroDegreeZero(self): Tests the spherical harmonics of order zero and degree zero.
- def testOrderOneDegreeZero(self): Tests the spherica... | Implement the Python class `SphericalHarmonicsTest` described below.
Class description:
Implement the SphericalHarmonicsTest class.
Method signatures and docstrings:
- def testOrderZeroDegreeZero(self): Tests the spherical harmonics of order zero and degree zero.
- def testOrderOneDegreeZero(self): Tests the spherica... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
<|body_0|>
def testOrderOneDegreeZero(self):
"""Tests the spherical harmonics of order one and degree zero."""
<|body_1|>
def te... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
num_theta = 6
num_phi = 4
expected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))
theta = jnp.linspace(0, math.pi, num_t... | the_stack_v2_python_sparse | simulation_research/signal_processing/spherical/spherical_harmonics_test.py | Jimmy-INL/google-research | train | 1 | |
c814413a89f1a2ba365ccf859a397170ddd11655 | [
"super().__init__()\nself.reference_sequence_length = reference_sequence_length\nself.reference_hidden_size = reference_hidden_size\nself.context_sequence_length = context_sequence_length\nself.context_hidden_size = context_hidden_size\nself.attention_size = attention_size\nself.individual_nonlinearity = individual... | <|body_start_0|>
super().__init__()
self.reference_sequence_length = reference_sequence_length
self.reference_hidden_size = reference_hidden_size
self.context_sequence_length = context_sequence_length
self.context_hidden_size = context_hidden_size
self.attention_size = at... | Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, pytorch uses U(-stddev, stddev) where stddev=1./math.sqrt(weight.size(1)). | ContextAttentionLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextAttentionLayer:
"""Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, pytorch uses U(-stddev, stddev) where st... | stack_v2_sparse_classes_10k_train_005860 | 25,239 | no_license | [
{
"docstring": "Constructor Arguments: reference_hidden_size (int): Hidden size of the reference input over which the attention will be computed (H). reference_sequence_length (int): Sequence length of the reference (T). context_hidden_size (int): This is either simply the amount of features used as context (G)... | 2 | stack_v2_sparse_classes_30k_train_000443 | Implement the Python class `ContextAttentionLayer` described below.
Class description:
Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, p... | Implement the Python class `ContextAttentionLayer` described below.
Class description:
Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, p... | e88840528fa963066f85940ffeb31687773be2ba | <|skeleton|>
class ContextAttentionLayer:
"""Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, pytorch uses U(-stddev, stddev) where st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContextAttentionLayer:
"""Implements context attention as in the PaccMann paper (Figure 2C) in Molecular Pharmaceutics. With the additional option of having a hidden size in the context. NOTE: In tensorflow, weights were initialized from N(0,0.1). Instead, pytorch uses U(-stddev, stddev) where stddev=1./math.... | the_stack_v2_python_sparse | Utility/layers.py | kaicd/KAICD_pipeline | train | 0 |
6d1d85bbbb581cdd3736cf342f2a9f9659f9c72e | [
"x, x_shape = self._prepare_x(x)\ny = self._evaluate_derivatives(x, der)\ny = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)\nif self._y_axis != 0 and x_shape != ():\n nx = len(x_shape)\n ny = len(self._y_extra_shape)\n s = [0] + list(range(nx + 1, nx + self._y_axis + 1)) + list(range(1, nx + 1))... | <|body_start_0|>
x, x_shape = self._prepare_x(x)
y = self._evaluate_derivatives(x, der)
y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
if self._y_axis != 0 and x_shape != ():
nx = len(x_shape)
ny = len(self._y_extra_shape)
s = [0] + list(... | _Interpolator1DWithDerivatives | [
"Python-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative values at the point x. Parameters ---------- x : array_like Point or points at which to evaluate the derivatives der : int ... | stack_v2_sparse_classes_10k_train_005861 | 22,677 | permissive | [
{
"docstring": "Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative values at the point x. Parameters ---------- x : array_like Point or points at which to evaluate the derivatives der : int or None, optional How many derivatives to extract; None for all potentially non... | 2 | null | Implement the Python class `_Interpolator1DWithDerivatives` described below.
Class description:
Implement the _Interpolator1DWithDerivatives class.
Method signatures and docstrings:
- def derivatives(self, x, der=None): Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative valu... | Implement the Python class `_Interpolator1DWithDerivatives` described below.
Class description:
Implement the _Interpolator1DWithDerivatives class.
Method signatures and docstrings:
- def derivatives(self, x, der=None): Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative valu... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative values at the point x. Parameters ---------- x : array_like Point or points at which to evaluate the derivatives der : int ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x Produce an array of all derivative values at the point x. Parameters ---------- x : array_like Point or points at which to evaluate the derivatives der : int or None, optio... | the_stack_v2_python_sparse | contrib/python/scipy/py2/scipy/interpolate/polyint.py | catboost/catboost | train | 8,012 | |
f59c9bf73253544f8295c3f367fd0232caa4d9c0 | [
"memory = []\n\ndef add_coor(a, b):\n ans = 0\n while a != 0:\n ans += a % 10\n a //= 10\n while b != 0:\n ans += b % 10\n b //= 10\n return ans\n\ndef __dfs(col, row):\n if col >= m or row >= n:\n return\n if [col, row] in memory:\n return\n if add_coo... | <|body_start_0|>
memory = []
def add_coor(a, b):
ans = 0
while a != 0:
ans += a % 10
a //= 10
while b != 0:
ans += b % 10
b //= 10
return ans
def __dfs(col, row):
if col ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递归 巨慢无比"""
<|body_0|>
def movingCount1(self, m: int, n: int, k: int) -> int:
"""比递归快了十倍"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
memory = []
def add_coor(a, b):
... | stack_v2_sparse_classes_10k_train_005862 | 2,545 | no_license | [
{
"docstring": "递归 巨慢无比",
"name": "movingCount",
"signature": "def movingCount(self, m: int, n: int, k: int) -> int"
},
{
"docstring": "比递归快了十倍",
"name": "movingCount1",
"signature": "def movingCount1(self, m: int, n: int, k: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_004724 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 递归 巨慢无比
- def movingCount1(self, m: int, n: int, k: int) -> int: 比递归快了十倍 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def movingCount(self, m: int, n: int, k: int) -> int: 递归 巨慢无比
- def movingCount1(self, m: int, n: int, k: int) -> int: 比递归快了十倍
<|skeleton|>
class Solution:
def movingCount(... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递归 巨慢无比"""
<|body_0|>
def movingCount1(self, m: int, n: int, k: int) -> int:
"""比递归快了十倍"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
"""递归 巨慢无比"""
memory = []
def add_coor(a, b):
ans = 0
while a != 0:
ans += a % 10
a //= 10
while b != 0:
ans += b % 10
b ... | the_stack_v2_python_sparse | 二刷+题解/每日一题/movingCount.py | 1oser5/LeetCode | train | 0 | |
7524de699b009fd91f7aaadb4a8bb3bdbfa2d3bf | [
"curs.execute('DROP TABLE jotd_emails')\nconn.commit()\ncurs.execute(TBLDEF)\nconn.commit()\nclient.run()",
"curs.execute('SELECT * FROM jotd_emails')\nobserved = len(curs.fetchall())\nexpected = DAYCOUNT * len(RECIPIENTS)\nself.assertEqual(observed, expected)",
"curs.execute('SELECT msgDate FROM jotd_emails')\... | <|body_start_0|>
curs.execute('DROP TABLE jotd_emails')
conn.commit()
curs.execute(TBLDEF)
conn.commit()
client.run()
<|end_body_0|>
<|body_start_1|>
curs.execute('SELECT * FROM jotd_emails')
observed = len(curs.fetchall())
expected = DAYCOUNT * len(RECIP... | test_client | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_client:
def setUp(self):
"""Provides each test with a freshly populated table"""
<|body_0|>
def test_table(self):
"""Tests that the appropriate number of emails have been created and stored"""
<|body_1|>
def test_date(self):
"""Tests if each... | stack_v2_sparse_classes_10k_train_005863 | 1,628 | no_license | [
{
"docstring": "Provides each test with a freshly populated table",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests that the appropriate number of emails have been created and stored",
"name": "test_table",
"signature": "def test_table(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_001819 | Implement the Python class `test_client` described below.
Class description:
Implement the test_client class.
Method signatures and docstrings:
- def setUp(self): Provides each test with a freshly populated table
- def test_table(self): Tests that the appropriate number of emails have been created and stored
- def te... | Implement the Python class `test_client` described below.
Class description:
Implement the test_client class.
Method signatures and docstrings:
- def setUp(self): Provides each test with a freshly populated table
- def test_table(self): Tests that the appropriate number of emails have been created and stored
- def te... | ecc38ddc4bb6719bf3a02d04b760722772e20413 | <|skeleton|>
class test_client:
def setUp(self):
"""Provides each test with a freshly populated table"""
<|body_0|>
def test_table(self):
"""Tests that the appropriate number of emails have been created and stored"""
<|body_1|>
def test_date(self):
"""Tests if each... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class test_client:
def setUp(self):
"""Provides each test with a freshly populated table"""
curs.execute('DROP TABLE jotd_emails')
conn.commit()
curs.execute(TBLDEF)
conn.commit()
client.run()
def test_table(self):
"""Tests that the appropriate number of ... | the_stack_v2_python_sparse | emailclient_test.py | aborgo/Certification_Work | train | 0 | |
83cfa08bd310863b47ec6cca55da4ac6173ecaea | [
"size = len(prices)\nif size <= 0:\n return 0\nmaxPro = 0\nfor i in range(size):\n for j in range(i + 1, size):\n maxPro = max(maxPro, self.maxProfit(prices[j + 1:]) + prices[j] - prices[i])\nreturn maxPro",
"size = len(prices)\nif size <= 0:\n return 0\nminIdx = 0\nmaxPro = 0\nfor i in range(1, s... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
maxPro = 0
for i in range(size):
for j in range(i + 1, size):
maxPro = max(maxPro, self.maxProfit(prices[j + 1:]) + prices[j] - prices[i])
return maxPro
<|end_body_0|>
<|body_start... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""暴力优化:消除一层循环+备忘录"""
<|body_1|>
def maxProfit2(self, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录... | stack_v2_sparse_classes_10k_train_005864 | 6,235 | permissive | [
{
"docstring": "暴力思路:无效for...for嵌套转化为递归",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "暴力优化:消除一层循环+备忘录",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices: List[int]) -> int"
},
{
"docstring": "暴力优化2:消除一层循环+备忘录... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力思路:无效for...for嵌套转化为递归
- def maxProfit1(self, prices: List[int]) -> int: 暴力优化:消除一层循环+备忘录
- def maxProfit2(self, prices: List[int])... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力思路:无效for...for嵌套转化为递归
- def maxProfit1(self, prices: List[int]) -> int: 暴力优化:消除一层循环+备忘录
- def maxProfit2(self, prices: List[int])... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""暴力优化:消除一层循环+备忘录"""
<|body_1|>
def maxProfit2(self, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力思路:无效for...for嵌套转化为递归"""
size = len(prices)
if size <= 0:
return 0
maxPro = 0
for i in range(size):
for j in range(i + 1, size):
maxPro = max(maxPro, self.maxProfit(pri... | the_stack_v2_python_sparse | 122-best-time-to-buy-and-sell-stock-ii.py | yuenliou/leetcode | train | 0 | |
8def01fb848c51ca717c6725ca0ca466e169e915 | [
"fixture = [('C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe -s', 'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe'), (\"'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe' -s\", 'C:\\\\Program Files\\\\Realtek\\\\Audio\\\\blah.exe'), ('C:\\\\Program Files\\\\NVIDIA Corporation\\\\nwiz.exe /quiet /blah',... | <|body_start_0|>
fixture = [('C:\\Program Files\\Realtek\\Audio\\blah.exe -s', 'C:\\Program Files\\Realtek\\Audio\\blah.exe'), ("'C:\\Program Files\\Realtek\\Audio\\blah.exe' -s", 'C:\\Program Files\\Realtek\\Audio\\blah.exe'), ('C:\\Program Files\\NVIDIA Corporation\\nwiz.exe /quiet /blah', 'C:\\Program Files\... | Tests for CreateWindowsRegistryExecutablePathsDetector() detector. | WindowsRegistryExecutablePathsDetectorTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
<|body_0|>
def testExctactsPathsFromRunDllStrings(s... | stack_v2_sparse_classes_10k_train_005865 | 8,407 | permissive | [
{
"docstring": "Test it extracts paths from non-rundll strings.",
"name": "testExtractsPathsFromNonRunDllStrings",
"signature": "def testExtractsPathsFromNonRunDllStrings(self)"
},
{
"docstring": "Test it extracts paths from rundll strings.",
"name": "testExctactsPathsFromRunDllStrings",
... | 4 | null | Implement the Python class `WindowsRegistryExecutablePathsDetectorTest` described below.
Class description:
Tests for CreateWindowsRegistryExecutablePathsDetector() detector.
Method signatures and docstrings:
- def testExtractsPathsFromNonRunDllStrings(self): Test it extracts paths from non-rundll strings.
- def test... | Implement the Python class `WindowsRegistryExecutablePathsDetectorTest` described below.
Class description:
Tests for CreateWindowsRegistryExecutablePathsDetector() detector.
Method signatures and docstrings:
- def testExtractsPathsFromNonRunDllStrings(self): Test it extracts paths from non-rundll strings.
- def test... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
<|body_0|>
def testExctactsPathsFromRunDllStrings(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WindowsRegistryExecutablePathsDetectorTest:
"""Tests for CreateWindowsRegistryExecutablePathsDetector() detector."""
def testExtractsPathsFromNonRunDllStrings(self):
"""Test it extracts paths from non-rundll strings."""
fixture = [('C:\\Program Files\\Realtek\\Audio\\blah.exe -s', 'C:\\Pr... | the_stack_v2_python_sparse | grr/core/grr_response_core/path_detection/windows_test.py | google/grr | train | 4,683 |
06e850714657e9824d7d193c6e7476800c351a07 | [
"if not root:\n return 0\ntr_l = root.left\ntr_r = root.right\nmin_depth = 1\nif not tr_l and (not tr_r):\n return min_depth\nelif tr_l and (not tr_r):\n min_depth += self.minDepth(tr_l)\nelif not tr_l and tr_r:\n min_depth += self.minDepth(tr_r)\nelse:\n min_depth += min(self.minDepth(tr_l), self.mi... | <|body_start_0|>
if not root:
return 0
tr_l = root.left
tr_r = root.right
min_depth = 1
if not tr_l and (not tr_r):
return min_depth
elif tr_l and (not tr_r):
min_depth += self.minDepth(tr_l)
elif not tr_l and tr_r:
... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth2(self, root):
"""BFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
tr_l = root.left
tr_r = root.right
... | stack_v2_sparse_classes_10k_train_005866 | 1,714 | permissive | [
{
"docstring": "DFS",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "BFS",
"name": "minDepth2",
"signature": "def minDepth2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004187 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: DFS
- def minDepth2(self, root): BFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: DFS
- def minDepth2(self, root): BFS
<|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS"""
... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS"""
<|body_0|>
def minDepth2(self, root):
"""BFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""DFS"""
if not root:
return 0
tr_l = root.left
tr_r = root.right
min_depth = 1
if not tr_l and (not tr_r):
return min_depth
elif tr_l and (not tr_r):
min_depth += ... | the_stack_v2_python_sparse | leetcode/0111_minimum_depth_of_binary_tree.py | chaosWsF/Python-Practice | train | 1 | |
ad2fd511e1073b47f541f1a9c2ada5414f3f3ff9 | [
"self._gv = gv\nself._dlg = ElevatioBandsDialog()\nself._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)\nself._dlg.move(self._gv.elevationBandsPos)\nself._dlg.okButton.clicked.connect(self.setBands)\nself._dlg.cancelButton.clicked.connect(self._dlg.close)\nself._dlg.elevBandsThreshold... | <|body_start_0|>
self._gv = gv
self._dlg = ElevatioBandsDialog()
self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self._dlg.move(self._gv.elevationBandsPos)
self._dlg.okButton.clicked.connect(self.setBands)
self._dlg.cancelButton.clicked... | Form and functions for defining elevation bands. | ElevationBands | [
"MIT",
"GPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
<|body_0|>
def run(self):
"""Run the form."""
<|body_1|>
def setBands(self):
"""Save bands definition."""
... | stack_v2_sparse_classes_10k_train_005867 | 2,977 | permissive | [
{
"docstring": "Initialise class variables.",
"name": "__init__",
"signature": "def __init__(self, gv)"
},
{
"docstring": "Run the form.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Save bands definition.",
"name": "setBands",
"signature": "def setBand... | 3 | null | Implement the Python class `ElevationBands` described below.
Class description:
Form and functions for defining elevation bands.
Method signatures and docstrings:
- def __init__(self, gv): Initialise class variables.
- def run(self): Run the form.
- def setBands(self): Save bands definition. | Implement the Python class `ElevationBands` described below.
Class description:
Form and functions for defining elevation bands.
Method signatures and docstrings:
- def __init__(self, gv): Initialise class variables.
- def run(self): Run the form.
- def setBands(self): Save bands definition.
<|skeleton|>
class Eleva... | ddb3de70708687ca3167ec4b72ac432426175f45 | <|skeleton|>
class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
<|body_0|>
def run(self):
"""Run the form."""
<|body_1|>
def setBands(self):
"""Save bands definition."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElevationBands:
"""Form and functions for defining elevation bands."""
def __init__(self, gv):
"""Initialise class variables."""
self._gv = gv
self._dlg = ElevatioBandsDialog()
self._dlg.setWindowFlags(self._dlg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self... | the_stack_v2_python_sparse | qswatplus/elevationbands.py | celray/swatplus-automatic-workflow | train | 11 |
bbab6ed2284f420c0b1e85218b76b3b8863bd97d | [
"NonlinearProblem.__init__(self)\nself.type = 'snes'\nself.bcs = bcs\nself.state = state\nalpha = state['alpha']\nV = alpha.function_space()\nalpha_v = TestFunction(V)\ndalpha = TrialFunction(V)\nself.energy = energy\nself.F = derivative(energy, alpha, alpha_v)\nself.J = derivative(self.F, alpha, dalpha)\nself.lb =... | <|body_start_0|>
NonlinearProblem.__init__(self)
self.type = 'snes'
self.bcs = bcs
self.state = state
alpha = state['alpha']
V = alpha.function_space()
alpha_v = TestFunction(V)
dalpha = TrialFunction(V)
self.energy = energy
self.F = deriva... | Class for the damage problem with an NonlinearVariationalProblem. | DamageProblemSNES | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
<|body_0|>
def update_lower_bound(self):
... | stack_v2_sparse_classes_10k_train_005868 | 13,772 | permissive | [
{
"docstring": "Initialises the damage problem. Arguments: * energy * state * boundary conditions",
"name": "__init__",
"signature": "def __init__(self, energy, state, bcs=None)"
},
{
"docstring": "Update lower bound.",
"name": "update_lower_bound",
"signature": "def update_lower_bound(s... | 2 | stack_v2_sparse_classes_30k_train_004020 | Implement the Python class `DamageProblemSNES` described below.
Class description:
Class for the damage problem with an NonlinearVariationalProblem.
Method signatures and docstrings:
- def __init__(self, energy, state, bcs=None): Initialises the damage problem. Arguments: * energy * state * boundary conditions
- def ... | Implement the Python class `DamageProblemSNES` described below.
Class description:
Class for the damage problem with an NonlinearVariationalProblem.
Method signatures and docstrings:
- def __init__(self, energy, state, bcs=None): Initialises the damage problem. Arguments: * energy * state * boundary conditions
- def ... | 9a82bf40742a9b16122b7a476ad8aec65fe22539 | <|skeleton|>
class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
<|body_0|>
def update_lower_bound(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
NonlinearProblem.__init__(self)
self.type = 'snes'
... | the_stack_v2_python_sparse | src/solvers.py | kumiori/stability-bifurcation | train | 1 |
3443b642c15b47ee5a8f373b6f86c22c394f0a6a | [
"if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:\n result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), options.get('column'))\n nu_results = {}\n for ds_key in result:\n if not result[ds_key].empty and ds_key in self.PERSP_COLUMNS:\n for n... | <|body_start_0|>
if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:
result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), options.get('column'))
nu_results = {}
for ds_key in result:
if not result[ds_key].empty and ... | Definição do repo | EmpresaRepository | [
"MIT",
"BSD-3-Clause",
"ISC",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
<|body_0|>
def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name):
"""Filter dataframe by person identification, according t... | stack_v2_sparse_classes_10k_train_005869 | 3,969 | permissive | [
{
"docstring": "Localiza um município pelo código do IBGE",
"name": "find_datasets",
"signature": "def find_datasets(self, options)"
},
{
"docstring": "Filter dataframe by person identification, according to options data",
"name": "filter_by_person",
"signature": "def filter_by_person(da... | 2 | stack_v2_sparse_classes_30k_train_002250 | Implement the Python class `EmpresaRepository` described below.
Class description:
Definição do repo
Method signatures and docstrings:
- def find_datasets(self, options): Localiza um município pelo código do IBGE
- def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name): Filter dataframe by person identi... | Implement the Python class `EmpresaRepository` described below.
Class description:
Definição do repo
Method signatures and docstrings:
- def find_datasets(self, options): Localiza um município pelo código do IBGE
- def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name): Filter dataframe by person identi... | 4f8b09f2dd1227c42d2788553b55159365168080 | <|skeleton|>
class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
<|body_0|>
def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name):
"""Filter dataframe by person identification, according t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:
result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), op... | the_stack_v2_python_sparse | app/repository/empresa/empresa.py | smartlab-br/suetonio-api | train | 1 |
e69623bb5205999e45ab3c7939e17fa981345ad5 | [
"Parametre.__init__(self, 'liste', 'list')\nself.aide_courte = 'liste les tags existants'\nself.aide_longue = 'Cette commande liste les tags existants, groupés par type. La première colonne est le type de tag. La seconde est sa clé. La troisième est le nombre de lignes scripting définies dans ce tag.'",
"tags = t... | <|body_start_0|>
Parametre.__init__(self, 'liste', 'list')
self.aide_courte = 'liste les tags existants'
self.aide_longue = 'Cette commande liste les tags existants, groupés par type. La première colonne est le type de tag. La seconde est sa clé. La troisième est le nombre de lignes scripting dé... | Commande 'tags liste'. | PrmListe | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmListe:
"""Commande 'tags liste'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__init... | stack_v2_sparse_classes_10k_train_005870 | 3,244 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmListe` described below.
Class description:
Commande 'tags liste'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmListe` described below.
Class description:
Commande 'tags liste'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmListe:
"""Commande 'tags liste'.""... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmListe:
"""Commande 'tags liste'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmListe:
"""Commande 'tags liste'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'liste', 'list')
self.aide_courte = 'liste les tags existants'
self.aide_longue = 'Cette commande liste les tags existants, groupés par type. La première col... | the_stack_v2_python_sparse | src/secondaires/tags/commandes/tags/liste.py | vincent-lg/tsunami | train | 5 |
4e0baa3fedeb22a03d1072fcf47b728e57bc2b49 | [
"response = self.client.get('/checkout/')\nself.assertEqual(response.status_code, 302)\nproduct = Product(name='Create a Test', price=1, available_quantity=10)\nproduct.save()\nsession = self.client.session\nsession['bag'] = {product.id: 1}\nsession.save()\nresponse = self.client.get('/checkout/')\nself.assertEqual... | <|body_start_0|>
response = self.client.get('/checkout/')
self.assertEqual(response.status_code, 302)
product = Product(name='Create a Test', price=1, available_quantity=10)
product.save()
session = self.client.session
session['bag'] = {product.id: 1}
session.save... | TestView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestView:
def test_checkout(self):
"""testing if the products page works and template used"""
<|body_0|>
def test_detect_delivery_problem(self):
"""detecting if there is an item that cannot be delivered"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005871 | 2,648 | no_license | [
{
"docstring": "testing if the products page works and template used",
"name": "test_checkout",
"signature": "def test_checkout(self)"
},
{
"docstring": "detecting if there is an item that cannot be delivered",
"name": "test_detect_delivery_problem",
"signature": "def test_detect_deliver... | 2 | stack_v2_sparse_classes_30k_test_000022 | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_checkout(self): testing if the products page works and template used
- def test_detect_delivery_problem(self): detecting if there is an item that cannot be delivered | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_checkout(self): testing if the products page works and template used
- def test_detect_delivery_problem(self): detecting if there is an item that cannot be delivered
<|... | e61dde21f68e84c312016fd2672c138b60b76344 | <|skeleton|>
class TestView:
def test_checkout(self):
"""testing if the products page works and template used"""
<|body_0|>
def test_detect_delivery_problem(self):
"""detecting if there is an item that cannot be delivered"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestView:
def test_checkout(self):
"""testing if the products page works and template used"""
response = self.client.get('/checkout/')
self.assertEqual(response.status_code, 302)
product = Product(name='Create a Test', price=1, available_quantity=10)
product.save()
... | the_stack_v2_python_sparse | checkout/test_views.py | Code-Institute-Submissions/furnitart | train | 0 | |
eb0dd1d6301893897020037559076902ed8522a2 | [
"if not request.user.is_superuser:\n self.queryset = Patient.objects.filter(user__pk=request.user.id)\nreturn super().list(request, args, kwargs)",
"queryset = Patient.objects.get(pk=request.GET['pk'])\nserializer = PatientReadSerializer(queryset, many=False)\nreturn Response(serializer.data)",
"serializer =... | <|body_start_0|>
if not request.user.is_superuser:
self.queryset = Patient.objects.filter(user__pk=request.user.id)
return super().list(request, args, kwargs)
<|end_body_0|>
<|body_start_1|>
queryset = Patient.objects.get(pk=request.GET['pk'])
serializer = PatientReadSeriali... | PatientViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_1|>
def create(self, request, *args, **kwargs)... | stack_v2_sparse_classes_10k_train_005872 | 8,609 | no_license | [
{
"docstring": "Override method to check permissions",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Override method to check permissions",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_train_002583 | Implement the Python class `PatientViewSet` described below.
Class description:
Implement the PatientViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Override method to check permissions
- def retrieve(self, request, *args, **kwargs): Override method to check permissions
- ... | Implement the Python class `PatientViewSet` described below.
Class description:
Implement the PatientViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Override method to check permissions
- def retrieve(self, request, *args, **kwargs): Override method to check permissions
- ... | cf1b9e973be872540dd0f5730df4830c987b9e33 | <|skeleton|>
class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_1|>
def create(self, request, *args, **kwargs)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
if not request.user.is_superuser:
self.queryset = Patient.objects.filter(user__pk=request.user.id)
return super().list(request, args, kwargs)
def retrieve(self, request... | the_stack_v2_python_sparse | backend/modules/patient/views.py | acca90/SleepWeb | train | 0 | |
af52a16954d4515cb5278db525982ad80d620ebd | [
"super(Dialog3DPlot, self).__init__(parent)\nself.setWindowTitle(title)\nself.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)\nself.layout = QtGui.QHBoxLayout(self)\nself.mayavi = MayaviViewer(self)\nself.layout.addWidget(self.mayavi)\nself.messenger = Messenger()",
"if volume is None ... | <|body_start_0|>
super(Dialog3DPlot, self).__init__(parent)
self.setWindowTitle(title)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
self.layout = QtGui.QHBoxLayout(self)
self.mayavi = MayaviViewer(self)
self.layout.addWidget(self.mayavi... | Dialog3DPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog3DPlot:
def __init__(self, parent, title='Plot'):
"""Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header"""
<|body_0|>
def show(self, volume=None):
"""Shows the plot Args: volume (numpy.ndarray): volum... | stack_v2_sparse_classes_10k_train_005873 | 1,120 | no_license | [
{
"docstring": "Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header",
"name": "__init__",
"signature": "def __init__(self, parent, title='Plot')"
},
{
"docstring": "Shows the plot Args: volume (numpy.ndarray): volume to plot",
"name... | 2 | stack_v2_sparse_classes_30k_train_007326 | Implement the Python class `Dialog3DPlot` described below.
Class description:
Implement the Dialog3DPlot class.
Method signatures and docstrings:
- def __init__(self, parent, title='Plot'): Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header
- def show(self,... | Implement the Python class `Dialog3DPlot` described below.
Class description:
Implement the Dialog3DPlot class.
Method signatures and docstrings:
- def __init__(self, parent, title='Plot'): Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header
- def show(self,... | 43c0ab07b72291ffce67e3b7088017e5654e89ca | <|skeleton|>
class Dialog3DPlot:
def __init__(self, parent, title='Plot'):
"""Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header"""
<|body_0|>
def show(self, volume=None):
"""Shows the plot Args: volume (numpy.ndarray): volum... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dialog3DPlot:
def __init__(self, parent, title='Plot'):
"""Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header"""
super(Dialog3DPlot, self).__init__(parent)
self.setWindowTitle(title)
self.setWindowFlags(self.windowFla... | the_stack_v2_python_sparse | annotation/components/Dialog3DPlot.py | potpov/IAN_annotation_tool | train | 12 | |
35b856c324cb40ca03d3a6af3f2448ebc3c74975 | [
"self._action_ph = tf.placeholder(tf.float32, (batch_size, action_size))\nself._batch_size = batch_size\nself._action_size = action_size\nself._build_target = build_target\nself._action_space = spaces.Box(low=-1, high=1, shape=(action_size,))\nself._include_timestep = include_timestep\nsuper(CEMActorPolicy, self)._... | <|body_start_0|>
self._action_ph = tf.placeholder(tf.float32, (batch_size, action_size))
self._batch_size = batch_size
self._action_size = action_size
self._build_target = build_target
self._action_space = spaces.Box(low=-1, high=1, shape=(action_size,))
self._include_tim... | Learned policy for grasping (continuous). Uses CEM for selecting actions. | CEMActorPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CEMActorPolicy:
"""Learned policy for grasping (continuous). Uses CEM for selecting actions."""
def __init__(self, q_func, state_shape, action_size, use_gpu=True, batch_size=64, build_target=False, include_timestep=True, checkpoint=None):
"""Initializes the policy. Args: q_func: Pyth... | stack_v2_sparse_classes_10k_train_005874 | 14,341 | permissive | [
{
"docstring": "Initializes the policy. Args: q_func: Python function that takes in state, action, scope as input and returns Q(state, action) and intermediate endpoints dictionary. state_shape: Tuple of ints describing shape of the state observation. action_size: (int) Size of the vector-encoded action. use_gp... | 3 | stack_v2_sparse_classes_30k_train_003040 | Implement the Python class `CEMActorPolicy` described below.
Class description:
Learned policy for grasping (continuous). Uses CEM for selecting actions.
Method signatures and docstrings:
- def __init__(self, q_func, state_shape, action_size, use_gpu=True, batch_size=64, build_target=False, include_timestep=True, che... | Implement the Python class `CEMActorPolicy` described below.
Class description:
Learned policy for grasping (continuous). Uses CEM for selecting actions.
Method signatures and docstrings:
- def __init__(self, q_func, state_shape, action_size, use_gpu=True, batch_size=64, build_target=False, include_timestep=True, che... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class CEMActorPolicy:
"""Learned policy for grasping (continuous). Uses CEM for selecting actions."""
def __init__(self, q_func, state_shape, action_size, use_gpu=True, batch_size=64, build_target=False, include_timestep=True, checkpoint=None):
"""Initializes the policy. Args: q_func: Pyth... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CEMActorPolicy:
"""Learned policy for grasping (continuous). Uses CEM for selecting actions."""
def __init__(self, q_func, state_shape, action_size, use_gpu=True, batch_size=64, build_target=False, include_timestep=True, checkpoint=None):
"""Initializes the policy. Args: q_func: Python function t... | the_stack_v2_python_sparse | dql_grasping/policies.py | Tarkiyah/googleResearch | train | 11 |
18304955acfc7cdcf25e313a437e1f6a78c305d3 | [
"if len(self.children) == 1 and self.children[0].qname() == (dav_namespace, 'all'):\n return True\n\ndef isAggregate(supportedPrivilege):\n sp = supportedPrivilege.childOfType(Privilege)\n if sp == self:\n\n def find(supportedPrivilege):\n if supportedPrivilege.childOfType(Privilege) == s... | <|body_start_0|>
if len(self.children) == 1 and self.children[0].qname() == (dav_namespace, 'all'):
return True
def isAggregate(supportedPrivilege):
sp = supportedPrivilege.childOfType(Privilege)
if sp == self:
def find(supportedPrivilege):
... | Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1) | Privilege | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Privilege:
"""Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1)"""
def isAggregateOf(self, subprivilege, supportedPrivileges):
"""Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privilege} @param supportedPrivileges: a L{SupportedPrivilegeSe... | stack_v2_sparse_classes_10k_train_005875 | 26,487 | permissive | [
{
"docstring": "Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privilege} @param supportedPrivileges: a L{SupportedPrivilegeSet} @return: C{True} is this privilege is an aggregate of C{subprivilege} according to C{supportedPrivileges}.",
"name": "isAggregateOf",
"signa... | 2 | null | Implement the Python class `Privilege` described below.
Class description:
Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1)
Method signatures and docstrings:
- def isAggregateOf(self, subprivilege, supportedPrivileges): Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privil... | Implement the Python class `Privilege` described below.
Class description:
Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1)
Method signatures and docstrings:
- def isAggregateOf(self, subprivilege, supportedPrivileges): Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privil... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class Privilege:
"""Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1)"""
def isAggregateOf(self, subprivilege, supportedPrivileges):
"""Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privilege} @param supportedPrivileges: a L{SupportedPrivilegeSe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Privilege:
"""Identifies a privilege. (RFC 3744, sections 5.3 and 5.5.1)"""
def isAggregateOf(self, subprivilege, supportedPrivileges):
"""Check whether this privilege is an aggregate of another. @param subprivilege: a L{Privilege} @param supportedPrivileges: a L{SupportedPrivilegeSet} @return: C... | the_stack_v2_python_sparse | txdav/xml/rfc3744.py | ass-a2s/ccs-calendarserver | train | 2 |
84faeb1def341eff7cba0f872c6088ebee2449b4 | [
"k = m + n - 1\ni = m - 1\nj = n - 1\nwhile k > -1:\n if i == -1:\n nums1[k] = nums2[j]\n j -= 1\n elif j == -1:\n nums1[k] = nums1[i]\n i -= 1\n elif nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n i -= 1\n else:\n nums1[k] = nums2[j]\n j -= 1\n k... | <|body_start_0|>
k = m + n - 1
i = m - 1
j = n - 1
while k > -1:
if i == -1:
nums1[k] = nums2[j]
j -= 1
elif j == -1:
nums1[k] = nums1[i]
i -= 1
elif nums1[i] > nums2[j]:
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) ->... | stack_v2_sparse_classes_10k_train_005876 | 1,008 | no_license | [
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1, m, nums2, n)"
},
{
"docstring": "Do not return anything, modify nums1 in-place inste... | 2 | stack_v2_sparse_classes_30k_train_000346 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
-... | 46ab9dabcca845a13f55efcb3f9be3bf3f2908a9 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) ->... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
k = m + n - 1
i = m - 1
j = n - 1
while k > -1:
if i == -1:
... | the_stack_v2_python_sparse | easy/88_merge_sorted_arrays.py | zehrahayirci/LeetCode | train | 0 | |
f8c91b5b8e69df879d8c9e0c59c56209d3229e2e | [
"self.internalModel = kwargs.pop('internal', None)\nself.weights = kwargs.pop('weights', 1.0)\nself.nMomentConditions = kwargs.pop('nMoM', self.internalModel.nParams)\nkwargs.setdefault('k_moms', self.nMomentConditions)\nkwargs.setdefault('k_params', self.internalModel.nParams)\nsuper(GMMgeneric, self).__init__(*ar... | <|body_start_0|>
self.internalModel = kwargs.pop('internal', None)
self.weights = kwargs.pop('weights', 1.0)
self.nMomentConditions = kwargs.pop('nMoM', self.internalModel.nParams)
kwargs.setdefault('k_moms', self.nMomentConditions)
kwargs.setdefault('k_params', self.internalMode... | ! @brief General method of moments base class | GMMgeneric | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univar... | stack_v2_sparse_classes_10k_train_005877 | 9,753 | permissive | [
{
"docstring": "! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univariate model - must have a moment() method.",
"name": "__init__",
"signature": "def __init__(self, *args, **kw... | 2 | stack_v2_sparse_classes_30k_val_000369 | Implement the Python class `GMMgeneric` described below.
Class description:
! @brief General method of moments base class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (o... | Implement the Python class `GMMgeneric` described below.
Class description:
! @brief General method of moments base class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (o... | 7b63c29e2c31d8ff36ac261381e7e95339421d7e | <|skeleton|>
class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univariate model - ... | the_stack_v2_python_sparse | starvine/uvar/uvmodels/uv_base.py | NinelK/StarVine | train | 0 |
d60d4a77f44b3a8cce24c974deac3c20b63bd6d8 | [
"for cube in cubes:\n self._fix_names(cube)\n self._fix_units(cube)\n self._fix_time(cube)\n fix_longitude(cube)\n self._fix_bounds(cube)\nreturn cubes",
"frequency = self.vardef.frequency\nif frequency in ('day', '3hr'):\n fix_time_day(cube)\nelif frequency == 'mon':\n fix_time_month(cube)\n... | <|body_start_0|>
for cube in cubes:
self._fix_names(cube)
self._fix_units(cube)
self._fix_time(cube)
fix_longitude(cube)
self._fix_bounds(cube)
return cubes
<|end_body_0|>
<|body_start_1|>
frequency = self.vardef.frequency
if f... | Fixes for pr. | Pr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
<|body_0|>
def _fix_time(self, cube):
"""Fix time."""
<|body_1|>
def _fix_units(self, cube):
"""Convert units from mm/[t] to kg m-2 s-1 units."""
<|body_2|>
... | stack_v2_sparse_classes_10k_train_005878 | 3,891 | permissive | [
{
"docstring": "Fix metadata.",
"name": "fix_metadata",
"signature": "def fix_metadata(self, cubes)"
},
{
"docstring": "Fix time.",
"name": "_fix_time",
"signature": "def _fix_time(self, cube)"
},
{
"docstring": "Convert units from mm/[t] to kg m-2 s-1 units.",
"name": "_fix_... | 5 | stack_v2_sparse_classes_30k_train_006253 | Implement the Python class `Pr` described below.
Class description:
Fixes for pr.
Method signatures and docstrings:
- def fix_metadata(self, cubes): Fix metadata.
- def _fix_time(self, cube): Fix time.
- def _fix_units(self, cube): Convert units from mm/[t] to kg m-2 s-1 units.
- def _fix_bounds(self, cube): Add boun... | Implement the Python class `Pr` described below.
Class description:
Fixes for pr.
Method signatures and docstrings:
- def fix_metadata(self, cubes): Fix metadata.
- def _fix_time(self, cube): Fix time.
- def _fix_units(self, cube): Convert units from mm/[t] to kg m-2 s-1 units.
- def _fix_bounds(self, cube): Add boun... | d5187438fea2928644cb53ecb26c6adb1e4cc947 | <|skeleton|>
class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
<|body_0|>
def _fix_time(self, cube):
"""Fix time."""
<|body_1|>
def _fix_units(self, cube):
"""Convert units from mm/[t] to kg m-2 s-1 units."""
<|body_2|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
for cube in cubes:
self._fix_names(cube)
self._fix_units(cube)
self._fix_time(cube)
fix_longitude(cube)
self._fix_bounds(cube)
return cubes
d... | the_stack_v2_python_sparse | esmvalcore/cmor/_fixes/native6/mswep.py | ESMValGroup/ESMValCore | train | 41 |
1060748d852c981d2ebb7586e2725fff7b4f96d2 | [
"warnings.warn('In following versions this function will become deprecated. Use deepattractornet_reconstructor.py instead', Warning)\nsuper(DeepattractorSoftmaxReconstructor, self).__init__(conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation)\nusedbins_names = conf['usedbins'].split(' ')\nusedbins_da... | <|body_start_0|>
warnings.warn('In following versions this function will become deprecated. Use deepattractornet_reconstructor.py instead', Warning)
super(DeepattractorSoftmaxReconstructor, self).__init__(conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation)
usedbins_names = conf['... | the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers | DeepattractorSoftmaxReconstructor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constr... | stack_v2_sparse_classes_10k_train_005879 | 3,997 | permissive | [
{
"docstring": "DeepclusteringReconstructor constructor Args: conf: the reconstructor configuration as a dictionary evalconf: the evaluator configuration as a ConfigParser dataconf: the database configuration rec_dir: the directory where the reconstructions will be stored task: task name",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_005028 | Implement the Python class `DeepattractorSoftmaxReconstructor` described below.
Class description:
the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers
Method signatures and docstrings:
- def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_fra... | Implement the Python class `DeepattractorSoftmaxReconstructor` described below.
Class description:
the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers
Method signatures and docstrings:
- def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_fra... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constructor Args: c... | the_stack_v2_python_sparse | nabu/postprocessing/reconstructors/deepattractornet_softmax_reconstructor.py | JeroenZegers/Nabu-MSSS | train | 19 |
e68a064cc0d770a60b519bda6817d7405b32dae5 | [
"graph = {}\nfor flight in flights:\n u, v, w = flight\n if u not in graph:\n graph[u] = {}\n graph[u][v] = w\ndist = [-1] * n\ndist[src] = 0\nqueue = [src]\nstep = 0\nprint(graph)\nwhile len(queue) > 0:\n qlen = len(queue)\n step += 1\n if step > K + 1:\n break\n for i in range(q... | <|body_start_0|>
graph = {}
for flight in flights:
u, v, w = flight
if u not in graph:
graph[u] = {}
graph[u][v] = w
dist = [-1] * n
dist[src] = 0
queue = [src]
step = 0
print(graph)
while len(queue) > 0:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
<|body_0|>
def findCheapestPrice(self, n, flights, src, dst, K):
""":type n: int :type flights... | stack_v2_sparse_classes_10k_train_005880 | 2,157 | no_license | [
{
"docstring": ":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int",
"name": "findCheapestPrice_DFS",
"signature": "def findCheapestPrice_DFS(self, n, flights, src, dst, K)"
},
{
"docstring": ":type n: int :type flights: List[List[int]] :type src: ... | 2 | stack_v2_sparse_classes_30k_train_004035 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCheapestPrice_DFS(self, n, flights, src, dst, K): :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int
- def findCheapestPri... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCheapestPrice_DFS(self, n, flights, src, dst, K): :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int
- def findCheapestPri... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
<|body_0|>
def findCheapestPrice(self, n, flights, src, dst, K):
""":type n: int :type flights... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findCheapestPrice_DFS(self, n, flights, src, dst, K):
""":type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int"""
graph = {}
for flight in flights:
u, v, w = flight
if u not in graph:
gra... | the_stack_v2_python_sparse | 2019/bfs/cheapest_flights_within_k_stops_787.py | yehongyu/acode | train | 0 | |
44cbd94e285adb6554f5e565192f72037dae8cc5 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('henryhcy_wangyp', 'henryhcy_wangyp')\nincome = repo['henryhcy_wangyp.income']\npoverty = repo['henryhcy_wangyp.poverty']\ninfo = []\nfor i in income.find():\n i = i.copy()\n temp = poverty.find_one... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('henryhcy_wangyp', 'henryhcy_wangyp')
income = repo['henryhcy_wangyp.income']
poverty = repo['henryhcy_wangyp.poverty']
info = []
f... | mergeIncomePoverty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mergeIncomePoverty:
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 every... | stack_v2_sparse_classes_10k_train_005881 | 4,296 | 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_006618 | Implement the Python class `mergeIncomePoverty` described below.
Class description:
Implement the mergeIncomePoverty 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(), startTi... | Implement the Python class `mergeIncomePoverty` described below.
Class description:
Implement the mergeIncomePoverty 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(), startTi... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class mergeIncomePoverty:
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 every... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mergeIncomePoverty:
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('henryhcy_wangyp', 'henryhcy_wang... | the_stack_v2_python_sparse | henryhcy_wangyp/mergeIncomePoverty.py | maximega/course-2019-spr-proj | train | 2 | |
e5b4f9e2ef7d1e0480bf0a77b9fc83a2bc55238a | [
"LayoutItem.__init__(self, dom, parent_element, text_object, mxd, arc_doc)\nself.dom = dom\nself.parent_element = parent_element\nself.text_object = text_object\nself.mxd = mxd\nself.arc_doc = arc_doc",
"arcpy_item = LayoutItem.get_arcpy_layout_element(self, self.layout_item_object)\nLayoutItemText.set_size_and_p... | <|body_start_0|>
LayoutItem.__init__(self, dom, parent_element, text_object, mxd, arc_doc)
self.dom = dom
self.parent_element = parent_element
self.text_object = text_object
self.mxd = mxd
self.arc_doc = arc_doc
<|end_body_0|>
<|body_start_1|>
arcpy_item = Layout... | LayoutItemText | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutItemText:
def __init__(self, dom, parent_element, text_object, mxd, arc_doc):
"""This function creates a Text-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param text_object: The text-object ... | stack_v2_sparse_classes_10k_train_005882 | 3,090 | permissive | [
{
"docstring": "This function creates a Text-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param text_object: The text-object itself as ArcObject :param mxd: the arcpy mxd-document :param arc_doc: the ArcObject IMxDocumen... | 2 | stack_v2_sparse_classes_30k_train_005536 | Implement the Python class `LayoutItemText` described below.
Class description:
Implement the LayoutItemText class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, text_object, mxd, arc_doc): This function creates a Text-Item for the layout :param dom: the Document Object Model :param pare... | Implement the Python class `LayoutItemText` described below.
Class description:
Implement the LayoutItemText class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, text_object, mxd, arc_doc): This function creates a Text-Item for the layout :param dom: the Document Object Model :param pare... | cd0aa5f533194c85cf6e098fadc079ea61b63fce | <|skeleton|>
class LayoutItemText:
def __init__(self, dom, parent_element, text_object, mxd, arc_doc):
"""This function creates a Text-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param text_object: The text-object ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayoutItemText:
def __init__(self, dom, parent_element, text_object, mxd, arc_doc):
"""This function creates a Text-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param text_object: The text-object itself as ArcO... | the_stack_v2_python_sparse | layout/layoutItemText.py | avaldeon/mapqonverter | train | 0 | |
4c65af1788cb863432480687edbbecdcf4f427ce | [
"self.holder_name = holder_name\nself.exp_month = exp_month\nself.exp_year = exp_year\nself.billing_address_id = billing_address_id\nself.billing_address = billing_address\nself.metadata = metadata\nself.label = label",
"if dictionary is None:\n return None\nholder_name = dictionary.get('holder_name')\nexp_mon... | <|body_start_0|>
self.holder_name = holder_name
self.exp_month = exp_month
self.exp_year = exp_year
self.billing_address_id = billing_address_id
self.billing_address = billing_address
self.metadata = metadata
self.label = label
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string): Id of the address to be used as billing address billing_address (BillingAddress1): TODO:... | CustomersCardsRequest1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomersCardsRequest1:
"""Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string): Id of the address to be used as billin... | stack_v2_sparse_classes_10k_train_005883 | 3,135 | permissive | [
{
"docstring": "Constructor for the CustomersCardsRequest1 class",
"name": "__init__",
"signature": "def __init__(self, holder_name=None, exp_month=None, exp_year=None, billing_address_id=None, billing_address=None, metadata=None, label=None)"
},
{
"docstring": "Creates an instance of this model... | 2 | stack_v2_sparse_classes_30k_train_000642 | Implement the Python class `CustomersCardsRequest1` described below.
Class description:
Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string):... | Implement the Python class `CustomersCardsRequest1` described below.
Class description:
Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string):... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class CustomersCardsRequest1:
"""Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string): Id of the address to be used as billin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomersCardsRequest1:
"""Implementation of the 'Customers Cards Request1' model. TODO: type model description here. Attributes: holder_name (string): Holder name exp_month (int): Expiration month exp_year (int): Expiration year billing_address_id (string): Id of the address to be used as billing address bil... | the_stack_v2_python_sparse | mundiapi/models/customers_cards_request_1.py | mundipagg/MundiAPI-PYTHON | train | 10 |
32a68502dcef40c8efde77e22310f38b5fd2d2f6 | [
"data = self.get_json()\nif 'rfamp' not in data and 'lockloss' not in data:\n return self.error('Need to provide at least one of rfamp or lockloss measurement')\nwith self.Session() as session:\n event = session.scalars(EarthquakeEvent.select(session.user_or_token).where(EarthquakeEvent.event_id == earthquake... | <|body_start_0|>
data = self.get_json()
if 'rfamp' not in data and 'lockloss' not in data:
return self.error('Need to provide at least one of rfamp or lockloss measurement')
with self.Session() as session:
event = session.scalars(EarthquakeEvent.select(session.user_or_tok... | EarthquakeMeasurementHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_d... | stack_v2_sparse_classes_10k_train_005884 | 28,208 | permissive | [
{
"docstring": "--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_detector_id required: true schema: type: string responses: 200: content: application/json: schem... | 4 | null | Implement the Python class `EarthquakeMeasurementHandler` described below.
Class description:
Implement the EarthquakeMeasurementHandler class.
Method signatures and docstrings:
- async def post(self, earthquake_id, mma_detector_id): --- description: Provide a ground velocity measurement for the earthquake. tags: - e... | Implement the Python class `EarthquakeMeasurementHandler` described below.
Class description:
Implement the EarthquakeMeasurementHandler class.
Method signatures and docstrings:
- async def post(self, earthquake_id, mma_detector_id): --- description: Provide a ground velocity measurement for the earthquake. tags: - e... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EarthquakeMeasurementHandler:
async def post(self, earthquake_id, mma_detector_id):
"""--- description: Provide a ground velocity measurement for the earthquake. tags: - earthquakeevents parameters: - in: path name: earthquake_id required: true schema: type: string - in: path name: mma_detector_id req... | the_stack_v2_python_sparse | skyportal/handlers/api/earthquake.py | skyportal/skyportal | train | 80 | |
edca37b31261169336906d806fc37b6d3e0f0266 | [
"print('ouput level = ' + str(ILog.get_output_level()))\nself.__test_output_all('default')\nfor i in range(1, 4):\n ILog.set_output_level(i)\n print('set ouput level = ' + str(i))\n self.__test_output_all('lv = ' + str(i))",
"ILog.error('error message: ' + _postfix)\nILog.warn('warning message: ' + _po... | <|body_start_0|>
print('ouput level = ' + str(ILog.get_output_level()))
self.__test_output_all('default')
for i in range(1, 4):
ILog.set_output_level(i)
print('set ouput level = ' + str(i))
self.__test_output_all('lv = ' + str(i))
<|end_body_0|>
<|body_start_... | test: Logger | TestIFGILogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIFGILogger:
"""test: Logger"""
def test_logger(self):
"""test logger."""
<|body_0|>
def __test_output_all(self, _postfix):
"""test subroutine to test all the output level"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('ouput level = '... | stack_v2_sparse_classes_10k_train_005885 | 1,114 | no_license | [
{
"docstring": "test logger.",
"name": "test_logger",
"signature": "def test_logger(self)"
},
{
"docstring": "test subroutine to test all the output level",
"name": "__test_output_all",
"signature": "def __test_output_all(self, _postfix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006699 | Implement the Python class `TestIFGILogger` described below.
Class description:
test: Logger
Method signatures and docstrings:
- def test_logger(self): test logger.
- def __test_output_all(self, _postfix): test subroutine to test all the output level | Implement the Python class `TestIFGILogger` described below.
Class description:
test: Logger
Method signatures and docstrings:
- def test_logger(self): test logger.
- def __test_output_all(self, _postfix): test subroutine to test all the output level
<|skeleton|>
class TestIFGILogger:
"""test: Logger"""
def... | f163b6b9e15100d223ddf4e180727a2b63fbae2d | <|skeleton|>
class TestIFGILogger:
"""test: Logger"""
def test_logger(self):
"""test logger."""
<|body_0|>
def __test_output_all(self, _postfix):
"""test subroutine to test all the output level"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestIFGILogger:
"""test: Logger"""
def test_logger(self):
"""test logger."""
print('ouput level = ' + str(ILog.get_output_level()))
self.__test_output_all('default')
for i in range(1, 4):
ILog.set_output_level(i)
print('set ouput level = ' + str(i))... | the_stack_v2_python_sparse | ifgi/base/test_ILog.py | yamauchih/ifgi-path-tracer | train | 0 |
dc6f46607dff4520cfc2334d91b227d487ad7acc | [
"out_put_file = open(PARSE_OUT_FILE, 'w')\ndat_dict = dict()\ndat_dict['last_catch_logs_date'] = self.last_catch_logs_date\ndat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num\npickle.dump(dat_dict, out_put_file)\nout_put_file.close()",
"if os.path.exists(PARSE_OUT_FILE):\n out_put_file = open... | <|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
out_put_file.close()
<|end_bod... | CatchData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_... | stack_v2_sparse_classes_10k_train_005886 | 3,325 | no_license | [
{
"docstring": "保存配置",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "加载",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001277 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载
<|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
... | ff2afd6d29e9dce6157a66ff62b4d1ea97d04184 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CatchData:
def put(self):
"""保存配置"""
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
... | the_stack_v2_python_sparse | apps/logs/catch_game_logs.py | robot-nan/GameLogServer | train | 0 | |
b8334cbc1224ec4df7aa5ff7657702a5b201a883 | [
"self._identity = identity\nself._results = results\nself._service = service\nself._schema = schema or service.schema\nself._params = params\nself._links_tpl = links_tpl\nself._links_item_tpl = links_item_tpl\nself._expand = expand",
"for hit in self._results:\n record = self._service.record_cls.loads(hit.to_d... | <|body_start_0|>
self._identity = identity
self._results = results
self._service = service
self._schema = schema or service.schema
self._params = params
self._links_tpl = links_tpl
self._links_item_tpl = links_item_tpl
self._expand = expand
<|end_body_0|>
... | List of result items. | CommunityListResult | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunityListResult:
"""List of result items."""
def __init__(self, service, identity, results, params=None, links_tpl=None, links_item_tpl=None, schema=None, expandable_fields=None, expand=False):
"""Constructor. :params service: a service instance :params identity: an identity that... | stack_v2_sparse_classes_10k_train_005887 | 3,427 | permissive | [
{
"docstring": "Constructor. :params service: a service instance :params identity: an identity that performed the service request :params results: the db search results :params params: dictionary of the query parameters",
"name": "__init__",
"signature": "def __init__(self, service, identity, results, p... | 2 | stack_v2_sparse_classes_30k_train_002916 | Implement the Python class `CommunityListResult` described below.
Class description:
List of result items.
Method signatures and docstrings:
- def __init__(self, service, identity, results, params=None, links_tpl=None, links_item_tpl=None, schema=None, expandable_fields=None, expand=False): Constructor. :params servi... | Implement the Python class `CommunityListResult` described below.
Class description:
List of result items.
Method signatures and docstrings:
- def __init__(self, service, identity, results, params=None, links_tpl=None, links_item_tpl=None, schema=None, expandable_fields=None, expand=False): Constructor. :params servi... | 9a17455c06bf606c19c6b1367e4e3d36bf017be9 | <|skeleton|>
class CommunityListResult:
"""List of result items."""
def __init__(self, service, identity, results, params=None, links_tpl=None, links_item_tpl=None, schema=None, expandable_fields=None, expand=False):
"""Constructor. :params service: a service instance :params identity: an identity that... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommunityListResult:
"""List of result items."""
def __init__(self, service, identity, results, params=None, links_tpl=None, links_item_tpl=None, schema=None, expandable_fields=None, expand=False):
"""Constructor. :params service: a service instance :params identity: an identity that performed th... | the_stack_v2_python_sparse | invenio_communities/communities/services/results.py | inveniosoftware/invenio-communities | train | 5 |
b41893c9d8fe370d24fde34039977d2efb92d2eb | [
"inv.Inventory.__init__(self, item_code, description, market_price, rental_price)\nself.material = material\nself.size = size",
"outputdict = {}\noutputdict['item_code'] = self.item_code\noutputdict['description'] = self.description\noutputdict['market_price'] = self.market_price\noutputdict['rental_price'] = sel... | <|body_start_0|>
inv.Inventory.__init__(self, item_code, description, market_price, rental_price)
self.material = material
self.size = size
<|end_body_0|>
<|body_start_1|>
outputdict = {}
outputdict['item_code'] = self.item_code
outputdict['description'] = self.descripti... | some stuff5 | Furniture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Furniture:
"""some stuff5"""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""some stuff6"""
<|body_0|>
def return_as_dictionary(self):
"""some stuff7"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
inv.... | stack_v2_sparse_classes_10k_train_005888 | 899 | no_license | [
{
"docstring": "some stuff6",
"name": "__init__",
"signature": "def __init__(self, item_code, description, market_price, rental_price, material, size)"
},
{
"docstring": "some stuff7",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
}
] | 2 | null | Implement the Python class `Furniture` described below.
Class description:
some stuff5
Method signatures and docstrings:
- def __init__(self, item_code, description, market_price, rental_price, material, size): some stuff6
- def return_as_dictionary(self): some stuff7 | Implement the Python class `Furniture` described below.
Class description:
some stuff5
Method signatures and docstrings:
- def __init__(self, item_code, description, market_price, rental_price, material, size): some stuff6
- def return_as_dictionary(self): some stuff7
<|skeleton|>
class Furniture:
"""some stuff5... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Furniture:
"""some stuff5"""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""some stuff6"""
<|body_0|>
def return_as_dictionary(self):
"""some stuff7"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Furniture:
"""some stuff5"""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""some stuff6"""
inv.Inventory.__init__(self, item_code, description, market_price, rental_price)
self.material = material
self.size = size
def return... | the_stack_v2_python_sparse | students/ScotchWSplenda/lesson01/assignment/inventory_management/furniture_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
21ed2d9ce79d50a07d917a02c99ea4a1e17ec838 | [
"def walk(root, lower, upper):\n if not root:\n return True\n if root.val > lower and root.val < upper:\n return walk(root.left, lower, root.val) and walk(root.right, root.val, upper)\n else:\n return False\nreturn walk(root, float('-inf'), float('inf'))",
"def isValid(root, smaller,... | <|body_start_0|>
def walk(root, lower, upper):
if not root:
return True
if root.val > lower and root.val < upper:
return walk(root.left, lower, root.val) and walk(root.right, root.val, upper)
else:
return False
return wa... | ValidBST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidBST:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST2(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def walk(root, lower, upper):
if n... | stack_v2_sparse_classes_10k_train_005889 | 942 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST2",
"signature": "def isValidBST2(self, root)"
}
] | 2 | null | Implement the Python class `ValidBST` described below.
Class description:
Implement the ValidBST class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBST2(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `ValidBST` described below.
Class description:
Implement the ValidBST class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBST2(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class ValidBST:
def isValidBST(s... | e7f486114df17918e49d6452c7047c9d90e8aef2 | <|skeleton|>
class ValidBST:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST2(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValidBST:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
def walk(root, lower, upper):
if not root:
return True
if root.val > lower and root.val < upper:
return walk(root.left, lower, root.val) and walk(root.right, ro... | the_stack_v2_python_sparse | tranquil-beach/tree/valid_bst.py | yokolet/tranquil-beach-python | train | 0 | |
197218acd377297b9572b9c6ee16525240f327c6 | [
"if target < candidates[0]:\n return set()\nif target == candidates[0]:\n return {(target,)}\ns = set()\nr1 = self.combinationSum(candidates[1:], target)\ns.update(r1)\nr2 = {(candidates[0],) + e for e in self.combinationSum(candidates, target - candidates[0])}\ns.update(r2)\nreturn s",
"if candidates == []... | <|body_start_0|>
if target < candidates[0]:
return set()
if target == candidates[0]:
return {(target,)}
s = set()
r1 = self.combinationSum(candidates[1:], target)
s.update(r1)
r2 = {(candidates[0],) + e for e in self.combinationSum(candidates, targ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
<|body_0|>
def combinationSum(self, candidates, target):
... | stack_v2_sparse_classes_10k_train_005890 | 1,708 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])",
"name": "combinationSumSorted",
"signature": "def combinationSumSorted(self, candidates, target)"
},
{
"docstring": ":type candid... | 2 | stack_v2_sparse_classes_30k_train_001661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSumSorted(self, candidates, target): :type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSumSorted(self, candidates, target): :type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) ... | d2e8b2dca40fc955045eb62e576c776bad8ee5f1 | <|skeleton|>
class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
<|body_0|>
def combinationSum(self, candidates, target):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
if target < candidates[0]:
return set()
if target == cand... | the_stack_v2_python_sparse | combination-sum/combination-sum.py | childe/leetcode | train | 2 | |
d5a55efd4830497d20281ac9a049b8c32ce863c2 | [
"data = {'ok': False, 'message': exception.message}\nresult = dumps(data) + '\\n'\nresp = make_response(result, exception.code)\nresp.headers['Content-Type'] = self.content_type\nreturn resp",
"method = getattr(self, request.method.lower(), None)\nif method is None and request.method == 'HEAD':\n method = geta... | <|body_start_0|>
data = {'ok': False, 'message': exception.message}
result = dumps(data) + '\n'
resp = make_response(result, exception.code)
resp.headers['Content-Type'] = self.content_type
return resp
<|end_body_0|>
<|body_start_1|>
method = getattr(self, request.method... | 自定义 View 类 json 序列化,异常处理,装饰器支持 | RestView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestView:
"""自定义 View 类 json 序列化,异常处理,装饰器支持"""
def handler_error(self, exception):
"""处理异常"""
<|body_0|>
def dispatch_request(self, *args, **kwargs):
"""重写父类方法,支持数据自动序列化"""
<|body_1|>
def unpack(value):
"""解析视图方法返回值"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k_train_005891 | 3,102 | permissive | [
{
"docstring": "处理异常",
"name": "handler_error",
"signature": "def handler_error(self, exception)"
},
{
"docstring": "重写父类方法,支持数据自动序列化",
"name": "dispatch_request",
"signature": "def dispatch_request(self, *args, **kwargs)"
},
{
"docstring": "解析视图方法返回值",
"name": "unpack",
... | 3 | stack_v2_sparse_classes_30k_train_001877 | Implement the Python class `RestView` described below.
Class description:
自定义 View 类 json 序列化,异常处理,装饰器支持
Method signatures and docstrings:
- def handler_error(self, exception): 处理异常
- def dispatch_request(self, *args, **kwargs): 重写父类方法,支持数据自动序列化
- def unpack(value): 解析视图方法返回值 | Implement the Python class `RestView` described below.
Class description:
自定义 View 类 json 序列化,异常处理,装饰器支持
Method signatures and docstrings:
- def handler_error(self, exception): 处理异常
- def dispatch_request(self, *args, **kwargs): 重写父类方法,支持数据自动序列化
- def unpack(value): 解析视图方法返回值
<|skeleton|>
class RestView:
"""自定义 ... | 655bb48711537efb7856a50dcab55f2380ea127a | <|skeleton|>
class RestView:
"""自定义 View 类 json 序列化,异常处理,装饰器支持"""
def handler_error(self, exception):
"""处理异常"""
<|body_0|>
def dispatch_request(self, *args, **kwargs):
"""重写父类方法,支持数据自动序列化"""
<|body_1|>
def unpack(value):
"""解析视图方法返回值"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestView:
"""自定义 View 类 json 序列化,异常处理,装饰器支持"""
def handler_error(self, exception):
"""处理异常"""
data = {'ok': False, 'message': exception.message}
result = dumps(data) + '\n'
resp = make_response(result, exception.code)
resp.headers['Content-Type'] = self.content_typ... | the_stack_v2_python_sparse | rmon/common/rest.py | lvsoso/rmon | train | 0 |
6e3aaee3eee289eed36819c1b0b53c39d0ead6a0 | [
"self.eula = kwargs.pop('eula', None)\nself.content_type_id = kwargs.pop('content_type_id', None)\nself.object_pk = kwargs.pop('object_pk', None)\nsuper(SignEULAForm, self).__init__(*args, **kwargs)\nself.fields['accept'].widget.attrs.update({'class': 'required'})",
"if self.content_type_id is not None and self.o... | <|body_start_0|>
self.eula = kwargs.pop('eula', None)
self.content_type_id = kwargs.pop('content_type_id', None)
self.object_pk = kwargs.pop('object_pk', None)
super(SignEULAForm, self).__init__(*args, **kwargs)
self.fields['accept'].widget.attrs.update({'class': 'required'})
<|e... | Display accept and next fields on EULA form. | SignEULAForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
<|body_0|>
def save(self, request):
"""Save the UserEULA and return the saved object."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_005892 | 1,601 | no_license | [
{
"docstring": "Initialise variables.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save the UserEULA and return the saved object.",
"name": "save",
"signature": "def save(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006292 | Implement the Python class `SignEULAForm` described below.
Class description:
Display accept and next fields on EULA form.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialise variables.
- def save(self, request): Save the UserEULA and return the saved object. | Implement the Python class `SignEULAForm` described below.
Class description:
Display accept and next fields on EULA form.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialise variables.
- def save(self, request): Save the UserEULA and return the saved object.
<|skeleton|>
class SignEU... | 9219e6c5a49eecd1c66dd1b518640c5d678acab6 | <|skeleton|>
class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
<|body_0|>
def save(self, request):
"""Save the UserEULA and return the saved object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SignEULAForm:
"""Display accept and next fields on EULA form."""
def __init__(self, *args, **kwargs):
"""Initialise variables."""
self.eula = kwargs.pop('eula', None)
self.content_type_id = kwargs.pop('content_type_id', None)
self.object_pk = kwargs.pop('object_pk', None)
... | the_stack_v2_python_sparse | tunobase/eula/forms.py | unomena/tunobase | train | 0 |
8e44d12efc2eb8f81bb8235c50df34da1b3839d1 | [
"cur_frame = None\ntry:\n 1 / 0\nexcept ZeroDivisionError:\n cur_frame = sys.exc_info()[2].tb_frame\nfor i in range(skip + 2):\n cur_frame = cur_frame.f_back\nstack_trace = []\nwhile cur_frame is not None:\n stack_trace.append((cur_frame, cur_frame.f_lineno))\n cur_frame = cur_frame.f_back\nreturn st... | <|body_start_0|>
cur_frame = None
try:
1 / 0
except ZeroDivisionError:
cur_frame = sys.exc_info()[2].tb_frame
for i in range(skip + 2):
cur_frame = cur_frame.f_back
stack_trace = []
while cur_frame is not None:
stack_trace.a... | Utilities for accessing the full stack trace of your application. | CommonStacktraceUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
<|body_0|>
def _exte... | stack_v2_sparse_classes_10k_train_005893 | 2,612 | permissive | [
{
"docstring": "Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack.",
"name": "current_stack",
"signature": "def current_stack(skip: int=0) -> Any"
},
{
"docstring": "Extend traceback with stack info.",
"name": "_extend_traceback",
... | 4 | null | Implement the Python class `CommonStacktraceUtil` described below.
Class description:
Utilities for accessing the full stack trace of your application.
Method signatures and docstrings:
- def current_stack(skip: int=0) -> Any: Retrieve the current stack :param skip: The number of lines to skip :return: A collection o... | Implement the Python class `CommonStacktraceUtil` described below.
Class description:
Utilities for accessing the full stack trace of your application.
Method signatures and docstrings:
- def current_stack(skip: int=0) -> Any: Retrieve the current stack :param skip: The number of lines to skip :return: A collection o... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
<|body_0|>
def _exte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
cur_frame = None
try:
... | the_stack_v2_python_sparse | src/sims4communitylib/exceptions/common_stacktrace_utils.py | velocist/TS4CheatsInfo | train | 1 |
924d1c938bd0ba5912840f26fae6e74db2256bcd | [
"num_stack = []\nopear_stack = []\nopeard = {'+': add, '-': sub}\nlevel = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}\ni = n = 0\ns += '$'\nfor i, c in enumerate(s):\n if c == ' ':\n continue\n if c.isdigit():\n n = n * 10 + int(c)\n if not s[i + 1].isdigit():\n num_stack.append(n... | <|body_start_0|>
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerate(s):
if c == ' ':
continue
if c.isdigit():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_005894 | 3,812 | no_license | [
{
"docstring": "使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈",
"name": "calculate",
"signature": "def calculate(self, s: str) -> int"
},
{
"docstring": "双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈",
"name": "calculate",
"signature": "def calcula... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | 092a800a15bdd0f3d0c8f521a5e0fc90f964e8a8 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerat... | the_stack_v2_python_sparse | leetcode/400/224. 基本计算器.py | August-us/exam | train | 1 | |
254f98416aa3173182783f958624dba2fc9d7666 | [
"create_ids = []\ncr.execute('SELECT s.employee_id as employee_id\\n From hr_employee_seniority s\\n where employee_id in %s', (tuple(emp_dict),))\nres = cr.dictfetchall()\nresult = map(lambda x: x['employee_id'], res)\ncreate_ids = list(set(emp_dict) - set(result))\nreturn create_ids",
"sen... | <|body_start_0|>
create_ids = []
cr.execute('SELECT s.employee_id as employee_id\n From hr_employee_seniority s\n where employee_id in %s', (tuple(emp_dict),))
res = cr.dictfetchall()
result = map(lambda x: x['employee_id'], res)
create_ids = list(set(emp_di... | seniority_update | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class seniority_update:
def check_create(self, cr, uid, ids, emp_dict, context=None):
"""To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs"""
<|body_0|>
def check_update(self, cr, uid, ids, emp_dict, context=None):
"""To check update o... | stack_v2_sparse_classes_10k_train_005895 | 8,692 | no_license | [
{
"docstring": "To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs",
"name": "check_create",
"signature": "def check_create(self, cr, uid, ids, emp_dict, context=None)"
},
{
"docstring": "To check update of Employee Seniority. @param emp_dict:Employee IDs @re... | 3 | null | Implement the Python class `seniority_update` described below.
Class description:
Implement the seniority_update class.
Method signatures and docstrings:
- def check_create(self, cr, uid, ids, emp_dict, context=None): To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs
- def check_... | Implement the Python class `seniority_update` described below.
Class description:
Implement the seniority_update class.
Method signatures and docstrings:
- def check_create(self, cr, uid, ids, emp_dict, context=None): To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs
- def check_... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class seniority_update:
def check_create(self, cr, uid, ids, emp_dict, context=None):
"""To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs"""
<|body_0|>
def check_update(self, cr, uid, ids, emp_dict, context=None):
"""To check update o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class seniority_update:
def check_create(self, cr, uid, ids, emp_dict, context=None):
"""To check create of Employee Seniority. @param emp_dict:Employee IDs @return:List of IDs"""
create_ids = []
cr.execute('SELECT s.employee_id as employee_id\n From hr_employee_seniority s\n ... | the_stack_v2_python_sparse | v_7/NISS/common_shamil_v3/hr_custom_military/hr_employee_seniority.py | musabahmed/baba | train | 0 | |
da9012b62dcc44372a39f460f223ed897f219f94 | [
"url = 'os-agents'\nif params:\n url += '?%s' % urllib.urlencode(params)\nresp, body = self.get(url)\nbody = json.loads(body)\nself.validate_response(schema.list_agents, resp, body)\nreturn rest_client.ResponseBody(resp, body)",
"post_body = json.dumps({'agent': kwargs})\nresp, body = self.post('os-agents', po... | <|body_start_0|>
url = 'os-agents'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(schema.list_agents, resp, body)
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body_s... | Tests Agents API | AgentsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentsClient:
"""Tests Agents API"""
def list_agents(self, **params):
"""List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-agent-builds"""
<|body_0|>
def create_age... | stack_v2_sparse_classes_10k_train_005896 | 3,003 | permissive | [
{
"docstring": "List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-agent-builds",
"name": "list_agents",
"signature": "def list_agents(self, **params)"
},
{
"docstring": "Create an agent bui... | 4 | null | Implement the Python class `AgentsClient` described below.
Class description:
Tests Agents API
Method signatures and docstrings:
- def list_agents(self, **params): List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#li... | Implement the Python class `AgentsClient` described below.
Class description:
Tests Agents API
Method signatures and docstrings:
- def list_agents(self, **params): List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#li... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class AgentsClient:
"""Tests Agents API"""
def list_agents(self, **params):
"""List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-agent-builds"""
<|body_0|>
def create_age... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AgentsClient:
"""Tests Agents API"""
def list_agents(self, **params):
"""List all agent builds. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#list-agent-builds"""
url = 'os-agents'
if params:
... | the_stack_v2_python_sparse | tempest/lib/services/compute/agents_client.py | openstack/tempest | train | 270 |
9c9a74ebe344f32c01ed31ab2d9b5e4d94686d34 | [
"BaseNeo.__init__(self, name=name, file_origin=file_origin, description=description, **annotations)\nif times is None:\n times = np.array([]) * pq.s\nif durations is None:\n durations = np.array([]) * pq.s\nif labels is None:\n labels = np.array([], dtype='S')\nself.times = times\nself.durations = duration... | <|body_start_0|>
BaseNeo.__init__(self, name=name, file_origin=file_origin, description=description, **annotations)
if times is None:
times = np.array([]) * pq.s
if durations is None:
durations = np.array([]) * pq.s
if labels is None:
labels = np.array... | Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = EpochArray(times=np.arange(0, 30, 10)*s, ... durations=[10, 5, 7]*ms, ... lab... | EpochArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpochArray:
"""Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = EpochArray(times=np.arange(0, 30, 10)*s... | stack_v2_sparse_classes_10k_train_005897 | 4,621 | no_license | [
{
"docstring": "Initialize a new :class:`EpochArray` instance.",
"name": "__init__",
"signature": "def __init__(self, times=None, durations=None, labels=None, name=None, description=None, file_origin=None, **annotations)"
},
{
"docstring": "Returns a string representing the :class:`EpochArray`."... | 3 | stack_v2_sparse_classes_30k_train_004087 | Implement the Python class `EpochArray` described below.
Class description:
Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = ... | Implement the Python class `EpochArray` described below.
Class description:
Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = ... | 4c7b22771289b848edaa666e0b4e47469aab5b74 | <|skeleton|>
class EpochArray:
"""Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = EpochArray(times=np.arange(0, 30, 10)*s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EpochArray:
"""Array of epochs. Introduced for performance reason. An :class:`EpochArray` is prefered to a list of :class:`Epoch` objects. *Usage*:: >>> from neo.core import EpochArray >>> from quantities import s, ms >>> import numpy as np >>> >>> epcarr = EpochArray(times=np.arange(0, 30, 10)*s, ... duratio... | the_stack_v2_python_sparse | core/epocharray.py | srsummerson/analysis | train | 0 |
35b569df012d50638e88f5b01e9ce6e990a15d51 | [
"slow = 0\nfor fast in range(len(nums)):\n if nums[fast] != val:\n nums[slow] = nums[fast]\n slow += 1\nreturn slow",
"start, end = (0, len(nums) - 1)\nwhile start <= end:\n if nums[start] == val:\n nums[start], nums[end] = (nums[end], nums[start])\n end -= 1\n else:\n ... | <|body_start_0|>
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
<|end_body_0|>
<|body_start_1|>
start, end = (0, len(nums) - 1)
while start <= end:
if nums[start] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int 快慢指针"""
<|body_0|>
def removeElement1(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int 双指针"""
<|body_1|>
def removeElement0(self, nums,... | stack_v2_sparse_classes_10k_train_005898 | 1,558 | no_license | [
{
"docstring": ":type nums: List[int] :type val: int :rtype: int 快慢指针",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
},
{
"docstring": ":type nums: List[int] :type val: int :rtype: int 双指针",
"name": "removeElement1",
"signature": "def removeElement1(self, nu... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int 快慢指针
- def removeElement1(self, nums, val): :type nums: List[int] :type val: int :rtype: int ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int 快慢指针
- def removeElement1(self, nums, val): :type nums: List[int] :type val: int :rtype: int ... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int 快慢指针"""
<|body_0|>
def removeElement1(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int 双指针"""
<|body_1|>
def removeElement0(self, nums,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int 快慢指针"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
def removeElemen... | the_stack_v2_python_sparse | 27.移除元素.py | yangyuxiang1996/leetcode | train | 0 | |
a0870471a8c93a8950f5d9e05257b8ddd59ea88d | [
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nmy_survey.store_response('Chinese')\nself.assertIn('Chinese', my_survey.responses)",
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nresponses = ['Chinese', 'Japanese... | <|body_start_0|>
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('Chinese')
self.assertIn('Chinese', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'What language did you first learn to spea... | 对 AnonymousSurvey 类的测试 | TestAnonymousSurveyCast | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurveyCast:
"""对 AnonymousSurvey 类的测试"""
def test_store_single_response(self):
"""测试单个答案是否能妥善的保存"""
<|body_0|>
def test_store_three_responses(self):
"""测试单个答案是否能妥善的保存"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
question = 'What ... | stack_v2_sparse_classes_10k_train_005899 | 928 | no_license | [
{
"docstring": "测试单个答案是否能妥善的保存",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "测试单个答案是否能妥善的保存",
"name": "test_store_three_responses",
"signature": "def test_store_three_responses(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000320 | Implement the Python class `TestAnonymousSurveyCast` described below.
Class description:
对 AnonymousSurvey 类的测试
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案是否能妥善的保存
- def test_store_three_responses(self): 测试单个答案是否能妥善的保存 | Implement the Python class `TestAnonymousSurveyCast` described below.
Class description:
对 AnonymousSurvey 类的测试
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案是否能妥善的保存
- def test_store_three_responses(self): 测试单个答案是否能妥善的保存
<|skeleton|>
class TestAnonymousSurveyCast:
"""对 Anonymou... | c1f2bfaf53703c36f1c4c45308b11b49ec09b917 | <|skeleton|>
class TestAnonymousSurveyCast:
"""对 AnonymousSurvey 类的测试"""
def test_store_single_response(self):
"""测试单个答案是否能妥善的保存"""
<|body_0|>
def test_store_three_responses(self):
"""测试单个答案是否能妥善的保存"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAnonymousSurveyCast:
"""对 AnonymousSurvey 类的测试"""
def test_store_single_response(self):
"""测试单个答案是否能妥善的保存"""
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('Chinese')
self.assertIn('Chines... | the_stack_v2_python_sparse | python_tutorial/com/python/chapter11/test_survey.py | kamaihamaiha/Tutorial | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.