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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c7cba4b22ea00eddb9d2fdf84a85e2117aaebe0 | [
"while end > begin:\n if string[begin] != string[end]:\n return False\n begin += 1\n end -= 1\nreturn True",
"size = len(string)\nfor length in range(size, 1, -1):\n for offset in range(size - length + 1):\n if self._isPalindrome(string, offset, offset + length - 1):\n return ... | <|body_start_0|>
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
<|end_body_0|>
<|body_start_1|>
size = len(string)
for length in range(size, 1, -1):
for offset in range(size... | Naive | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while end > begin:
if st... | stack_v2_sparse_classes_10k_train_007500 | 3,988 | no_license | [
{
"docstring": "Verify if substring is a palindrome.",
"name": "_isPalindrome",
"signature": "def _isPalindrome(self, string, begin, end)"
},
{
"docstring": "Solve the problem.",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, string)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001334 | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem. | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem.
<|skeleton|>
class Naive:
def _isPalin... | 97246c26483637b95198ed2ef76e234d3c0194dc | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
def longestPalindrome(self, string):
... | the_stack_v2_python_sparse | coding/leetcode/problems/longest_palindromic_substring_hashing_v3_stress.py | baites/examples | train | 4 | |
b9d676a34e4a83f592580247ecde07aa85750585 | [
"queryset = kwargs.get('queryset')\nfilters = None\nfilter_map = kwargs.get('filter_map', {})\nfg = FilterGenerator(queryset.model, filter_map=filter_map)\nif len(request.data):\n fg = FilterGenerator(queryset.model)\n filters = fg.create_from_request_body(request.data)\nelse:\n filters = Q(**fg.create_fro... | <|body_start_0|>
queryset = kwargs.get('queryset')
filters = None
filter_map = kwargs.get('filter_map', {})
fg = FilterGenerator(queryset.model, filter_map=filter_map)
if len(request.data):
fg = FilterGenerator(queryset.model)
filters = fg.create_from_requ... | Handles queryset filtering. | FilterQuerysetMixin | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterQuerysetMixin:
"""Handles queryset filtering."""
def filter_records(self, request, *args, **kwargs):
"""Filter a queryset based on request parameters"""
<|body_0|>
def order_records(self, request, *args, **kwargs):
"""Order a queryset based on request param... | stack_v2_sparse_classes_10k_train_007501 | 10,956 | permissive | [
{
"docstring": "Filter a queryset based on request parameters",
"name": "filter_records",
"signature": "def filter_records(self, request, *args, **kwargs)"
},
{
"docstring": "Order a queryset based on request parameters.",
"name": "order_records",
"signature": "def order_records(self, re... | 3 | stack_v2_sparse_classes_30k_test_000026 | Implement the Python class `FilterQuerysetMixin` described below.
Class description:
Handles queryset filtering.
Method signatures and docstrings:
- def filter_records(self, request, *args, **kwargs): Filter a queryset based on request parameters
- def order_records(self, request, *args, **kwargs): Order a queryset b... | Implement the Python class `FilterQuerysetMixin` described below.
Class description:
Handles queryset filtering.
Method signatures and docstrings:
- def filter_records(self, request, *args, **kwargs): Filter a queryset based on request parameters
- def order_records(self, request, *args, **kwargs): Order a queryset b... | 38f920438697930ae3ac57bbcaae9034877d8fb7 | <|skeleton|>
class FilterQuerysetMixin:
"""Handles queryset filtering."""
def filter_records(self, request, *args, **kwargs):
"""Filter a queryset based on request parameters"""
<|body_0|>
def order_records(self, request, *args, **kwargs):
"""Order a queryset based on request param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilterQuerysetMixin:
"""Handles queryset filtering."""
def filter_records(self, request, *args, **kwargs):
"""Filter a queryset based on request parameters"""
queryset = kwargs.get('queryset')
filters = None
filter_map = kwargs.get('filter_map', {})
fg = FilterGene... | the_stack_v2_python_sparse | usaspending_api/common/mixins.py | fedspendingtransparency/usaspending-api | train | 276 |
4f91bfd2089fdb28fe03e287621db3f9eedebdb9 | [
"from bars_items.models.sellitem import SellItem\nfrom bars_stats.utils import compute_ranking\nf = {'stockitems__itemoperation__transaction__bar': pk, 'stockitems__itemoperation__transaction__type__in': ('buy', 'meal'), 'stockitems__deleted': False}\nann = Count('stockitems__itemoperation__transaction') / Count('s... | <|body_start_0|>
from bars_items.models.sellitem import SellItem
from bars_stats.utils import compute_ranking
f = {'stockitems__itemoperation__transaction__bar': pk, 'stockitems__itemoperation__transaction__type__in': ('buy', 'meal'), 'stockitems__deleted': False}
ann = Count('stockitems... | BarViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - nam... | stack_v2_sparse_classes_10k_train_007502 | 7,957 | no_license | [
{
"docstring": "Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - name: date_end required: false type: datetime paramType: query",
... | 3 | stack_v2_sparse_classes_30k_train_003166 | Implement the Python class `BarViewSet` described below.
Class description:
Implement the BarViewSet class.
Method signatures and docstrings:
- def sellitem_ranking(self, request, pk): Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_se... | Implement the Python class `BarViewSet` described below.
Class description:
Implement the BarViewSet class.
Method signatures and docstrings:
- def sellitem_ranking(self, request, pk): Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_se... | 7e464d4398e14b94d5b802bbd73c563639b5f125 | <|skeleton|>
class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - nam... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - name: date_end re... | the_stack_v2_python_sparse | bars_core/models/bar.py | BinetReseau/chocapix-server | train | 2 | |
4461b2eba907b9afb6292ad0ef79f692485cc5db | [
"super(PretrainTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.conv_decoder = nn.Sequential(nn.Conv1D(in_channels=in_channels, out_channels=128, k... | <|body_start_0|>
super(PretrainTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size
self.conv_decoder = nn.Sequential(nn.Con... | PretrainTaskModel | PretrainTaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(PretrainTaskModel, s... | stack_v2_sparse_classes_10k_train_007503 | 17,522 | permissive | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, class_num, model_config, encoder_model)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, input, pos)"
}
] | 2 | null | Implement the Python class `PretrainTaskModel` described below.
Class description:
PretrainTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward | Implement the Python class `PretrainTaskModel` described below.
Class description:
PretrainTaskModel
Method signatures and docstrings:
- def __init__(self, class_num, model_config, encoder_model): __init__
- def forward(self, input, pos): forward
<|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
<|body_0|>
def forward(self, input, pos):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PretrainTaskModel:
"""PretrainTaskModel"""
def __init__(self, class_num, model_config, encoder_model):
"""__init__"""
super(PretrainTaskModel, self).__init__()
model_type = model_config.get('model_type', 'transformer')
hidden_size = model_config.get('hidden_size', 512)
... | the_stack_v2_python_sparse | pahelix/model_zoo/protein_sequence_model.py | PaddlePaddle/PaddleHelix | train | 771 |
f4a5cc685caf7747ed8dad6b3e143696a62f7096 | [
"self._whithout_iren_start = whithout_iren_start\nself.showm = showm\nself.window2image_filter = vtk.vtkWindowToImageFilter()\nself.window2image_filter.SetInput(self.showm.window)\nself.image_buffers = []\nself.image_buffer_names = []\nself.info_buffer_name = None\nself.image_reprs = []\nself.num_buffers = num_buff... | <|body_start_0|>
self._whithout_iren_start = whithout_iren_start
self.showm = showm
self.window2image_filter = vtk.vtkWindowToImageFilter()
self.window2image_filter.SetInput(self.showm.window)
self.image_buffers = []
self.image_buffer_names = []
self.info_buffer_n... | This obj is responsible to create a StreamClient. | FuryStreamClient | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FuryStreamClient:
"""This obj is responsible to create a StreamClient."""
def __init__(self, showm, max_window_size=None, use_raw_array=True, whithout_iren_start=False, num_buffers=2):
"""A StreamClient extracts a framebuffer from the OpenGL context and writes into a shared memory re... | stack_v2_sparse_classes_10k_train_007504 | 12,536 | permissive | [
{
"docstring": "A StreamClient extracts a framebuffer from the OpenGL context and writes into a shared memory resource. Parameters ---------- showm : ShowManager max_window_size : tuple of ints, optional This allows resize events inside of the FURY window instance. Should be greater than the window size. use_ra... | 4 | stack_v2_sparse_classes_30k_train_002335 | Implement the Python class `FuryStreamClient` described below.
Class description:
This obj is responsible to create a StreamClient.
Method signatures and docstrings:
- def __init__(self, showm, max_window_size=None, use_raw_array=True, whithout_iren_start=False, num_buffers=2): A StreamClient extracts a framebuffer f... | Implement the Python class `FuryStreamClient` described below.
Class description:
This obj is responsible to create a StreamClient.
Method signatures and docstrings:
- def __init__(self, showm, max_window_size=None, use_raw_array=True, whithout_iren_start=False, num_buffers=2): A StreamClient extracts a framebuffer f... | e595bad0246899d58d24121dcc291eb050721f9f | <|skeleton|>
class FuryStreamClient:
"""This obj is responsible to create a StreamClient."""
def __init__(self, showm, max_window_size=None, use_raw_array=True, whithout_iren_start=False, num_buffers=2):
"""A StreamClient extracts a framebuffer from the OpenGL context and writes into a shared memory re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FuryStreamClient:
"""This obj is responsible to create a StreamClient."""
def __init__(self, showm, max_window_size=None, use_raw_array=True, whithout_iren_start=False, num_buffers=2):
"""A StreamClient extracts a framebuffer from the OpenGL context and writes into a shared memory resource. Param... | the_stack_v2_python_sparse | fury/stream/client.py | fury-gl/fury | train | 209 |
4cfec4c036af9ea970a3ca8fe8b5d4ba0cb55353 | [
"self.mod_df = mod_df\noptions = [opts_dd(column, column) for column in self.mod_df.columns]\nif self.show_filter:\n filter_elements = dbc.Row([dbc.Col([dbc.Form([dcc.Input(id=ids[self.get(self.id_filter_input)], placeholder='Enter filter query', style={'width': '100%'}), dbc.Button('Apply', color='secondary', i... | <|body_start_0|>
self.mod_df = mod_df
options = [opts_dd(column, column) for column in self.mod_df.columns]
if self.show_filter:
filter_elements = dbc.Row([dbc.Col([dbc.Form([dcc.Input(id=ids[self.get(self.id_filter_input)], placeholder='Enter filter query', style={'width': '100%'}),... | Modular Dash data table with column selection and filter. | ModuleFilteredTable | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleFilteredTable:
"""Modular Dash data table with column selection and filter."""
def return_layout(self, ids, mod_df):
"""Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Returns: dict: Dash HTML object"""
<|body_0|>
d... | stack_v2_sparse_classes_10k_train_007505 | 10,244 | permissive | [
{
"docstring": "Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Returns: dict: Dash HTML object",
"name": "return_layout",
"signature": "def return_layout(self, ids, mod_df)"
},
{
"docstring": "Register callbacks to handle user interaction. Args:... | 5 | stack_v2_sparse_classes_30k_train_000740 | Implement the Python class `ModuleFilteredTable` described below.
Class description:
Modular Dash data table with column selection and filter.
Method signatures and docstrings:
- def return_layout(self, ids, mod_df): Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Ret... | Implement the Python class `ModuleFilteredTable` described below.
Class description:
Modular Dash data table with column selection and filter.
Method signatures and docstrings:
- def return_layout(self, ids, mod_df): Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Ret... | fe784f4224136e6854d9ce67628976f17a2d9433 | <|skeleton|>
class ModuleFilteredTable:
"""Modular Dash data table with column selection and filter."""
def return_layout(self, ids, mod_df):
"""Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Returns: dict: Dash HTML object"""
<|body_0|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModuleFilteredTable:
"""Modular Dash data table with column selection and filter."""
def return_layout(self, ids, mod_df):
"""Return Dash application layout. Args: ids: `self._il` from base application mod_df: dataframe for Returns: dict: Dash HTML object"""
self.mod_df = mod_df
o... | the_stack_v2_python_sparse | dash_charts/modules_datatable.py | KyleKing/dash_charts | train | 20 |
d244ece889197c6099474d8bcec2c02860ca2eb7 | [
"fileName = inspect.getsourcefile(self.parent._create_widgets)\nself.master = master\nself.title('Source Code: ' + fileName)\ntxtFrame = ttk.Frame(self)\ntxtFrame.pack(side=TOP, fill=BOTH)\ntext = tk.Text(txtFrame, height=24, width=100, wrap=WORD, setgrid=1, highlightthickness=0, pady=2, padx=3)\nyscroll = ttk.Scro... | <|body_start_0|>
fileName = inspect.getsourcefile(self.parent._create_widgets)
self.master = master
self.title('Source Code: ' + fileName)
txtFrame = ttk.Frame(self)
txtFrame.pack(side=TOP, fill=BOTH)
text = tk.Text(txtFrame, height=24, width=100, wrap=WORD, setgrid=1, hi... | Create a modal dialog to display a demo's source code file. | CodeDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
<|body_0|>
def buttonbox(self) -> None:... | stack_v2_sparse_classes_10k_train_007506 | 4,028 | permissive | [
{
"docstring": "Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons.",
"name": "body",
"signature": "def body(self, master: tk.Tk) -> None"
},
{
"docstring": "Overrides Dialog.buttonbox() to create custom buttons for this dialog.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_005643 | Implement the Python class `CodeDialog` described below.
Class description:
Create a modal dialog to display a demo's source code file.
Method signatures and docstrings:
- def body(self, master: tk.Tk) -> None: Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons... | Implement the Python class `CodeDialog` described below.
Class description:
Create a modal dialog to display a demo's source code file.
Method signatures and docstrings:
- def body(self, master: tk.Tk) -> None: Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons... | 4672c6a6faa3e8ed31f0bbc1d8c8fdee8b8f928a | <|skeleton|>
class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
<|body_0|>
def buttonbox(self) -> None:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
fileName = inspect.getsourcefile(self.parent._create_widg... | the_stack_v2_python_sparse | src/dmltk/panels.py | Yobmod/dmlmung | train | 0 |
22575a28636580d9cdb1b0242147371eb339c52f | [
"data = {'OriginalURL': self.original_url, 'ResolvedURL': self.resolved_url, 'ServiceName': self.service_name, 'RedirectCount': len(self.redirect_history) - 1, 'RedirectHistory': self.redirect_history, 'EncounteredError': self.encountered_error}\nif self.api_usage is not None:\n data['APIUsageCount'] = self.api_... | <|body_start_0|>
data = {'OriginalURL': self.original_url, 'ResolvedURL': self.resolved_url, 'ServiceName': self.service_name, 'RedirectCount': len(self.redirect_history) - 1, 'RedirectHistory': self.redirect_history, 'EncounteredError': self.encountered_error}
if self.api_usage is not None:
... | A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list of URLs that were redirected to get to the resolved URL. raw_data (dict | list[dict] |... | URLUnshorteningData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLUnshorteningData:
"""A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list of URLs that were redirected to get to ... | stack_v2_sparse_classes_10k_train_007507 | 14,906 | permissive | [
{
"docstring": "Converts the data to a dictionary that will be used as the context data. Adds recursion data only if relevant. Note: We subtract 1 from RedirectCount because the original URL is included in the recursion history. Returns: dict: A dictionary containing the data in context format.",
"name": "t... | 2 | null | Implement the Python class `URLUnshorteningData` described below.
Class description:
A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list ... | Implement the Python class `URLUnshorteningData` described below.
Class description:
A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class URLUnshorteningData:
"""A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list of URLs that were redirected to get to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class URLUnshorteningData:
"""A tuple containing data for unshortend URLs. Attributes: original_url (str): The original URL. resolved_url (str): The resolved URL. service_name (str): The name of the service used to resolve the URL. redirect_history (list): A list of URLs that were redirected to get to the resolved ... | the_stack_v2_python_sparse | Packs/CommonScripts/Scripts/ResolveShortenedURL/ResolveShortenedURL.py | demisto/content | train | 1,023 |
9a68fd46635c7eaf7791ea603f811d3cd2016cf1 | [
"if not prices:\n return 0\nINT_MAX = 2147483647\nmaxPro = 0\nminPrice = INT_MAX\nfor i in range(len(prices)):\n minPrice = min(minPrice, prices[i])\n maxPro = max(maxPro, prices[i] - minPrice)\nreturn maxPro",
"result = 0\nINF = float('inf')\nmin_price = INF\nfor p in prices:\n min_price = min(min_pr... | <|body_start_0|>
if not prices:
return 0
INT_MAX = 2147483647
maxPro = 0
minPrice = INT_MAX
for i in range(len(prices)):
minPrice = min(minPrice, prices[i])
maxPro = max(maxPro, prices[i] - minPrice)
return maxPro
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_self(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not prices:
return 0
... | stack_v2_sparse_classes_10k_train_007508 | 736 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_self",
"signature": "def maxProfit_self(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_self(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_self(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def ma... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_self(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
INT_MAX = 2147483647
maxPro = 0
minPrice = INT_MAX
for i in range(len(prices)):
minPrice = min(minPrice, prices[i])
maxPr... | the_stack_v2_python_sparse | 121_best_time_to_buy_and_sell_stock/sol.py | lianke123321/leetcode_sol | train | 0 | |
0a1a023e88e4ea6742fa0ed7791e517e3065cb0e | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('h1.bookinfo-title').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_author = soup.select_one('span', {'itemprop': 'creator'}).text.strip()\nlogger.info('Novel author: %s... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.bookinfo-title').text.strip()
logger.info('Novel title: %s', self.novel_title)
self.novel_author = soup.select_one('span', {'itemprop': 'creato... | NovelCool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NovelCool:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007509 | 2,362 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_002118 | Implement the Python class `NovelCool` described below.
Class description:
Implement the NovelCool class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format. | Implement the Python class `NovelCool` described below.
Class description:
Implement the NovelCool class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as clean html format.
<|s... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class NovelCool:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NovelCool:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.bookinfo-title').text.strip()
logger.info('Novel title: %s', self.novel_... | the_stack_v2_python_sparse | lncrawl/sources/novelcool.py | NNTin/lightnovel-crawler | train | 2 | |
5bf3a626ae092b2fe0d1c2d8623b2609f9d3e34d | [
"if not head:\n return None\nself.reverse_iter(head)\nreturn self.head",
"if not node.next:\n self.head = node\n return node\nelse:\n parent = self.reverse_iter(node.next)\n parent.next = ListNode(node.val)\n parent = parent.next\n return parent"
] | <|body_start_0|>
if not head:
return None
self.reverse_iter(head)
return self.head
<|end_body_0|>
<|body_start_1|>
if not node.next:
self.head = node
return node
else:
parent = self.reverse_iter(node.next)
parent.next =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverse_iter(self, node):
""":type node: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return None... | stack_v2_sparse_classes_10k_train_007510 | 1,997 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type node: ListNode :rtype: ListNode",
"name": "reverse_iter",
"signature": "def reverse_iter(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007327 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverse_iter(self, node): :type node: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverse_iter(self, node): :type node: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def re... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverse_iter(self, node):
""":type node: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return None
self.reverse_iter(head)
return self.head
def reverse_iter(self, node):
""":type node: ListNode :rtype: ListNode"""
if not node.next:
... | the_stack_v2_python_sparse | 206.py | Gackle/leetcode_practice | train | 0 | |
6d7dc80a330fe276c6b2d5583c475d55b72b2bb4 | [
"digits = []\ndec = 10\nwhile n > 0:\n d = n % dec\n digits.append(d)\n n = (n - d) // dec\nm = len(digits)\ni = 1\nwhile i < m:\n if digits[i] < digits[i - 1]:\n break\n i += 1\nif i == m:\n return -1\nj = 0\nwhile j <= i:\n if digits[j] > digits[i]:\n break\n j += 1\ndigits[i... | <|body_start_0|>
digits = []
dec = 10
while n > 0:
d = n % dec
digits.append(d)
n = (n - d) // dec
m = len(digits)
i = 1
while i < m:
if digits[i] < digits[i - 1]:
break
i += 1
if i == m:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElementStr(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
digits = []
dec = 10
while n > 0:
... | stack_v2_sparse_classes_10k_train_007511 | 2,345 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElementStr",
"signature": "def nextGreaterElementStr(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006862 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, n): :type n: int :rtype: int
- def nextGreaterElementStr(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, n): :type n: int :rtype: int
- def nextGreaterElementStr(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nextGreaterElement... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElementStr(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
digits = []
dec = 10
while n > 0:
d = n % dec
digits.append(d)
n = (n - d) // dec
m = len(digits)
i = 1
while i < m:
if digits[i] < ... | the_stack_v2_python_sparse | N/NextGreaterElementIII.py | bssrdf/pyleet | train | 2 | |
1b48c25051464bb76f02165f9264e94b63006a40 | [
"self.assertEqual(max_list_iter([1]), 1)\nself.assertEqual(max_list_iter([1, 2, 3]), 3)\nself.assertEqual(max_list_iter([-1, -2, -3]), -1)\nself.assertEqual(max_list_iter([1, 1, 1]), 1)\nself.assertEqual(max_list_iter([2, 1, 3]), 3)\nself.assertEqual(max_list_iter([]), None)\nself.assertEqual(max_list_iter([1, 3, 3... | <|body_start_0|>
self.assertEqual(max_list_iter([1]), 1)
self.assertEqual(max_list_iter([1, 2, 3]), 3)
self.assertEqual(max_list_iter([-1, -2, -3]), -1)
self.assertEqual(max_list_iter([1, 1, 1]), 1)
self.assertEqual(max_list_iter([2, 1, 3]), 3)
self.assertEqual(max_list_i... | TestLab1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
<|body_0|>
def test_reverse_rec(self):
"""tests reverse_rec, a methon for reculsivly reversing a list"""
<|body_1|>
def test_bin_search(self):
"""A test of binary sear... | stack_v2_sparse_classes_10k_train_007512 | 1,782 | no_license | [
{
"docstring": "Tests max list through iteration",
"name": "test_max_list_iter",
"signature": "def test_max_list_iter(self)"
},
{
"docstring": "tests reverse_rec, a methon for reculsivly reversing a list",
"name": "test_reverse_rec",
"signature": "def test_reverse_rec(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_001339 | Implement the Python class `TestLab1` described below.
Class description:
Implement the TestLab1 class.
Method signatures and docstrings:
- def test_max_list_iter(self): Tests max list through iteration
- def test_reverse_rec(self): tests reverse_rec, a methon for reculsivly reversing a list
- def test_bin_search(sel... | Implement the Python class `TestLab1` described below.
Class description:
Implement the TestLab1 class.
Method signatures and docstrings:
- def test_max_list_iter(self): Tests max list through iteration
- def test_reverse_rec(self): tests reverse_rec, a methon for reculsivly reversing a list
- def test_bin_search(sel... | 8f3bb6433ea8555f0ba73cb0db2fabd98c95d8ee | <|skeleton|>
class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
<|body_0|>
def test_reverse_rec(self):
"""tests reverse_rec, a methon for reculsivly reversing a list"""
<|body_1|>
def test_bin_search(self):
"""A test of binary sear... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
self.assertEqual(max_list_iter([1]), 1)
self.assertEqual(max_list_iter([1, 2, 3]), 3)
self.assertEqual(max_list_iter([-1, -2, -3]), -1)
self.assertEqual(max_list_iter([1, 1, 1]), 1)
s... | the_stack_v2_python_sparse | CSC202/lab1-baileywickham/lab1_test_cases.py | baileywickham/college | train | 1 | |
18808924659768d24a74f4831c32441242f0c90c | [
"if node[u'type'] == NodeType.DUT:\n pci_address1 = Topology.get_interface_pci_addr(node, if1)\n pci_address2 = Topology.get_interface_pci_addr(node, if2)\n command = f'{Constants.REMOTE_FW_DIR}/{Constants.RESOURCES_LIB_SH}/entry/init_dpdk.sh {nic_driver} {pci_address1} {pci_address2}'\n message = u'Ini... | <|body_start_0|>
if node[u'type'] == NodeType.DUT:
pci_address1 = Topology.get_interface_pci_addr(node, if1)
pci_address2 = Topology.get_interface_pci_addr(node, if2)
command = f'{Constants.REMOTE_FW_DIR}/{Constants.RESOURCES_LIB_SH}/entry/init_dpdk.sh {nic_driver} {pci_addre... | This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment. | DPDKTools | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT ... | stack_v2_sparse_classes_10k_train_007513 | 4,823 | permissive | [
{
"docstring": "Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT first interface name. :param if2: DUT second interface name. :param nic_driver: Interface driver. :type node: dict :type if1: str :type if2: str :type nic_driver: str :raises RuntimeE... | 5 | stack_v2_sparse_classes_30k_train_002820 | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_framework(node, if1, if2, nic_driver): Initialize the DPDK framework on the DUT node. Bind inte... | Implement the Python class `DPDKTools` described below.
Class description:
This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment.
Method signatures and docstrings:
- def initialize_dpdk_framework(node, if1, if2, nic_driver): Initialize the DPDK framework on the DUT node. Bind inte... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DPDKTools:
"""This class implements: - Initialization of DPDK environment, - Cleanup of DPDK environment."""
def initialize_dpdk_framework(node, if1, if2, nic_driver):
"""Initialize the DPDK framework on the DUT node. Bind interfaces to driver. :param node: DUT node. :param if1: DUT first interfa... | the_stack_v2_python_sparse | resources/libraries/python/DPDK/DPDKTools.py | FDio/csit | train | 28 |
cdaa8e0565f07044bc78d6b3d3acc193cfd0f3fb | [
"self.mean = np.array(mean, dtype=np.float32)\nself.std = np.array(std, dtype=np.float32)\nself.size = size\nself.interpolation = interpolation",
"img = results['img']\nif self.interpolation == 0:\n self.interpolation = cv2.INTER_NEAREST\nelif self.interpolation == 1:\n self.interpolation = cv2.INTER_LINEAR... | <|body_start_0|>
self.mean = np.array(mean, dtype=np.float32)
self.std = np.array(std, dtype=np.float32)
self.size = size
self.interpolation = interpolation
<|end_body_0|>
<|body_start_1|>
img = results['img']
if self.interpolation == 0:
self.interpolation = ... | Package resize normalize in a pipeline, Support for different interpolate modes | ResizeNormalize | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResizeNormalize:
"""Package resize normalize in a pipeline, Support for different interpolate modes"""
def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5)):
"""Args: size (tuple): image resize size interpolation (int): interpolation type, i... | stack_v2_sparse_classes_10k_train_007514 | 28,723 | permissive | [
{
"docstring": "Args: size (tuple): image resize size interpolation (int): interpolation type, including [0, 1, 2, 3] mean (tuple): image normalization mean std (tuple): image normalization std",
"name": "__init__",
"signature": "def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=... | 2 | stack_v2_sparse_classes_30k_train_002865 | Implement the Python class `ResizeNormalize` described below.
Class description:
Package resize normalize in a pipeline, Support for different interpolate modes
Method signatures and docstrings:
- def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5)): Args: size (tuple): ima... | Implement the Python class `ResizeNormalize` described below.
Class description:
Package resize normalize in a pipeline, Support for different interpolate modes
Method signatures and docstrings:
- def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5)): Args: size (tuple): ima... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class ResizeNormalize:
"""Package resize normalize in a pipeline, Support for different interpolate modes"""
def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5)):
"""Args: size (tuple): image resize size interpolation (int): interpolation type, i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResizeNormalize:
"""Package resize normalize in a pipeline, Support for different interpolate modes"""
def __init__(self, size, interpolation=2, mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5)):
"""Args: size (tuple): image resize size interpolation (int): interpolation type, including [0, ... | the_stack_v2_python_sparse | davarocr/davarocr/davar_common/datasets/pipelines/transforms.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
87da29dba6340ec4955cc8c858e6108d0a19d6ed | [
"super(LMLossLayer, self).__init__(**kwargs)\nself.n_token = n_token\nself.d_model = d_model\nself.initializer = initializer\nself.tie_weight = tie_weight\nself.bi_data = bi_data\nself.use_tpu = use_tpu\nself.use_proj = use_proj",
"if self.use_proj:\n self.proj_layer = tf.keras.layers.Dense(units=self.d_model,... | <|body_start_0|>
super(LMLossLayer, self).__init__(**kwargs)
self.n_token = n_token
self.d_model = d_model
self.initializer = initializer
self.tie_weight = tie_weight
self.bi_data = bi_data
self.use_tpu = use_tpu
self.use_proj = use_proj
<|end_body_0|>
<|... | Layer computing cross entropy loss for language modeling. | LMLossLayer | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMLossLayer:
"""Layer computing cross entropy loss for language modeling."""
def __init__(self, n_token, d_model, initializer, tie_weight=False, bi_data=True, use_tpu=False, use_proj=False, **kwargs):
"""Constructs LMLoss layer. Args: n_token: Number of tokens in vocabulary. d_model:... | stack_v2_sparse_classes_10k_train_007515 | 46,062 | permissive | [
{
"docstring": "Constructs LMLoss layer. Args: n_token: Number of tokens in vocabulary. d_model: The dimension of model hidden state. initializer: Initializer used for parameters. tie_weight: Whether to share weights between embedding lookup layer and next-token prediction layer. bi_data: Whether to use bidirec... | 3 | null | Implement the Python class `LMLossLayer` described below.
Class description:
Layer computing cross entropy loss for language modeling.
Method signatures and docstrings:
- def __init__(self, n_token, d_model, initializer, tie_weight=False, bi_data=True, use_tpu=False, use_proj=False, **kwargs): Constructs LMLoss layer... | Implement the Python class `LMLossLayer` described below.
Class description:
Layer computing cross entropy loss for language modeling.
Method signatures and docstrings:
- def __init__(self, n_token, d_model, initializer, tie_weight=False, bi_data=True, use_tpu=False, use_proj=False, **kwargs): Constructs LMLoss layer... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class LMLossLayer:
"""Layer computing cross entropy loss for language modeling."""
def __init__(self, n_token, d_model, initializer, tie_weight=False, bi_data=True, use_tpu=False, use_proj=False, **kwargs):
"""Constructs LMLoss layer. Args: n_token: Number of tokens in vocabulary. d_model:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LMLossLayer:
"""Layer computing cross entropy loss for language modeling."""
def __init__(self, n_token, d_model, initializer, tie_weight=False, bi_data=True, use_tpu=False, use_proj=False, **kwargs):
"""Constructs LMLoss layer. Args: n_token: Number of tokens in vocabulary. d_model: The dimensio... | the_stack_v2_python_sparse | models/official/nlp/xlnet/xlnet_modeling.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
9c62a47a8fbb331afcccecbaad161ea36c3f815f | [
"specs = super(ExpectedImprovement, cls).getInputSpecification()\nspecs.description = \"If this node is present within the acquisition node,\\n the expected improvement acqusition function is utilized.\\n This function is derived by applying Bayesian optimal decision ma... | <|body_start_0|>
specs = super(ExpectedImprovement, cls).getInputSpecification()
specs.description = "If this node is present within the acquisition node,\n the expected improvement acqusition function is utilized.\n This function is derived by applying Baye... | Provides class for the Expected Improvement (EI) acquisition function | ExpectedImprovement | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_10k_train_007516 | 5,235 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Evalu... | 3 | null | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | Implement the Python class `ExpectedImprovement` described below.
Class description:
Provides class for the Expected Improvement (EI) acquisition function
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for sp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExpectedImprovement:
"""Provides class for the Expected Improvement (EI) acquisition function"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying inpu... | the_stack_v2_python_sparse | ravenframework/Optimizers/acquisitionFunctions/ExpectedImprovement.py | idaholab/raven | train | 201 |
ed92b882459bb173298447219338286e8d89f537 | [
"self._announce_text = announce_text\nself._logger = logger\nself._start_byte = start_byte\nself._override_total_size = override_total_size\nself._last_byte_written = False",
"if not self._logger.isEnabledFor(logging.INFO) or self._last_byte_written:\n return\nif self._override_total_size:\n total_size = se... | <|body_start_0|>
self._announce_text = announce_text
self._logger = logger
self._start_byte = start_byte
self._override_total_size = override_total_size
self._last_byte_written = False
<|end_body_0|>
<|body_start_1|>
if not self._logger.isEnabledFor(logging.INFO) or self... | Outputs progress info for large operations like file copy or hash. | FileProgressCallbackHandler | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileProgressCallbackHandler:
"""Outputs progress info for large operations like file copy or hash."""
def __init__(self, announce_text, logger, start_byte=0, override_total_size=None):
"""Initializes the callback handler. Args: announce_text: String describing the operation. logger: ... | stack_v2_sparse_classes_10k_train_007517 | 7,111 | permissive | [
{
"docstring": "Initializes the callback handler. Args: announce_text: String describing the operation. logger: For outputting log messages. start_byte: The beginning of the file component, if one is being used. override_total_size: The size of the file component, if one is being used.",
"name": "__init__",... | 2 | stack_v2_sparse_classes_30k_train_003887 | Implement the Python class `FileProgressCallbackHandler` described below.
Class description:
Outputs progress info for large operations like file copy or hash.
Method signatures and docstrings:
- def __init__(self, announce_text, logger, start_byte=0, override_total_size=None): Initializes the callback handler. Args:... | Implement the Python class `FileProgressCallbackHandler` described below.
Class description:
Outputs progress info for large operations like file copy or hash.
Method signatures and docstrings:
- def __init__(self, announce_text, logger, start_byte=0, override_total_size=None): Initializes the callback handler. Args:... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class FileProgressCallbackHandler:
"""Outputs progress info for large operations like file copy or hash."""
def __init__(self, announce_text, logger, start_byte=0, override_total_size=None):
"""Initializes the callback handler. Args: announce_text: String describing the operation. logger: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileProgressCallbackHandler:
"""Outputs progress info for large operations like file copy or hash."""
def __init__(self, announce_text, logger, start_byte=0, override_total_size=None):
"""Initializes the callback handler. Args: announce_text: String describing the operation. logger: For outputtin... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/gslib/progress_callback.py | metux/chromium-suckless | train | 5 |
508e92b584dbf04c6df9b34c38bc0776801c8f68 | [
"text = ''\nshortened = False\nif self.abstract:\n text = self.abstract\nelif self.description:\n for block in json.loads(self.description)['data']:\n if block.get('type') == 'text':\n data = block['data']\n if len(data['text']) > settings.ABSTRACT_LENGTH:\n trimmed... | <|body_start_0|>
text = ''
shortened = False
if self.abstract:
text = self.abstract
elif self.description:
for block in json.loads(self.description)['data']:
if block.get('type') == 'text':
data = block['data']
... | Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link). | AbstractHTMLMixin | [
"CC0-1.0",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractHTMLMixin:
"""Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link)."""
def abstract_plaintext(self, include_shortened=Fal... | stack_v2_sparse_classes_10k_train_007518 | 24,965 | permissive | [
{
"docstring": "If an explicit abstract is present, return it. Otherwise, return the first paragraph of the description",
"name": "abstract_plaintext",
"signature": "def abstract_plaintext(self, include_shortened=False)"
},
{
"docstring": "Take the plaintext and run it through a sir trevor templ... | 2 | stack_v2_sparse_classes_30k_train_007130 | Implement the Python class `AbstractHTMLMixin` described below.
Class description:
Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link).
Method signatures ... | Implement the Python class `AbstractHTMLMixin` described below.
Class description:
Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link).
Method signatures ... | 840c451eff415ebc57203bfeca55409131e9ab05 | <|skeleton|>
class AbstractHTMLMixin:
"""Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link)."""
def abstract_plaintext(self, include_shortened=Fal... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AbstractHTMLMixin:
"""Adds the abstract_html method. Assumes the object has an abstract and description field, where the description field is sir-trevor json. Also assumes that the object has a primary_url method (for the read-more link)."""
def abstract_plaintext(self, include_shortened=False):
... | the_stack_v2_python_sparse | peacecorps/peacecorps/models.py | forumone/peacecorps-site | train | 1 |
236e095119e026f3d122a24d26c154997b812528 | [
"def init_weights(m):\n if isinstance(m, nn.Linear):\n torch.nn.init.xavier_uniform_(m.weight)\nmodel = LCNN(n_occupancy, n_neighbor_sites_list, n_permutation_list, n_task, dropout_rate, n_conv, n_features, sitewise_n_feature)\nmodel.apply(init_weights)\nloss = L2Loss()\noutput_types = ['prediction']\nsup... | <|body_start_0|>
def init_weights(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight)
model = LCNN(n_occupancy, n_neighbor_sites_list, n_permutation_list, n_task, dropout_rate, n_conv, n_features, sitewise_n_feature)
model.apply(init_weights)
... | Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energy. These formation energies are found using DFT calculations and LCNNModel i... | LCNNModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCNNModel:
"""Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energy. These formation energies are found u... | stack_v2_sparse_classes_10k_train_007519 | 18,579 | permissive | [
{
"docstring": "This class accepts all the keyword arguments from TorchModel. Parameters ---------- n_occupancy: int, default 3 number of possible occupancy. n_neighbor_sites_list: int, default 19 Number of neighbors of each site. n_permutation: int, default 6 Diffrent permutations taken along diffrent directio... | 2 | stack_v2_sparse_classes_30k_train_001454 | Implement the Python class `LCNNModel` described below.
Class description:
Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energ... | Implement the Python class `LCNNModel` described below.
Class description:
Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energ... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class LCNNModel:
"""Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energy. These formation energies are found u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LCNNModel:
"""Lattice Convolutional Neural Network (LCNN). Here is a simple example of code that uses the LCNNModel with Platinum 2d Adsorption dataset. This model takes arbitrary configurations of Molecules on an adsorbate and predicts their formation energy. These formation energies are found using DFT calc... | the_stack_v2_python_sparse | deepchem/models/torch_models/lcnn.py | deepchem/deepchem | train | 4,876 |
c96c3895a12e4cc80fc65eb4603d2df319cb9b3f | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nurl = 'http://datamechanics.io/data/hospitalsgeo.json'\ndata = urllib.request.urlopen(url).read().decode('utf-8')\nresponse = json.loads(data)\nhospitals = []\nID = 0\nfor hospita... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
url = 'http://datamechanics.io/data/hospitalsgeo.json'
data = urllib.request.urlopen(url).read().decode('utf-8')
re... | getHospitals | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getHospitals:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_10k_train_007520 | 3,600 | 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_003654 | Implement the Python class `getHospitals` described below.
Class description:
Implement the getHospitals class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `getHospitals` described below.
Class description:
Implement the getHospitals class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class getHospitals:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class getHospitals:
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('jgrishey', 'jgrishey')
url = '... | the_stack_v2_python_sparse | jgrishey/getHospitals.py | lingyigu/course-2017-spr-proj | train | 0 | |
9015a6981f4388cb8fd6788addf1c6447f0c876a | [
"result = cls(group=operation, data_type=data_type)\nlatency_unit = 'ms'\nfor _, name, val in lines:\n name = name.strip()\n val = val.strip()\n if name.startswith('>'):\n name = name[1:]\n val = float(val) if '.' in val or 'nan' in val.lower() else int(val)\n if name.isdigit():\n if va... | <|body_start_0|>
result = cls(group=operation, data_type=data_type)
latency_unit = 'ms'
for _, name, val in lines:
name = name.strip()
val = val.strip()
if name.startswith('>'):
name = name[1:]
val = float(val) if '.' in val or 'nan... | Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, overall) statistics: dict mapping from statistic name to value (e.g. {'Count... | _OpResult | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _OpResult:
"""Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, overall) statistics: dict mapping from ... | stack_v2_sparse_classes_10k_train_007521 | 37,650 | permissive | [
{
"docstring": "Returns an _OpResult parsed from YCSB summary lines. Example format: [UPDATE], Operations, 2468054 [UPDATE], AverageLatency(us), 2218.8513395574005 [UPDATE], MinLatency(us), 554 [UPDATE], MaxLatency(us), 352634 [UPDATE], 95thPercentileLatency(ms), 4 [UPDATE], 99thPercentileLatency(ms), 7 [UPDATE... | 2 | null | Implement the Python class `_OpResult` described below.
Class description:
Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, ... | Implement the Python class `_OpResult` described below.
Class description:
Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, ... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class _OpResult:
"""Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, overall) statistics: dict mapping from ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _OpResult:
"""Individual results for a single operation. YCSB results are either aggregated per operation (read/update) at the end of the run or output on a per-interval (i.e. second) basis during the run. Attributes: group: group name (e.g. update, insert, overall) statistics: dict mapping from statistic nam... | the_stack_v2_python_sparse | perfkitbenchmarker/linux_packages/ycsb_stats.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
ea5599556288a026dd04697e661fc1655989985d | [
"self.grid = matrix\nself.cache = []\nr = len(matrix)\nc = len(matrix[0])\nfor i in range(r):\n temp = []\n last = 0\n for j in range(c):\n last += matrix[i][j]\n temp.append(last)\n self.cache.append(temp)\nprint(self.cache)",
"ans = 0\nfor i in range(row1, row2 + 1):\n row_sum = sel... | <|body_start_0|>
self.grid = matrix
self.cache = []
r = len(matrix)
c = len(matrix[0])
for i in range(r):
temp = []
last = 0
for j in range(c):
last += matrix[i][j]
temp.append(last)
self.cache.append... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_007522 | 3,429 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_004004 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | fe1928d8b10a63d7aa561118a70eeaec2f3a2f36 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.grid = matrix
self.cache = []
r = len(matrix)
c = len(matrix[0])
for i in range(r):
temp = []
last = 0
for j in range(c):
last += ... | the_stack_v2_python_sparse | May/Week2/Range Sum Query 2D - Immutable.py | vinaykumar7686/Leetcode-Monthly_Challenges | train | 0 | |
d4a33d100c1a3b15ace4f1c91d47961e7d167e4b | [
"argument_group.add_argument('--status_view', '--status-view', dest='status_view_mode', choices=cls._STATUS_VIEW_TYPES, action='store', metavar='TYPE', default=status_view.StatusView.MODE_WINDOW, help='The processing status view mode: \"file\", \"linear\", \"none\" or \"window\".')\nargument_group.add_argument('--s... | <|body_start_0|>
argument_group.add_argument('--status_view', '--status-view', dest='status_view_mode', choices=cls._STATUS_VIEW_TYPES, action='store', metavar='TYPE', default=status_view.StatusView.MODE_WINDOW, help='The processing status view mode: "file", "linear", "none" or "window".')
argument_grou... | Status view CLI arguments helper. | StatusViewArgumentsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper ... | stack_v2_sparse_classes_10k_train_007523 | 3,122 | permissive | [
{
"docstring": "Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.",
"name": "AddArgum... | 2 | stack_v2_sparse_classes_30k_val_000233 | Implement the Python class `StatusViewArgumentsHelper` described below.
Class description:
Status view CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object a... | Implement the Python class `StatusViewArgumentsHelper` described below.
Class description:
Status view CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object a... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StatusViewArgumentsHelper:
"""Status view CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Arg... | the_stack_v2_python_sparse | plaso/cli/helpers/status_view.py | log2timeline/plaso | train | 1,506 |
701e519a250a167b32499c5aec38aa10e39b6fc6 | [
"if self.action == 'list':\n return ViewFeatureListSerializer\nelif self.include_child_pages:\n return ViewFeatureSerializer\nelse:\n return ViewFeatureRowChildrenSerializer",
"context = super(ViewFeaturesBaseViewSet, self).get_serializer_context()\ncontext['include_child_pages'] = self.include_child_pag... | <|body_start_0|>
if self.action == 'list':
return ViewFeatureListSerializer
elif self.include_child_pages:
return ViewFeatureSerializer
else:
return ViewFeatureRowChildrenSerializer
<|end_body_0|>
<|body_start_1|>
context = super(ViewFeaturesBaseViewS... | ViewFeaturesBaseViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewFeaturesBaseViewSet:
def get_serializer_class(self):
"""Return the serializer to use based on action and query."""
<|body_0|>
def get_serializer_context(self):
"""Add include_child_pages to context."""
<|body_1|>
def include_child_pages(self):
... | stack_v2_sparse_classes_10k_train_007524 | 9,430 | no_license | [
{
"docstring": "Return the serializer to use based on action and query.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Add include_child_pages to context.",
"name": "get_serializer_context",
"signature": "def get_serializer_context(self... | 4 | stack_v2_sparse_classes_30k_train_001981 | Implement the Python class `ViewFeaturesBaseViewSet` described below.
Class description:
Implement the ViewFeaturesBaseViewSet class.
Method signatures and docstrings:
- def get_serializer_class(self): Return the serializer to use based on action and query.
- def get_serializer_context(self): Add include_child_pages ... | Implement the Python class `ViewFeaturesBaseViewSet` described below.
Class description:
Implement the ViewFeaturesBaseViewSet class.
Method signatures and docstrings:
- def get_serializer_class(self): Return the serializer to use based on action and query.
- def get_serializer_context(self): Add include_child_pages ... | bc092964153b03381aaff74a4d80f43a2b2dec19 | <|skeleton|>
class ViewFeaturesBaseViewSet:
def get_serializer_class(self):
"""Return the serializer to use based on action and query."""
<|body_0|>
def get_serializer_context(self):
"""Add include_child_pages to context."""
<|body_1|>
def include_child_pages(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ViewFeaturesBaseViewSet:
def get_serializer_class(self):
"""Return the serializer to use based on action and query."""
if self.action == 'list':
return ViewFeatureListSerializer
elif self.include_child_pages:
return ViewFeatureSerializer
else:
... | the_stack_v2_python_sparse | browsercompat/webplatformcompat/viewsets.py | WeilerWebServices/MDN-Web-Docs | train | 1 | |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"self.column_names: List = kargs.pop('column_names')\nself.action: Action = kargs.pop('action')\nsuper().__init__(*args, **kargs)\nself.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])\nuser_fname_column = self.fields['user_fname_column'].initial\nitem_col... | <|body_start_0|>
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
self.set_fields_from_dict(['item_column', 'user_fname_column', 'file_suffix', 'zip_for_moodle', 'confirm_items'])
user_fname_column = se... | Form to create a ZIP. | ZipActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k_train_007525 | 20,237 | permissive | [
{
"docstring": "Store column names, action and payload, adjust fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Detect uniques values in one column, and different column names.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000250 | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names. | Implement the Python class `ZipActionForm` described below.
Class description:
Form to create a ZIP.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names, action and payload, adjust fields.
- def clean(self): Detect uniques values in one column, and different column names.
<|ske... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
<|body_0|>
def clean(self):
"""Detect uniques values in one column, and different column names."""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZipActionForm:
"""Form to create a ZIP."""
def __init__(self, *args, **kargs):
"""Store column names, action and payload, adjust fields."""
self.column_names: List = kargs.pop('column_names')
self.action: Action = kargs.pop('action')
super().__init__(*args, **kargs)
... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
9fbecb529d70108d30831ec25cef202c9c063aaa | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IdentityUserFlowAttributeAssignment()",
"from .entity import Entity\nfrom .identity_user_flow_attribute import IdentityUserFlowAttribute\nfrom .identity_user_flow_attribute_input_type import IdentityUserFlowAttributeInputType\nfrom .us... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IdentityUserFlowAttributeAssignment()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .identity_user_flow_attribute import IdentityUserFlowAttribute
from .identit... | IdentityUserFlowAttributeAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_10k_train_007526 | 4,693 | 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: IdentityUserFlowAttributeAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_fr... | 3 | null | Implement the Python class `IdentityUserFlowAttributeAssignment` described below.
Class description:
Implement the IdentityUserFlowAttributeAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment: Creates a ... | Implement the Python class `IdentityUserFlowAttributeAssignment` described below.
Class description:
Implement the IdentityUserFlowAttributeAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment: Creates a ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/identity_user_flow_attribute_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5881273a1498425f88cc95d308f8a8992a76634c | [
"use_numba = engine == 'numba' and numba.numba_available\nif isinstance(prior, str):\n prior = self.prior_map[prior][int(use_numba)]\nif isinstance(prior, type):\n prior = prior(**prior_params)\nself.prior = prior\nif isinstance(obs_likelihood, str):\n obs_likelihood = self.likelihood_map[obs_likelihood]\n... | <|body_start_0|>
use_numba = engine == 'numba' and numba.numba_available
if isinstance(prior, str):
prior = self.prior_map[prior][int(use_numba)]
if isinstance(prior, type):
prior = prior(**prior_params)
self.prior = prior
if isinstance(obs_likelihood, str... | Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package. | BayesOffline | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss... | stack_v2_sparse_classes_10k_train_007527 | 21,057 | permissive | [
{
"docstring": "Parameters ---------- prior : {\"const\", \"geometric\", \"neg_binomial\"} or prior class, optional Prior probabiltiy. This can either be a string describing the prior or a type or instance of a class implementing the prior, as for example :py:class:`ConstPrior`, :py:class:`GeometricPrior`, or :... | 2 | stack_v2_sparse_classes_30k_train_001014 | Implement the Python class `BayesOffline` described below.
Class description:
Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package.
Method signatures and d... | Implement the Python class `BayesOffline` described below.
Class description:
Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package.
Method signatures and d... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss', prior_para... | the_stack_v2_python_sparse | sdt/changepoint/bayes_offline.py | schuetzgroup/sdt-python | train | 31 |
e1c00c96dad9e99e39266b4c71c290e03735ad89 | [
"self.l = capacity\nself.history = []\nself.map = {}",
"if key not in self.map:\n return -1\nself.history.remove(key)\nself.history.append(key)\nreturn self.map[key]",
"if key in self.map:\n self.history.remove(key)\n self.history.append(key)\n self.map[key] = value\nelse:\n if len(self.history) ... | <|body_start_0|>
self.l = capacity
self.history = []
self.map = {}
<|end_body_0|>
<|body_start_1|>
if key not in self.map:
return -1
self.history.remove(key)
self.history.append(key)
return self.map[key]
<|end_body_1|>
<|body_start_2|>
if key... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_007528 | 870 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_005205 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | fa1a63cb192666fc6aa5c7c72130993818ea58d0 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.l = capacity
self.history = []
self.map = {}
def get(self, key):
""":rtype: int"""
if key not in self.map:
return -1
self.history.remove(key)
self.history.app... | the_stack_v2_python_sparse | q146.py | gitttttt/lc | train | 0 | |
09a1b6c560f856e1d686ae30b19f01eb21edce10 | [
"start = self.startPixmap()\nend = self.endPixmap()\npainter = QPainter(self.outPixmap())\npainter.drawPixmap(0, 0, start)\nsize = start.size().expandedTo(end.size())\nwidth = size.width()\nheight = size.height()\nradius = int((width ** 2 + height ** 2) ** 0.5) / 2\nstart_rect = QRect(width / 2, height / 2, 0, 0)\n... | <|body_start_0|>
start = self.startPixmap()
end = self.endPixmap()
painter = QPainter(self.outPixmap())
painter.drawPixmap(0, 0, start)
size = start.size().expandedTo(end.size())
width = size.width()
height = size.height()
radius = int((width ** 2 + height... | A QPixmap transition which animates using an iris effect. | QIrisTransition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QIrisTransition:
"""A QPixmap transition which animates using an iris effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition update then sets a circular clipping region on the ouput... | stack_v2_sparse_classes_10k_train_007529 | 14,565 | permissive | [
{
"docstring": "Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition update then sets a circular clipping region on the ouput and draws in the ending pixmap.",
"name": "preparePixmap",
"signature": "def preparePixmap(self)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_003251 | Implement the Python class `QIrisTransition` described below.
Class description:
A QPixmap transition which animates using an iris effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition... | Implement the Python class `QIrisTransition` described below.
Class description:
A QPixmap transition which animates using an iris effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QIrisTransition:
"""A QPixmap transition which animates using an iris effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition update then sets a circular clipping region on the ouput... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QIrisTransition:
"""A QPixmap transition which animates using an iris effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition update then sets a circular clipping region on the ouput and draws in... | the_stack_v2_python_sparse | enaml/qt/q_pixmap_transition.py | MatthieuDartiailh/enaml | train | 26 |
7fdbe5b026270cbe6d1f19d30c4a1259c6f64251 | [
"if not request.user.is_superuser:\n self.queryset = Group.objects.filter(owner__pk=request.user.id)\nreturn super().list(request, args, kwargs)",
"queryset = Group.objects.get(pk=request.GET['pk'])\nserializer = GroupReadSerializer(queryset, many=False)\nreturn Response(serializer.data)",
"write_serializer ... | <|body_start_0|>
if not request.user.is_superuser:
self.queryset = Group.objects.filter(owner__pk=request.user.id)
return super().list(request, args, kwargs)
<|end_body_0|>
<|body_start_1|>
queryset = Group.objects.get(pk=request.GET['pk'])
serializer = GroupReadSerializer(q... | GroupViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupViewSet:
def list(self, request, *args, **kwargs):
"""Method for list groups"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Method for retrieve a single group"""
<|body_1|>
def create(self, request, *args, **kwargs):
"""Metho... | stack_v2_sparse_classes_10k_train_007530 | 3,350 | no_license | [
{
"docstring": "Method for list groups",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Method for retrieve a single group",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "Method for c... | 6 | stack_v2_sparse_classes_30k_train_004137 | Implement the Python class `GroupViewSet` described below.
Class description:
Implement the GroupViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Method for list groups
- def retrieve(self, request, *args, **kwargs): Method for retrieve a single group
- def create(self, req... | Implement the Python class `GroupViewSet` described below.
Class description:
Implement the GroupViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Method for list groups
- def retrieve(self, request, *args, **kwargs): Method for retrieve a single group
- def create(self, req... | cf1b9e973be872540dd0f5730df4830c987b9e33 | <|skeleton|>
class GroupViewSet:
def list(self, request, *args, **kwargs):
"""Method for list groups"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Method for retrieve a single group"""
<|body_1|>
def create(self, request, *args, **kwargs):
"""Metho... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupViewSet:
def list(self, request, *args, **kwargs):
"""Method for list groups"""
if not request.user.is_superuser:
self.queryset = Group.objects.filter(owner__pk=request.user.id)
return super().list(request, args, kwargs)
def retrieve(self, request, *args, **kwargs... | the_stack_v2_python_sparse | backend/modules/group/views.py | acca90/SleepWeb | train | 0 | |
2328ea021016837fb5391277e2d0e8bc9a646ad8 | [
"if len(lists) == 0:\n return []\nif len(lists) == 1:\n return lists[0]\nmerge_node = ListNode(0)\nresult = merge_node\nnode_list = []\nfor node in lists:\n while node:\n node_list.append(node.val)\n node = node.next\nnode_list.sort()\nwhile node_list:\n merge_node.next = ListNode(node_lis... | <|body_start_0|>
if len(lists) == 0:
return []
if len(lists) == 1:
return lists[0]
merge_node = ListNode(0)
result = merge_node
node_list = []
for node in lists:
while node:
node_list.append(node.val)
nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_007531 | 3,032 | no_license | [
{
"docstring": "将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: [ListNode]) -> ListNode"
},
{
"docstring": "show all value of ListNode :param node: :return:",
"name": "showNode",
"signature": "def showNode(self, node: Li... | 2 | stack_v2_sparse_classes_30k_train_003802 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :pa... | fa45cd44c3d4e7b0205833efcdc708d1638cbbe4 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""将所有元素取出来放在列表中排序再逐个添加至新链表 :param lists: :return:"""
if len(lists) == 0:
return []
if len(lists) == 1:
return lists[0]
merge_node = ListNode(0)
result = merge_node
node_list... | the_stack_v2_python_sparse | Python/t23.py | g-lyc/LeetCode | train | 15 | |
1d052e68851bfbee35867cf6718e181321af9c24 | [
"stack = [root] if root else []\nall_nodes = {}\nwhile stack:\n new_stack = []\n for node in stack:\n for child in (node.left, node.right):\n if child:\n all_nodes[child] = node\n new_stack.append(child)\n if not new_stack:\n break\n stack = new_sta... | <|body_start_0|>
stack = [root] if root else []
all_nodes = {}
while stack:
new_stack = []
for node in stack:
for child in (node.left, node.right):
if child:
all_nodes[child] = node
new_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subtreeWithAllDeepest(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def subtreeWithAllDeepest(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = [root] if... | stack_v2_sparse_classes_10k_train_007532 | 1,261 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "subtreeWithAllDeepest",
"signature": "def subtreeWithAllDeepest(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "subtreeWithAllDeepest",
"signature": "def subtreeWithAllDeepest(self, root)"
... | 2 | stack_v2_sparse_classes_30k_train_006746 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subtreeWithAllDeepest(self, root): :type root: TreeNode :rtype: TreeNode
- def subtreeWithAllDeepest(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subtreeWithAllDeepest(self, root): :type root: TreeNode :rtype: TreeNode
- def subtreeWithAllDeepest(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class So... | 16e4343922041929bc3021e152093425066620bb | <|skeleton|>
class Solution:
def subtreeWithAllDeepest(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def subtreeWithAllDeepest(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def subtreeWithAllDeepest(self, root):
""":type root: TreeNode :rtype: TreeNode"""
stack = [root] if root else []
all_nodes = {}
while stack:
new_stack = []
for node in stack:
for child in (node.left, node.right):
... | the_stack_v2_python_sparse | 865_subtreeWithAllDeepest.py | zzz686970/leetcode-2018 | train | 3 | |
3620ae30cfa5a3320c4d79b97f3176c91794cd0e | [
"with open('eqs.json') as qData:\n self.questions = json.load(qData)\nwith open('eqsave.json') as uData:\n self.records = json.load(uData)\nself.types = {'1': 'Reformer', '2': 'Helper', '3': 'Achiever', '4': 'Individualist', '5': 'Investigator', '6': 'Loyalist', '7': 'Enthusiast', '8': 'Challenger', '9': 'Pea... | <|body_start_0|>
with open('eqs.json') as qData:
self.questions = json.load(qData)
with open('eqsave.json') as uData:
self.records = json.load(uData)
self.types = {'1': 'Reformer', '2': 'Helper', '3': 'Achiever', '4': 'Individualist', '5': 'Investigator', '6': 'Loyalist',... | enneagram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class enneagram:
def __init__(self):
"""loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {"S": list of statements[2] {"S": text of statement "E": eValue of statement, if chosen} "D": display decimal value (1 - 144) "K": display base12 value (... | stack_v2_sparse_classes_10k_train_007533 | 1,855 | no_license | [
{
"docstring": "loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {\"S\": list of statements[2] {\"S\": text of statement \"E\": eValue of statement, if chosen} \"D\": display decimal value (1 - 144) \"K\": display base12 value (00 - BB)} records: a list of dic... | 2 | stack_v2_sparse_classes_30k_train_003017 | Implement the Python class `enneagram` described below.
Class description:
Implement the enneagram class.
Method signatures and docstrings:
- def __init__(self): loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {"S": list of statements[2] {"S": text of statement "E"... | Implement the Python class `enneagram` described below.
Class description:
Implement the enneagram class.
Method signatures and docstrings:
- def __init__(self): loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {"S": list of statements[2] {"S": text of statement "E"... | f2e43365c6f4572a548db4b4a3a17d2ecfe7a522 | <|skeleton|>
class enneagram:
def __init__(self):
"""loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {"S": list of statements[2] {"S": text of statement "E": eValue of statement, if chosen} "D": display decimal value (1 - 144) "K": display base12 value (... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class enneagram:
def __init__(self):
"""loads questions and records and types questions: a list of dicts, one dict for each of 144 questions {"S": list of statements[2] {"S": text of statement "E": eValue of statement, if chosen} "D": display decimal value (1 - 144) "K": display base12 value (00 - BB)} reco... | the_stack_v2_python_sparse | tomar/nine/enneagram.py | tomargames/tomarPython | train | 0 | |
a5df710216898b36bd489aec2be984a72a5188e3 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | DependenciaList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una dependencia"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_10k_train_007534 | 6,772 | no_license | [
{
"docstring": "Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Crear una dependencia",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002244 | Implement the Python class `DependenciaList` described below.
Class description:
Implement the DependenciaList class.
Method signatures and docstrings:
- def get(self): Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una dependencia | Implement the Python class `DependenciaList` described below.
Class description:
Implement the DependenciaList class.
Method signatures and docstrings:
- def get(self): Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una dependencia
<|sk... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una dependencia"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DependenciaList:
def get(self):
"""Listado de dependencias. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/dependencias.py | Telematica/knight-rider | train | 1 | |
893c89076649bf25c15c091b0fe36b0b673a3e31 | [
"self.mobmondir = self.tempdir\nself.staticdir = os.path.join(self.mobmondir, self.STATICDIR)\nosutils.SafeMakedirs(self.staticdir)",
"cfm = MockCheckFileManager()\nroot = mobmonitor.MobMonitorRoot(cfm, staticdir=self.staticdir)\nself.assertEqual(cfm.GetServiceList(), json.loads(root.GetServiceList()))",
"cfm =... | <|body_start_0|>
self.mobmondir = self.tempdir
self.staticdir = os.path.join(self.mobmondir, self.STATICDIR)
osutils.SafeMakedirs(self.staticdir)
<|end_body_0|>
<|body_start_1|>
cfm = MockCheckFileManager()
root = mobmonitor.MobMonitorRoot(cfm, staticdir=self.staticdir)
... | Unittests for the MobMonitorRoot. | MobMonitorRootTest | [
"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 MobMonitorRootTest:
"""Unittests for the MobMonitorRoot."""
def setUp(self):
"""Setup directories expected by the Mob* Monitor."""
<|body_0|>
def testGetServiceList(self):
"""Test the GetServiceList RPC."""
<|body_1|>
def testGetStatus(self):
... | stack_v2_sparse_classes_10k_train_007535 | 4,242 | permissive | [
{
"docstring": "Setup directories expected by the Mob* Monitor.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the GetServiceList RPC.",
"name": "testGetServiceList",
"signature": "def testGetServiceList(self)"
},
{
"docstring": "Test the GetStatus RPC.... | 5 | null | Implement the Python class `MobMonitorRootTest` described below.
Class description:
Unittests for the MobMonitorRoot.
Method signatures and docstrings:
- def setUp(self): Setup directories expected by the Mob* Monitor.
- def testGetServiceList(self): Test the GetServiceList RPC.
- def testGetStatus(self): Test the Ge... | Implement the Python class `MobMonitorRootTest` described below.
Class description:
Unittests for the MobMonitorRoot.
Method signatures and docstrings:
- def setUp(self): Setup directories expected by the Mob* Monitor.
- def testGetServiceList(self): Test the GetServiceList RPC.
- def testGetStatus(self): Test the Ge... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class MobMonitorRootTest:
"""Unittests for the MobMonitorRoot."""
def setUp(self):
"""Setup directories expected by the Mob* Monitor."""
<|body_0|>
def testGetServiceList(self):
"""Test the GetServiceList RPC."""
<|body_1|>
def testGetStatus(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MobMonitorRootTest:
"""Unittests for the MobMonitorRoot."""
def setUp(self):
"""Setup directories expected by the Mob* Monitor."""
self.mobmondir = self.tempdir
self.staticdir = os.path.join(self.mobmondir, self.STATICDIR)
osutils.SafeMakedirs(self.staticdir)
def test... | the_stack_v2_python_sparse | third_party/chromite/mobmonitor/scripts/mobmonitor_unittest.py | metux/chromium-suckless | train | 5 |
d4697daa605f3eb2e3917e55d3cce49d4259465c | [
"sentiment = global_cons.NEUTRAL\nif score <= thresholds[0]:\n sentiment = global_cons.NEGATIVE\nif score >= thresholds[1]:\n sentiment = global_cons.POSITIVE\nreturn sentiment",
"if not scores:\n logger.warning(msg='Empty baseline (scores) to calculate thresholds.')\n return (None, None)\nmu, std = n... | <|body_start_0|>
sentiment = global_cons.NEUTRAL
if score <= thresholds[0]:
sentiment = global_cons.NEGATIVE
if score >= thresholds[1]:
sentiment = global_cons.POSITIVE
return sentiment
<|end_body_0|>
<|body_start_1|>
if not scores:
logger.war... | InterfaceLabel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceLabel:
def label_sentiment(score: float, thresholds: tuple) -> str:
"""Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative and positive sentiment :return: sentiment label"""
<|body_0|>
def calculate_threshold_positi... | stack_v2_sparse_classes_10k_train_007536 | 1,312 | permissive | [
{
"docstring": "Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative and positive sentiment :return: sentiment label",
"name": "label_sentiment",
"signature": "def label_sentiment(score: float, thresholds: tuple) -> str"
},
{
"docstring": "Calcul... | 2 | stack_v2_sparse_classes_30k_test_000218 | Implement the Python class `InterfaceLabel` described below.
Class description:
Implement the InterfaceLabel class.
Method signatures and docstrings:
- def label_sentiment(score: float, thresholds: tuple) -> str: Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative an... | Implement the Python class `InterfaceLabel` described below.
Class description:
Implement the InterfaceLabel class.
Method signatures and docstrings:
- def label_sentiment(score: float, thresholds: tuple) -> str: Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative an... | c98eb8c483a05af938a2f6f49d8ea803f5711572 | <|skeleton|>
class InterfaceLabel:
def label_sentiment(score: float, thresholds: tuple) -> str:
"""Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative and positive sentiment :return: sentiment label"""
<|body_0|>
def calculate_threshold_positi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InterfaceLabel:
def label_sentiment(score: float, thresholds: tuple) -> str:
"""Label sentiment on interface :param score: score of the text :param thresholds: thresholds of negative and positive sentiment :return: sentiment label"""
sentiment = global_cons.NEUTRAL
if score <= threshol... | the_stack_v2_python_sparse | engage-analytics/sentiment_analysis/src/model/labelling_interface.py | oliveriopt/mood-analytics | train | 0 | |
02e4befb1952d023997bac68961c5a728887435b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Searches for videos | SearchServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
<|body_0|>
def GetQuerySuggestions(self, request, context):
"""Gets search query suggestions (could be used for typeahead su... | stack_v2_sparse_classes_10k_train_007537 | 2,478 | permissive | [
{
"docstring": "Searches for videos by a given query term",
"name": "SearchVideos",
"signature": "def SearchVideos(self, request, context)"
},
{
"docstring": "Gets search query suggestions (could be used for typeahead support)",
"name": "GetQuerySuggestions",
"signature": "def GetQuerySu... | 2 | stack_v2_sparse_classes_30k_train_002952 | Implement the Python class `SearchServiceServicer` described below.
Class description:
Searches for videos
Method signatures and docstrings:
- def SearchVideos(self, request, context): Searches for videos by a given query term
- def GetQuerySuggestions(self, request, context): Gets search query suggestions (could be ... | Implement the Python class `SearchServiceServicer` described below.
Class description:
Searches for videos
Method signatures and docstrings:
- def SearchVideos(self, request, context): Searches for videos by a given query term
- def GetQuerySuggestions(self, request, context): Gets search query suggestions (could be ... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
<|body_0|>
def GetQuerySuggestions(self, request, context):
"""Gets search query suggestions (could be used for typeahead su... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not i... | the_stack_v2_python_sparse | killrvideo/search/search_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
ffd5ee77cb95c1e1abe8e063d13c88bfa785d9db | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthDeviceModelPerformance()",
"from .entity import Entity\nfrom .user_experience_analytics_health_state import UserExperienceAnalyticsHealthState\nfrom .entity import Entity\nfrom .user_experience_analytics... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthDeviceModelPerformance()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .user_experience_analytics_health_state import UserExperienceAnal... | The user experience analytics device model performance entity contains device model performance details. | UserExperienceAnalyticsAppHealthDeviceModelPerformance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerfo... | stack_v2_sparse_classes_10k_train_007538 | 4,467 | 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: UserExperienceAnalyticsAppHealthDeviceModelPerformance",
"name": "create_from_discriminator_value",
"signatu... | 3 | null | Implement the Python class `UserExperienceAnalyticsAppHealthDeviceModelPerformance` described below.
Class description:
The user experience analytics device model performance entity contains device model performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[... | Implement the Python class `UserExperienceAnalyticsAppHealthDeviceModelPerformance` described below.
Class description:
The user experience analytics device model performance entity contains device model performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerfo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerformance:
... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_device_model_performance.py | microsoftgraph/msgraph-sdk-python | train | 135 |
4f7f5caa66680656ab52cea86c52a5ea24f860aa | [
"self.cassandra_additional_info = cassandra_additional_info\nself.cassandra_source_version = cassandra_source_version\nself.selected_data_center_vec = selected_data_center_vec\nself.staging_directory_vec = staging_directory_vec\nself.suffix = suffix",
"if dictionary is None:\n return None\ncassandra_additional... | <|body_start_0|>
self.cassandra_additional_info = cassandra_additional_info
self.cassandra_source_version = cassandra_source_version
self.selected_data_center_vec = selected_data_center_vec
self.staging_directory_vec = staging_directory_vec
self.suffix = suffix
<|end_body_0|>
<|... | Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan) : Remove this. cassandra_source_version... | CassandraRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_10k_train_007539 | 3,238 | permissive | [
{
"docstring": "Constructor for the CassandraRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, cassandra_additional_info=None, cassandra_source_version=None, selected_data_center_vec=None, staging_directory_vec=None, suffix=None)"
},
{
"docstring": "Creates an instanc... | 2 | stack_v2_sparse_classes_30k_test_000388 | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | Implement the Python class `CassandraRecoverJobParams` described below.
Class description:
Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CassandraRecoverJobParams:
"""Implementation of the 'CassandraRecoverJobParams' model. Contains any additional cassandra environment specific params for the recover job. Attributes: cassandra_additional_info (CassandraAdditionalParams): Additional parameters required for Cassandra recovery. TODO (faizan.khan)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cassandra_recover_job_params.py | hsantoyo2/management-sdk-python | train | 0 |
a22185544a7f253e95967705f19161dccf18d4ae | [
"super(MADF, self).__init__()\nself.in_channels_m = in_channels_m\nself.out_channels_m = out_channels_m\nself.in_channels_e = in_channels_e\nself.out_channels_e = out_channels_e\nself.kernel_size_e = kernel_size_e\nself.kernel_size_m = kernel_size_m\nself.padding_e = padding_e\nself.padding_m = padding_m\nself.stri... | <|body_start_0|>
super(MADF, self).__init__()
self.in_channels_m = in_channels_m
self.out_channels_m = out_channels_m
self.in_channels_e = in_channels_e
self.out_channels_e = out_channels_e
self.kernel_size_e = kernel_size_e
self.kernel_size_m = kernel_size_m
... | MADF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input... | stack_v2_sparse_classes_10k_train_007540 | 14,232 | no_license | [
{
"docstring": ":param in_channels_m: input channels of mask layer - m {l-1} :param out_channels_m: output channels of mask layer - m {l} :param in_channels_e: input chanels of image layer - e {l-1} :param out_channels_e: output channels of image layer - e {l} :param kernel_size_m: kernel size for transformatio... | 2 | stack_v2_sparse_classes_30k_train_003739 | Implement the Python class `MADF` described below.
Class description:
Implement the MADF class.
Method signatures and docstrings:
- def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e... | Implement the Python class `MADF` described below.
Class description:
Implement the MADF class.
Method signatures and docstrings:
- def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e... | eb9325edb73208ea992eda4be2a92119be867d10 | <|skeleton|>
class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MADF:
def __init__(self, in_channels_m, out_channels_m, in_channels_e, out_channels_e, kernel_size_m, kernel_size_e, stride_m, stride_e, padding_m, padding_e, activation_m='relu', activation_e='relu', norm_m='none', norm_e='bn', device=torch.device('cpu')):
""":param in_channels_m: input channels of m... | the_stack_v2_python_sparse | models/MadfGAN/model/blocks.py | Oorgien/Scene-Inpainting | train | 1 | |
bb602474d0647a3a18c239c87672bfa308f4d1ac | [
"self.consumer_id = consumer_id\nself.consumer_ssn = consumer_ssn\nself.event_name = event_name\nself.id = id\nself.status = status\nself.mtype = mtype\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nconsumer_id = dictionary.get('consumerId')\nconsumer_ssn = diction... | <|body_start_0|>
self.consumer_id = consumer_id
self.consumer_ssn = consumer_ssn
self.event_name = event_name
self.id = id
self.status = status
self.mtype = mtype
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictio... | Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. This field is optional and may not always return... | ReportNotification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. Th... | stack_v2_sparse_classes_10k_train_007541 | 3,117 | permissive | [
{
"docstring": "Constructor for the ReportNotification class",
"name": "__init__",
"signature": "def __init__(self, consumer_id=None, consumer_ssn=None, event_name=None, id=None, status=None, mtype=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dicti... | 2 | stack_v2_sparse_classes_30k_train_000270 | Implement the Python class `ReportNotification` described below.
Class description:
Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of th... | Implement the Python class `ReportNotification` described below.
Class description:
Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of th... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReportNotification:
"""Implementation of the 'ReportNotification' model. TODO: type model description here. Attributes: consumer_id (string): Finicity’s consumer ID. This field is optional and may not always return. consumer_ssn (string): The last four of the consumer’s social security number. This field is o... | the_stack_v2_python_sparse | finicityapi/models/report_notification.py | monarchmoney/finicity-python | train | 0 |
310410e29abccbba00f653f0a1a27c482c9f8aab | [
"def rec(res, index, nums, path, k):\n if len(path) == k:\n path.sort()\n res.append(path)\n for i in range(index, len(nums)):\n if len(path + [nums[i]]) > k:\n continue\n rec(res, i + 1, nums, path + [nums[i]], k)\nnums = [i + 1 for i in range(n)]\nans = []\nrec(ans, 0,... | <|body_start_0|>
def rec(res, index, nums, path, k):
if len(path) == k:
path.sort()
res.append(path)
for i in range(index, len(nums)):
if len(path + [nums[i]]) > k:
continue
rec(res, i + 1, nums, path + [... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def combine2(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def rec(res, index, ... | stack_v2_sparse_classes_10k_train_007542 | 1,299 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine",
"signature": "def combine(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine2",
"signature": "def combine2(self, n, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002043 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def combine2(self, n, k): :type n: int :type k: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def combine2(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
<|skeleton|>
class Solut... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def combine2(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
def rec(res, index, nums, path, k):
if len(path) == k:
path.sort()
res.append(path)
for i in range(index, len(nums)):
if len(path +... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00077.Combinations.py | roger6blog/LeetCode | train | 0 | |
e4b5ef3c4903ca97fe28d17a88421d5176f48c14 | [
"self.dhcp_lease_time = dhcp_lease_time\nself.dns_nameservers = dns_nameservers\nself.dns_custom_nameservers = dns_custom_nameservers",
"if dictionary is None:\n return None\ndhcp_lease_time = dictionary.get('dhcpLeaseTime')\ndns_nameservers = dictionary.get('dnsNameservers')\ndns_custom_nameservers = dictiona... | <|body_start_0|>
self.dhcp_lease_time = dhcp_lease_time
self.dns_nameservers = dns_nameservers
self.dns_custom_nameservers = dns_custom_nameservers
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
dhcp_lease_time = dictionary.get('dhcpLeaseTime')
... | Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week'. dns_nameservers (string): DNS name servers mode for al... | UpdateNetworkCellularGatewaySettingsDhcpModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1... | stack_v2_sparse_classes_10k_train_007543 | 2,535 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkCellularGatewaySettingsDhcpModel class",
"name": "__init__",
"signature": "def __init__(self, dhcp_lease_time=None, dns_nameservers=None, dns_custom_nameservers=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | null | Implement the Python class `UpdateNetworkCellularGatewaySettingsDhcpModel` described below.
Class description:
Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minute... | Implement the Python class `UpdateNetworkCellularGatewaySettingsDhcpModel` described below.
Class description:
Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minute... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateNetworkCellularGatewaySettingsDhcpModel:
"""Implementation of the 'updateNetworkCellularGatewaySettingsDhcp' model. TODO: type model description here. Attributes: dhcp_lease_time (string): DHCP Lease time for all MG of the network. It can be '30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 w... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_cellular_gateway_settings_dhcp_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
e9560d463e5144538e379603b5e3d8e3baa7d891 | [
"grid = gd.makeGrid(grid_type, **grid_kwargs)\nwith scipyio.FortranFile(filename, mode='r') as f:\n print('Reading input from {0}'.format(filename))\n return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())",
"with scipyio.FortranFile(filename, mode='w') as f:\n print('Writing output to ... | <|body_start_0|>
grid = gd.makeGrid(grid_type, **grid_kwargs)
with scipyio.FortranFile(filename, mode='r') as f:
print('Reading input from {0}'.format(filename))
return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())
<|end_body_0|>
<|body_start_1|>
with... | Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats | SciPyFortranFileIOHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_10k_train_007544 | 23,117 | permissive | [
{
"docstring": "Load a field from a unformatted fortran file using a method from scipy Arguments: filename: string; full path of the file to load grid_type: string; keyword specifying what type of grid to use **grid_kwargs: keyword dictionary; keyword arguments giving parameters of the grid fieldname, timeslice... | 2 | stack_v2_sparse_classes_30k_train_006856 | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | 08b627238c4bfa39026820c6116c1ed71f453b22 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False,... | the_stack_v2_python_sparse | Dynamic_HD_Scripts/Dynamic_HD_Scripts/base/iohelper.py | ThomasRiddick/DynamicHD | train | 1 |
fd4d0dac22d6e7360ae7adeae8152cce83b43a55 | [
"self.table = {}\nwith open(filename) as input_file:\n for line in input_file:\n str_vals = [i.strip() for i in line.split() if i.strip()]\n vals = [float(i) for i in str_vals]\n pt_thrs = (vals[0], vals[1])\n eta_thrs = (vals[2], vals[3])\n if pt_thrs not in self.table:\n ... | <|body_start_0|>
self.table = {}
with open(filename) as input_file:
for line in input_file:
str_vals = [i.strip() for i in line.split() if i.strip()]
vals = [float(i) for i in str_vals]
pt_thrs = (vals[0], vals[1])
eta_thrs = (v... | Loads a txt file with data to MC corrections | CorrectionLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrectionLoader:
"""Loads a txt file with data to MC corrections"""
def __init__(self, filename):
"""Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta max, correction uncertainty"""
<|body_0|>
de... | stack_v2_sparse_classes_10k_train_007545 | 1,473 | no_license | [
{
"docstring": "Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta max, correction uncertainty",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Return correction given pt and eta, raise ... | 2 | null | Implement the Python class `CorrectionLoader` described below.
Class description:
Loads a txt file with data to MC corrections
Method signatures and docstrings:
- def __init__(self, filename): Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta ... | Implement the Python class `CorrectionLoader` described below.
Class description:
Loads a txt file with data to MC corrections
Method signatures and docstrings:
- def __init__(self, filename): Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta ... | bcb164a8e27d459a9ac438780f6c8730d3e856bf | <|skeleton|>
class CorrectionLoader:
"""Loads a txt file with data to MC corrections"""
def __init__(self, filename):
"""Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta max, correction uncertainty"""
<|body_0|>
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CorrectionLoader:
"""Loads a txt file with data to MC corrections"""
def __init__(self, filename):
"""Creates object given input filename path txt file format, tab separated table, no header columns: ptmin, ptmax, eta min, eta max, correction uncertainty"""
self.table = {}
with op... | the_stack_v2_python_sparse | TagAndProbe/python/correctionloader.py | uwcms/FinalStateAnalysis | train | 5 |
972b4d292e87e9380d32036e27864d5ad6d31eaf | [
"group = self.context['group']\nuser = data\nmembership = Membership.objects.filter(group=group, user=user)\nif membership.exists():\n raise serializers.ValidationError('User has already been invited to this group.')\nreturn data",
"try:\n invitation = Invitation.objects.get(code=data, group=self.context['g... | <|body_start_0|>
group = self.context['group']
user = data
membership = Membership.objects.filter(group=group, user=user)
if membership.exists():
raise serializers.ValidationError('User has already been invited to this group.')
return data
<|end_body_0|>
<|body_start... | Add member serializer. Handle the addition of a new member to a group. | AddMemberSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberSerializer:
"""Add member serializer. Handle the addition of a new member to a group."""
def validate_user(self, data):
"""Verify user is not already a member."""
<|body_0|>
def validate_invitation_code(self, data):
"""Verify code exists and that it is r... | stack_v2_sparse_classes_10k_train_007546 | 2,279 | no_license | [
{
"docstring": "Verify user is not already a member.",
"name": "validate_user",
"signature": "def validate_user(self, data)"
},
{
"docstring": "Verify code exists and that it is related to the group.",
"name": "validate_invitation_code",
"signature": "def validate_invitation_code(self, d... | 3 | stack_v2_sparse_classes_30k_train_006823 | Implement the Python class `AddMemberSerializer` described below.
Class description:
Add member serializer. Handle the addition of a new member to a group.
Method signatures and docstrings:
- def validate_user(self, data): Verify user is not already a member.
- def validate_invitation_code(self, data): Verify code ex... | Implement the Python class `AddMemberSerializer` described below.
Class description:
Add member serializer. Handle the addition of a new member to a group.
Method signatures and docstrings:
- def validate_user(self, data): Verify user is not already a member.
- def validate_invitation_code(self, data): Verify code ex... | fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb | <|skeleton|>
class AddMemberSerializer:
"""Add member serializer. Handle the addition of a new member to a group."""
def validate_user(self, data):
"""Verify user is not already a member."""
<|body_0|>
def validate_invitation_code(self, data):
"""Verify code exists and that it is r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddMemberSerializer:
"""Add member serializer. Handle the addition of a new member to a group."""
def validate_user(self, data):
"""Verify user is not already a member."""
group = self.context['group']
user = data
membership = Membership.objects.filter(group=group, user=us... | the_stack_v2_python_sparse | facebook/app/groups/serializers/memberships.py | ricagome/Api-Facebook-Clone | train | 0 |
f711134f727746337ffa8ca1d324831a185afde8 | [
"newalphabets = []\nmaxcount = 0\nfor i in s:\n if i not in newalphabets:\n newalphabets.append(i)\n else:\n newalphabets = newalphabets[newalphabets.index(i) + 1:]\n newalphabets.append(i)\n if maxcount < len(newalphabets):\n maxcount = len(newalphabets)\nreturn maxcount",
"n... | <|body_start_0|>
newalphabets = []
maxcount = 0
for i in s:
if i not in newalphabets:
newalphabets.append(i)
else:
newalphabets = newalphabets[newalphabets.index(i) + 1:]
newalphabets.append(i)
if maxcount < len(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
newalphabets = []
maxcount = 0
... | stack_v2_sparse_classes_10k_train_007547 | 2,187 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007169 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(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 lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOf... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(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 lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
newalphabets = []
maxcount = 0
for i in s:
if i not in newalphabets:
newalphabets.append(i)
else:
newalphabets = newalphabets[newalphabets.ind... | the_stack_v2_python_sparse | 3_lengthOfLongestSubstring.py | Anirban2404/LeetCodePractice | train | 1 | |
b20098cafc2fc4ec4161a010f5bf0d2188865d5e | [
"if left is None:\n left = 0\nif right is None:\n right = 3 * opt\nself.opt = opt\nself.left = left\nself.right = right\nself.weight = weight",
"opt = self.opt * density\nif value < opt:\n other = self.left * density\nelif value > opt:\n other = self.right * density\nelse:\n return 0\nfactor = (val... | <|body_start_0|>
if left is None:
left = 0
if right is None:
right = 3 * opt
self.opt = opt
self.left = left
self.right = right
self.weight = weight
<|end_body_0|>
<|body_start_1|>
opt = self.opt * density
if value < opt:
... | a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analytic form of the rating is cubic for both, the left and the right side of... | cube | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cube:
"""a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analytic form of the rating is cubic for both... | stack_v2_sparse_classes_10k_train_007548 | 10,567 | permissive | [
{
"docstring": "initializes the rater - by default, left is set to zero, right is set to 3*opt - left should be smaller than opt, right should be bigger than opt - weight should be positive and is a factor multiplicated to the rates",
"name": "__init__",
"signature": "def __init__(self, opt, left=None, ... | 2 | stack_v2_sparse_classes_30k_train_001579 | Implement the Python class `cube` described below.
Class description:
a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analyt... | Implement the Python class `cube` described below.
Class description:
a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analyt... | 3a9693e37fd3afbd52001839966b0f2811fb4ccd | <|skeleton|>
class cube:
"""a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analytic form of the rating is cubic for both... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cube:
"""a value rater - a cube rater has an optimal value, where the rate becomes zero - for a left (below the optimum) and a right value (above the optimum), the rating is value is set to 1 (modified by an overall weight factor for the rating) - the analytic form of the rating is cubic for both, the left an... | the_stack_v2_python_sparse | compiler/gdsMill/pyx/graph/axis/rater.py | kanokkorn/OpenRAM | train | 0 |
58f65d75ad373949cf0198f5c14d8a296cf06d03 | [
"self._state = True\nself._last_action = time.time()\nself.async_write_ha_state()\nawait self.coordinator.api.set_relay_valve(int(self._item_id[1]), int(self._item_id[3]), int(self._item_id[-1]), 1)",
"self._state = False\nself._last_action = time.time()\nself.async_write_ha_state()\nawait self.coordinator.api.se... | <|body_start_0|>
self._state = True
self._last_action = time.time()
self.async_write_ha_state()
await self.coordinator.api.set_relay_valve(int(self._item_id[1]), int(self._item_id[3]), int(self._item_id[-1]), 1)
<|end_body_0|>
<|body_start_1|>
self._state = False
self._l... | Define the OmniLogic Relay entity. | OmniLogicRelayControl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Turn off the relay."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_007549 | 8,137 | permissive | [
{
"docstring": "Turn on the relay.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs)"
},
{
"docstring": "Turn off the relay.",
"name": "async_turn_off",
"signature": "async def async_turn_off(self, **kwargs)"
}
] | 2 | null | Implement the Python class `OmniLogicRelayControl` described below.
Class description:
Define the OmniLogic Relay entity.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Turn on the relay.
- async def async_turn_off(self, **kwargs): Turn off the relay. | Implement the Python class `OmniLogicRelayControl` described below.
Class description:
Define the OmniLogic Relay entity.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Turn on the relay.
- async def async_turn_off(self, **kwargs): Turn off the relay.
<|skeleton|>
class OmniLogicRelayCo... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Turn off the relay."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OmniLogicRelayControl:
"""Define the OmniLogic Relay entity."""
async def async_turn_on(self, **kwargs):
"""Turn on the relay."""
self._state = True
self._last_action = time.time()
self.async_write_ha_state()
await self.coordinator.api.set_relay_valve(int(self._ite... | the_stack_v2_python_sparse | homeassistant/components/omnilogic/switch.py | home-assistant/core | train | 35,501 |
8d23dcef39ba91dad029d9acc60e671ae972281b | [
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_dat... | <|body_start_0|>
try:
return_data = ''
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
retu... | WorkFlowEvalConf | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowEvalConf:
def post(self, request, nnid, ver):
"""This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method (n fold, random, extra test set) --- # Class Name : WorkFlowEvalConf # Description: Set Test method and t... | stack_v2_sparse_classes_10k_train_007550 | 2,971 | permissive | [
{
"docstring": "This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method (n fold, random, extra test set) --- # Class Name : WorkFlowEvalConf # Description: Set Test method and test data source",
"name": "post",
"signature": "def post(... | 4 | stack_v2_sparse_classes_30k_train_000237 | Implement the Python class `WorkFlowEvalConf` described below.
Class description:
Implement the WorkFlowEvalConf class.
Method signatures and docstrings:
- def post(self, request, nnid, ver): This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method ... | Implement the Python class `WorkFlowEvalConf` described below.
Class description:
Implement the WorkFlowEvalConf class.
Method signatures and docstrings:
- def post(self, request, nnid, ver): This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method ... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowEvalConf:
def post(self, request, nnid, ver):
"""This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method (n fold, random, extra test set) --- # Class Name : WorkFlowEvalConf # Description: Set Test method and t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkFlowEvalConf:
def post(self, request, nnid, ver):
"""This API is for set node parameters This node is for evaluation of train result You can choose 3 diffrent kind of test method (n fold, random, extra test set) --- # Class Name : WorkFlowEvalConf # Description: Set Test method and test data sourc... | the_stack_v2_python_sparse | api/views/workflow_eval_conf.py | yurimkoo/tensormsa | train | 1 | |
cb76b087de100e65f6a6729c5614477a6cfa9709 | [
"if not digits:\n return\nmappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\ncur = []\ndigits = list(digits)\nwhile digits:\n s = digits.pop()\n if cur:\n cur = [b + a for a in cur for b in mappings[s]]\n else:\n cur = list(mappin... | <|body_start_0|>
if not digits:
return
mappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
cur = []
digits = list(digits)
while digits:
s = digits.pop()
if cur:
cur = [b ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
<|body_0|>
def letterCombinations2(self, digits: str):
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not digits:
return
mappings = {'2': 'abc', '... | stack_v2_sparse_classes_10k_train_007551 | 1,850 | permissive | [
{
"docstring": "Backtracking",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits: str)"
},
{
"docstring": "DFS",
"name": "letterCombinations2",
"signature": "def letterCombinations2(self, digits: str)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str): Backtracking
- def letterCombinations2(self, digits: str): DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str): Backtracking
- def letterCombinations2(self, digits: str): DFS
<|skeleton|>
class Solution:
def letterCombinations(self, digits: ... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
<|body_0|>
def letterCombinations2(self, digits: str):
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
if not digits:
return
mappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
cur = []
digits = list(digits)
while digits:
... | the_stack_v2_python_sparse | leetcode/0017_letter_combinations_of_a_phone_number.py | chaosWsF/Python-Practice | train | 1 | |
f865edb1017dc8d64ed4897e9b152af0d2cafa5e | [
"if self.num_shared_convs > 0:\n for conv in self.shared_convs:\n x = conv(x)\nif self.num_shared_fcs > 0:\n if self.with_avg_pool:\n x = self.avg_pool(x)\n x = x.flatten(1)\n for fc in self.shared_fcs:\n x = self.relu(fc(x))\nreturn x",
"x_cls = x\nx_reg = x\nfor conv in self.cls... | <|body_start_0|>
if self.num_shared_convs > 0:
for conv in self.shared_convs:
x = conv(x)
if self.num_shared_fcs > 0:
if self.with_avg_pool:
x = self.avg_pool(x)
x = x.flatten(1)
for fc in self.shared_fcs:
x ... | BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature. | SCNetBBoxHead | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x... | stack_v2_sparse_classes_10k_train_007552 | 2,836 | permissive | [
{
"docstring": "Forward function for shared part. Args: x (Tensor): Input feature. Returns: Tensor: Shared feature.",
"name": "_forward_shared",
"signature": "def _forward_shared(self, x: Tensor) -> Tensor"
},
{
"docstring": "Forward function for classification and regression parts. Args: x (Ten... | 3 | stack_v2_sparse_classes_30k_train_007203 | Implement the Python class `SCNetBBoxHead` described below.
Class description:
BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature.
Method signatures and docstrings:
- def _forward_shared(self, x: Ten... | Implement the Python class `SCNetBBoxHead` described below.
Class description:
BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature.
Method signatures and docstrings:
- def _forward_shared(self, x: Ten... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x (Tensor): In... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/roi_heads/bbox_heads/scnet_bbox_head.py | alldatacenter/alldata | train | 774 |
3894fc824c7d8eb33e9d6787fee7554c7e5b41c1 | [
"parser = parent.add_parser('create', help='create pod')\nsuper().subparser(parser)\nparser.add_argument('--cgroup-parent', dest='cgroupparent', type=str, help='Path to cgroups under which the cgroup for the pod will be created.')\nparser.add_flag('--infra', help='Create an infra container and associate it with the... | <|body_start_0|>
parser = parent.add_parser('create', help='create pod')
super().subparser(parser)
parser.add_argument('--cgroup-parent', dest='cgroupparent', type=str, help='Path to cgroups under which the cgroup for the pod will be created.')
parser.add_flag('--infra', help='Create an ... | Implement Create Pod command. | CreatePod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
<|body_0|>
def create(self):
"""Create Pod from given options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser = par... | stack_v2_sparse_classes_10k_train_007553 | 2,499 | permissive | [
{
"docstring": "Add Pod Create command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Create Pod from given options.",
"name": "create",
"signature": "def create(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004294 | Implement the Python class `CreatePod` described below.
Class description:
Implement Create Pod command.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Create command to parent parser.
- def create(self): Create Pod from given options. | Implement the Python class `CreatePod` described below.
Class description:
Implement Create Pod command.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Create command to parent parser.
- def create(self): Create Pod from given options.
<|skeleton|>
class CreatePod:
"""Implement Create Po... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
<|body_0|>
def create(self):
"""Create Pod from given options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreatePod:
"""Implement Create Pod command."""
def subparser(cls, parent):
"""Add Pod Create command to parent parser."""
parser = parent.add_parser('create', help='create pod')
super().subparser(parser)
parser.add_argument('--cgroup-parent', dest='cgroupparent', type=str,... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/pod/create_parser.py | 4383/python-podman | train | 0 |
3fd0f8a80e2687472efde5a91ec8037e95c57006 | [
"data = self.data\nid_ = data['entity']['id']\nreturn f'{PLATFORM_URL}orders/{id_}'",
"available = super().available\ndata = self.data\nto_role = data['to_role']\nreturn to_role == 'customer_user' and available"
] | <|body_start_0|>
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
<|end_body_0|>
<|body_start_1|>
available = super().available
data = self.data
to_role = data['to_role']
return to_role == 'customer_user' and available
<|end_body_1... | Email to customer on comment created. | CommentCreatedToCustomer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentCreatedToCustomer:
"""Email to customer on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
da... | stack_v2_sparse_classes_10k_train_007554 | 5,020 | no_license | [
{
"docstring": "Action URL.",
"name": "action_url",
"signature": "def action_url(self) -> str"
},
{
"docstring": "Check if this action is available.",
"name": "available",
"signature": "def available(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_006973 | Implement the Python class `CommentCreatedToCustomer` described below.
Class description:
Email to customer on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available. | Implement the Python class `CommentCreatedToCustomer` described below.
Class description:
Email to customer on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available.
<|skeleton|>
class CommentCreatedToCustomer:
... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class CommentCreatedToCustomer:
"""Email to customer on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentCreatedToCustomer:
"""Email to customer on comment created."""
def action_url(self) -> str:
"""Action URL."""
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
def available(self) -> bool:
"""Check if this action is availa... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/leica/comment.py | BriefyHQ/briefy.choreographer | train | 0 |
673096ab1a035bcc11797b7743218261900df161 | [
"super().__init__()\nself.length = embed_size\nself.model = nn.Sequential()\nlayers_size = [in_channels] + layers_size\niterations = enumerate(zip(layers_size[:-1], layers_size[1:], kernels_size, strides, paddings))\nfor i, (in_c, out_c, k, s, p) in iterations:\n conv2d_i = nn.Conv2d(in_c, out_c, kernel_size=k, ... | <|body_start_0|>
super().__init__()
self.length = embed_size
self.model = nn.Sequential()
layers_size = [in_channels] + layers_size
iterations = enumerate(zip(layers_size[:-1], layers_size[1:], kernels_size, strides, paddings))
for i, (in_c, out_c, k, s, p) in iterations:... | Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer. | ImageInput | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageInput:
"""Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer."""
def __init__(self, embed_size: int, in_channels: int, layers_size: List[int], kernels_size: List[int], strides: List[int], paddings: List[int], pooling: Opt... | stack_v2_sparse_classes_10k_train_007555 | 3,726 | permissive | [
{
"docstring": "Initialize ImageInput. Args: embed_size (int): Size of embedding tensor in_channels (int): Number of channel of inputs layers_size (List[int]): Layers size of CNN kernels_size (List[int]): Kernels size of CNN strides (List[int]): Strides of CNN paddings (List[int]): Paddings of CNN pooling (str,... | 2 | stack_v2_sparse_classes_30k_train_006393 | Implement the Python class `ImageInput` described below.
Class description:
Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer.
Method signatures and docstrings:
- def __init__(self, embed_size: int, in_channels: int, layers_size: List[int], kernels_si... | Implement the Python class `ImageInput` described below.
Class description:
Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer.
Method signatures and docstrings:
- def __init__(self, embed_size: int, in_channels: int, layers_size: List[int], kernels_si... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class ImageInput:
"""Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer."""
def __init__(self, embed_size: int, in_channels: int, layers_size: List[int], kernels_size: List[int], strides: List[int], paddings: List[int], pooling: Opt... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageInput:
"""Base Input class for image, which embed image by a stack of convolution neural network (CNN) and fully-connect layer."""
def __init__(self, embed_size: int, in_channels: int, layers_size: List[int], kernels_size: List[int], strides: List[int], paddings: List[int], pooling: Optional[str]='a... | the_stack_v2_python_sparse | torecsys/inputs/base/image_inp.py | p768lwy3/torecsys | train | 98 |
4d805f6c5759f328c56ac3b1f0ef110c034b0360 | [
"super(EmRecoverNode, self).__init__()\nself.service = GlobalModule.SERVICE_RECOVER_NODE\nself._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]\nself.scenario_name = 'RecoverNode'",
"json_message = super(EmRecoverNode, self)._creating_json(device_message)\ndevice_json_message = json.loads(json_message... | <|body_start_0|>
super(EmRecoverNode, self).__init__()
self.service = GlobalModule.SERVICE_RECOVER_NODE
self._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]
self.scenario_name = 'RecoverNode'
<|end_body_0|>
<|body_start_1|>
json_message = super(EmRecoverNode, self).... | Scenario class for recover node | EmRecoverNode | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmRecoverNode:
"""Scenario class for recover node"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _creating_json(self, device_message):
"""Merges EC message(XML) devided into that in each device and device registration information received from DB convert... | stack_v2_sparse_classes_10k_train_007556 | 4,887 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Merges EC message(XML) devided into that in each device and device registration information received from DB converts them to JSDN and sets QOS information for service resetting Argument: devic... | 5 | stack_v2_sparse_classes_30k_train_001111 | Implement the Python class `EmRecoverNode` described below.
Class description:
Scenario class for recover node
Method signatures and docstrings:
- def __init__(self): Constructor
- def _creating_json(self, device_message): Merges EC message(XML) devided into that in each device and device registration information rec... | Implement the Python class `EmRecoverNode` described below.
Class description:
Scenario class for recover node
Method signatures and docstrings:
- def __init__(self): Constructor
- def _creating_json(self, device_message): Merges EC message(XML) devided into that in each device and device registration information rec... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class EmRecoverNode:
"""Scenario class for recover node"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _creating_json(self, device_message):
"""Merges EC message(XML) devided into that in each device and device registration information received from DB convert... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmRecoverNode:
"""Scenario class for recover node"""
def __init__(self):
"""Constructor"""
super(EmRecoverNode, self).__init__()
self.service = GlobalModule.SERVICE_RECOVER_NODE
self._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]
self.scenario_name = ... | the_stack_v2_python_sparse | lib/Scenario/EmRecoverNode.py | lixiaochun/element-manager | train | 0 |
4e0faa6e994386076b722987ca909bbb149f1607 | [
"row = len(matrix)\nif row == 0:\n return 0\narea = 0\ncol = len(matrix[0])\nheights: List[int] = [0] * col\nfor i in range(row):\n for j in range(col):\n if matrix[i][j] == '1':\n heights[j] += 1\n else:\n heights[j] = 0\n area = max(area, self.largest_rectangle_area(he... | <|body_start_0|>
row = len(matrix)
if row == 0:
return 0
area = 0
col = len(matrix[0])
heights: List[int] = [0] * col
for i in range(row):
for j in range(col):
if matrix[i][j] == '1':
heights[j] += 1
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def maximal_rectangle(self, matrix: List[List[str]]) -> int:
"""计算每层高度,求柱形图中最大的矩形面积。"""
<|body_0|>
def largest_rectangle_area(self, heights: List[int]) -> int:
"""单调栈。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
row = len(matri... | stack_v2_sparse_classes_10k_train_007557 | 3,665 | no_license | [
{
"docstring": "计算每层高度,求柱形图中最大的矩形面积。",
"name": "maximal_rectangle",
"signature": "def maximal_rectangle(self, matrix: List[List[str]]) -> int"
},
{
"docstring": "单调栈。",
"name": "largest_rectangle_area",
"signature": "def largest_rectangle_area(self, heights: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_003304 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def maximal_rectangle(self, matrix: List[List[str]]) -> int: 计算每层高度,求柱形图中最大的矩形面积。
- def largest_rectangle_area(self, heights: List[int]) -> int: 单调栈。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def maximal_rectangle(self, matrix: List[List[str]]) -> int: 计算每层高度,求柱形图中最大的矩形面积。
- def largest_rectangle_area(self, heights: List[int]) -> int: 单调栈。
<|skeleton|... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def maximal_rectangle(self, matrix: List[List[str]]) -> int:
"""计算每层高度,求柱形图中最大的矩形面积。"""
<|body_0|>
def largest_rectangle_area(self, heights: List[int]) -> int:
"""单调栈。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def maximal_rectangle(self, matrix: List[List[str]]) -> int:
"""计算每层高度,求柱形图中最大的矩形面积。"""
row = len(matrix)
if row == 0:
return 0
area = 0
col = len(matrix[0])
heights: List[int] = [0] * col
for i in range(row):
fo... | the_stack_v2_python_sparse | 0085_maximal-rectangle.py | Nigirimeshi/leetcode | train | 0 | |
12f9b4d30774393712a613afe07d1ec9ebf67e1c | [
"super(RedactingPIIFilter, self).__init__()\nself.scrubber = self._get_scrubber()\nself._patterns = patterns",
"scrubber = scrubadub.Scrubber()\nscrubber.remove_detector('email')\nscrubber.remove_detector('name')\nscrubber.remove_detector('phone')\nscrubber.add_detector(TINDetector)\nreturn scrubber",
"record.m... | <|body_start_0|>
super(RedactingPIIFilter, self).__init__()
self.scrubber = self._get_scrubber()
self._patterns = patterns
<|end_body_0|>
<|body_start_1|>
scrubber = scrubadub.Scrubber()
scrubber.remove_detector('email')
scrubber.remove_detector('name')
scrubber.... | Redacting filter to remove PII information. | RedactingPIIFilter | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedactingPIIFilter:
"""Redacting filter to remove PII information."""
def __init__(self, patterns=[]):
"""Initialize PII filter. New patterns can be given as input."""
<|body_0|>
def _get_scrubber():
"""Initialize a scrubber with phone, skype, ssn, tin and url de... | stack_v2_sparse_classes_10k_train_007558 | 1,926 | permissive | [
{
"docstring": "Initialize PII filter. New patterns can be given as input.",
"name": "__init__",
"signature": "def __init__(self, patterns=[])"
},
{
"docstring": "Initialize a scrubber with phone, skype, ssn, tin and url detector.",
"name": "_get_scrubber",
"signature": "def _get_scrubbe... | 4 | stack_v2_sparse_classes_30k_train_004151 | Implement the Python class `RedactingPIIFilter` described below.
Class description:
Redacting filter to remove PII information.
Method signatures and docstrings:
- def __init__(self, patterns=[]): Initialize PII filter. New patterns can be given as input.
- def _get_scrubber(): Initialize a scrubber with phone, skype... | Implement the Python class `RedactingPIIFilter` described below.
Class description:
Redacting filter to remove PII information.
Method signatures and docstrings:
- def __init__(self, patterns=[]): Initialize PII filter. New patterns can be given as input.
- def _get_scrubber(): Initialize a scrubber with phone, skype... | 1e2da9494faf9e316a17cbe899284db9e61d0902 | <|skeleton|>
class RedactingPIIFilter:
"""Redacting filter to remove PII information."""
def __init__(self, patterns=[]):
"""Initialize PII filter. New patterns can be given as input."""
<|body_0|>
def _get_scrubber():
"""Initialize a scrubber with phone, skype, ssn, tin and url de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RedactingPIIFilter:
"""Redacting filter to remove PII information."""
def __init__(self, patterns=[]):
"""Initialize PII filter. New patterns can be given as input."""
super(RedactingPIIFilter, self).__init__()
self.scrubber = self._get_scrubber()
self._patterns = patterns... | the_stack_v2_python_sparse | claims_to_quality/lib/qpp_logging/pii_scrubber.py | gaybro8777/qpp-claims-to-quality-public | train | 0 |
e45b82ff7692afab42642610824cf7c103d911c7 | [
"self.id = 1\nself.title = title\nself._analyzer = analyzer",
"parameter_dict = aggregation.parameters\nif agg_type:\n parameter_dict['supported_charts'] = agg_type\nelse:\n agg_type = parameter_dict.get('supported_charts')\n if not agg_type:\n agg_type = 'table'\n parameter_dict['supported... | <|body_start_0|>
self.id = 1
self.title = title
self._analyzer = analyzer
<|end_body_0|>
<|body_start_1|>
parameter_dict = aggregation.parameters
if agg_type:
parameter_dict['supported_charts'] = agg_type
else:
agg_type = parameter_dict.get('suppo... | Mocked story object. | Story | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_10k_train_007559 | 31,229 | permissive | [
{
"docstring": "Initialize the story.",
"name": "__init__",
"signature": "def __init__(self, analyzer, title)"
},
{
"docstring": "Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add to the story. agg_type (str): string indicating the type of aggregatio... | 5 | stack_v2_sparse_classes_30k_train_005812 | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
self.id = 1
self.title = title
self._analyzer = analyzer
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggr... | the_stack_v2_python_sparse | test_tools/timesketch/lib/analyzers/interface.py | google/timesketch | train | 2,263 |
2d830183c622a70f6df9a3729fd55833c88530df | [
"self.log = logging.getLogger(self.__class__.__name__)\nself.sim_start_ts = sim_start_ts\nself.log_interval = log_interval\nself.sim_time = None\nself.time_step = None\nself.msg_time = None\nself.last_log_time = None\nself.regexp = re.compile('(?:incrementing to )([0-9]+)')\ngad.subscribe(topic=topics.simulation_lo... | <|body_start_0|>
self.log = logging.getLogger(self.__class__.__name__)
self.sim_start_ts = sim_start_ts
self.log_interval = log_interval
self.sim_time = None
self.time_step = None
self.msg_time = None
self.last_log_time = None
self.regexp = re.compile('(?:... | Class for keeping track of a simulation's time as it progresses. | SimulationClock | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationClock:
"""Class for keeping track of a simulation's time as it progresses."""
def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int, log_interval=60):
"""Initialize attributes, subscribe to the simulation log. :param gad: Initialized gridappsd.GridAPPSD object. ... | stack_v2_sparse_classes_10k_train_007560 | 30,082 | permissive | [
{
"docstring": "Initialize attributes, subscribe to the simulation log. :param gad: Initialized gridappsd.GridAPPSD object. :param sim_id: Simulation ID of the simulation to track. :param sim_start_ts: Simulation start timestamp in seconds since the epoch. :param log_interval: How many simulation seconds in bet... | 2 | stack_v2_sparse_classes_30k_train_002548 | Implement the Python class `SimulationClock` described below.
Class description:
Class for keeping track of a simulation's time as it progresses.
Method signatures and docstrings:
- def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int, log_interval=60): Initialize attributes, subscribe to the simulation ... | Implement the Python class `SimulationClock` described below.
Class description:
Class for keeping track of a simulation's time as it progresses.
Method signatures and docstrings:
- def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int, log_interval=60): Initialize attributes, subscribe to the simulation ... | 410aaf42f721e4b43bb32cd3b83d3e2cb2b78923 | <|skeleton|>
class SimulationClock:
"""Class for keeping track of a simulation's time as it progresses."""
def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int, log_interval=60):
"""Initialize attributes, subscribe to the simulation log. :param gad: Initialized gridappsd.GridAPPSD object. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimulationClock:
"""Class for keeping track of a simulation's time as it progresses."""
def __init__(self, gad: GridAPPSD, sim_id: str, sim_start_ts: int, log_interval=60):
"""Initialize attributes, subscribe to the simulation log. :param gad: Initialized gridappsd.GridAPPSD object. :param sim_id... | the_stack_v2_python_sparse | pyvvo/gridappsd_platform.py | GRIDAPPSD/pyvvo | train | 4 |
0f146d3e5232a742fadb963e253b3a9e1772d28b | [
"if root is None:\n return 0\nres = 0\nif root.val == sum:\n res += 1\nres += self.containNode(root.left, sum - root.val)\nres += self.containNode(root.right, sum - root.val)\nreturn res",
"if root is None:\n return 0\nres = self.containNode(root, sum)\nres += self.pathSum(root.left, sum)\nres += self.pa... | <|body_start_0|>
if root is None:
return 0
res = 0
if root.val == sum:
res += 1
res += self.containNode(root.left, sum - root.val)
res += self.containNode(root.right, sum - root.val)
return res
<|end_body_0|>
<|body_start_1|>
if root is No... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_007561 | 1,068 | no_license | [
{
"docstring": "calcuate how many path is valid from root, that sums up to the given value",
"name": "containNode",
"signature": "def containNode(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, root... | 2 | stack_v2_sparse_classes_30k_train_000537 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containNode(self, root, sum): calcuate how many path is valid from root, that sums up to the given value
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containNode(self, root, sum): calcuate how many path is valid from root, that sums up to the given value
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :... | f8b35179b980e55f61bbcd2631fa3a9bf30c40ec | <|skeleton|>
class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def containNode(self, root, sum):
"""calcuate how many path is valid from root, that sums up to the given value"""
if root is None:
return 0
res = 0
if root.val == sum:
res += 1
res += self.containNode(root.left, sum - root.val)
... | the_stack_v2_python_sparse | Python Solutions/437 Path Sum III.py | Sue9/Leetcode | train | 0 | |
ea97491740fdb756629ae14602b1db028a3c93fa | [
"leoTkinterDialog.__init__(self, 'Enter unique id', resizeable=False, canClose=False)\nself.id_entry = None\nself.answer = None\nself.createTopFrame()\nself.top.bind('<Key>', self.onKey)\nmessage = 'leoID.txt not found\\n\\n' + 'Please enter an id that identifies you uniquely.\\n' + 'Your cvs login name is a good c... | <|body_start_0|>
leoTkinterDialog.__init__(self, 'Enter unique id', resizeable=False, canClose=False)
self.id_entry = None
self.answer = None
self.createTopFrame()
self.top.bind('<Key>', self.onKey)
message = 'leoID.txt not found\n\n' + 'Please enter an id that identifies... | A class that creates the Tkinter About Leo dialog. | tkinterAskLeoID | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tkinterAskLeoID:
"""A class that creates the Tkinter About Leo dialog."""
def __init__(self):
"""Create the Leo Id dialog."""
<|body_0|>
def createFrame(self, message):
"""Create the frame for the Leo Id dialog."""
<|body_1|>
def onButton(self):
... | stack_v2_sparse_classes_10k_train_007562 | 25,997 | no_license | [
{
"docstring": "Create the Leo Id dialog.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create the frame for the Leo Id dialog.",
"name": "createFrame",
"signature": "def createFrame(self, message)"
},
{
"docstring": "Handle clicks in the Leo Id close... | 4 | stack_v2_sparse_classes_30k_train_001302 | Implement the Python class `tkinterAskLeoID` described below.
Class description:
A class that creates the Tkinter About Leo dialog.
Method signatures and docstrings:
- def __init__(self): Create the Leo Id dialog.
- def createFrame(self, message): Create the frame for the Leo Id dialog.
- def onButton(self): Handle c... | Implement the Python class `tkinterAskLeoID` described below.
Class description:
A class that creates the Tkinter About Leo dialog.
Method signatures and docstrings:
- def __init__(self): Create the Leo Id dialog.
- def createFrame(self, message): Create the frame for the Leo Id dialog.
- def onButton(self): Handle c... | 28c22721e1bc313c120a8a6c288893bc566a5c67 | <|skeleton|>
class tkinterAskLeoID:
"""A class that creates the Tkinter About Leo dialog."""
def __init__(self):
"""Create the Leo Id dialog."""
<|body_0|>
def createFrame(self, message):
"""Create the frame for the Leo Id dialog."""
<|body_1|>
def onButton(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class tkinterAskLeoID:
"""A class that creates the Tkinter About Leo dialog."""
def __init__(self):
"""Create the Leo Id dialog."""
leoTkinterDialog.__init__(self, 'Enter unique id', resizeable=False, canClose=False)
self.id_entry = None
self.answer = None
self.createTop... | the_stack_v2_python_sparse | Projects/jyleo/src/leoTkinterDialog.py | leo-editor/leo-editor-contrib | train | 6 |
2cf39ae831a923e80197608352057a8860df9d28 | [
"x = []\nif root:\n stack = [root]\n while stack:\n node = stack.pop()\n x.append(node.val)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\nreturn ' '.join(map(str, x))",
"x = deque([int(v) for v in data.split()])\nif n... | <|body_start_0|>
x = []
if root:
stack = [root]
while stack:
node = stack.pop()
x.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)... | optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder). | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_10k_train_007563 | 2,340 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder).
Method signatures... | Implement the Python class `Codec` described below.
Class description:
optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder).
Method signatures... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""optimize the encoded str size for transmission. 1. Binary tree could be constructed from preorder/postorder and inorder traversal. 2. Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder)."""
def serialize(self, root: TreeNode) -> str:
"""Encodes... | the_stack_v2_python_sparse | src/0400-0499/0449.serialize.deserialize.bst.py | gyang274/leetcode | train | 1 |
6530a97d02c14b7e1355817d81594f39ed9d5d55 | [
"self.k = k\nself.h_train = None\nself.bsk_label_train = None\nself.clf = None",
"assert self.k is not None, 'k cannot be none before train'\nself.h_train = h_train.sign()\nif isinstance(bsk_label_train, pd.DataFrame):\n bsk_label_train = bsk_label_train.values\nself.bsk_label_train = bsk_label_train\nself.clf... | <|body_start_0|>
self.k = k
self.h_train = None
self.bsk_label_train = None
self.clf = None
<|end_body_0|>
<|body_start_1|>
assert self.k is not None, 'k cannot be none before train'
self.h_train = h_train.sign()
if isinstance(bsk_label_train, pd.DataFrame):
... | A knn prediction class | knn_Predictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_10k_train_007564 | 4,002 | no_license | [
{
"docstring": "The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')",
"name": "__init__",
"signature": "def __init__(self, k=None)"
},
{
"docstring": "The train method of class :param h_train... | 4 | stack_v2_sparse_classes_30k_train_004221 | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | 7f9ef25bb9c50f996534ff9067da0d95ac3fdbd5 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
self.k = k
self.h_train = None
self.bs... | the_stack_v2_python_sparse | src/knn_prediction_cls.py | bigdatamatta/HyperGo | train | 0 |
9f9d94431fb2479decd6f5d49cc561af7f1931d8 | [
"super().__init__(order=CallbackOrder.Optimizer, node=CallbackNode.All)\nself.loss_key: str = loss_key\nself.optimizer_key: str = optimizer_key\nself.accumulation_steps: int = accumulation_steps\nself._accumulation_counter: int = 0\ngrad_clip_params: dict = grad_clip_params or {}\nself.grad_clip_fn = registry.GRAD_... | <|body_start_0|>
super().__init__(order=CallbackOrder.Optimizer, node=CallbackNode.All)
self.loss_key: str = loss_key
self.optimizer_key: str = optimizer_key
self.accumulation_steps: int = accumulation_steps
self._accumulation_counter: int = 0
grad_clip_params: dict = gra... | Optimizer callback, abstraction over optimizer step. | OptimizerCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for grad... | stack_v2_sparse_classes_10k_train_007565 | 5,598 | permissive | [
{
"docstring": "Args: grad_clip_params (dict): params for gradient clipping accumulation_steps (int): number of steps before ``model.zero_grad()`` optimizer_key (str): A key to take a optimizer in case there are several of them and they are in a dictionary format. loss_key (str): key to get loss from ``state.lo... | 6 | stack_v2_sparse_classes_30k_test_000244 | Implement the Python class `OptimizerCallback` described below.
Class description:
Optimizer callback, abstraction over optimizer step.
Method signatures and docstrings:
- def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: b... | Implement the Python class `OptimizerCallback` described below.
Class description:
Optimizer callback, abstraction over optimizer step.
Method signatures and docstrings:
- def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: b... | 75ffa808e2bbb9071a169a1a9c813deb6a69a797 | <|skeleton|>
class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for grad... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OptimizerCallback:
"""Optimizer callback, abstraction over optimizer step."""
def __init__(self, loss_key: str='loss', optimizer_key: str=None, accumulation_steps: int=1, grad_clip_params: Dict=None, decouple_weight_decay: bool=True):
"""Args: grad_clip_params (dict): params for gradient clipping... | the_stack_v2_python_sparse | catalyst_rl/core/callbacks/optimizer.py | catalyst-team/catalyst-rl | train | 50 |
cf8ad7922cb70a6d2afaa818d62998ace58c1142 | [
"app.setStyle('Fusion')\nwith open(self._STYLESHEET) as stylesheet:\n app.setStyleSheet(stylesheet.read())",
"darkPalette = QPalette()\ndarkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))\ndarkPalette.setColor(QPalette.Button, QColor(53, 53, 53))\ndarkPalette.setColor(QPalette.Light, QColor(180, 1... | <|body_start_0|>
app.setStyle('Fusion')
with open(self._STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read())
<|end_body_0|>
<|body_start_1|>
darkPalette = QPalette()
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPal... | DarkStyle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
<|body_0|>
def apply_style(self, app):
"""Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ... | stack_v2_sparse_classes_10k_train_007566 | 5,792 | permissive | [
{
"docstring": "Apply base theme to the application. Args: app (QApplication): QApplication instance.",
"name": "_apply_base_theme",
"signature": "def _apply_base_theme(self, app)"
},
{
"docstring": "Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication instance... | 2 | stack_v2_sparse_classes_30k_train_006725 | Implement the Python class `DarkStyle` described below.
Class description:
Implement the DarkStyle class.
Method signatures and docstrings:
- def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance.
- def apply_style(self, app): Apply Dark Theme to the Qt... | Implement the Python class `DarkStyle` described below.
Class description:
Implement the DarkStyle class.
Method signatures and docstrings:
- def _apply_base_theme(self, app): Apply base theme to the application. Args: app (QApplication): QApplication instance.
- def apply_style(self, app): Apply Dark Theme to the Qt... | 7a79feab40ec801198ea5d519948ccbfd0203df3 | <|skeleton|>
class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
<|body_0|>
def apply_style(self, app):
"""Apply Dark Theme to the Qt application instance. Args: app (QApplication): QApplication ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DarkStyle:
def _apply_base_theme(self, app):
"""Apply base theme to the application. Args: app (QApplication): QApplication instance."""
app.setStyle('Fusion')
with open(self._STYLESHEET) as stylesheet:
app.setStyleSheet(stylesheet.read())
def apply_style(self, app):
... | the_stack_v2_python_sparse | folderplay/gui/styles.py | hurlenko/folderplay | train | 1 | |
ed9e175402b075bca6d1fabe8640635b0465da44 | [
"self.contains_change_event = contains_change_event\nself.end_seq_number = end_seq_number\nself.log_file_name = log_file_name\nself.log_rollover = log_rollover\nself.start_seq_number = start_seq_number",
"if dictionary is None:\n return None\ncontains_change_event = dictionary.get('containsChangeEvent')\nend_s... | <|body_start_0|>
self.contains_change_event = contains_change_event
self.end_seq_number = end_seq_number
self.log_file_name = log_file_name
self.log_rollover = log_rollover
self.start_seq_number = start_seq_number
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond to the range of logs inside this file whi... | NoSqlLogData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond t... | stack_v2_sparse_classes_10k_train_007567 | 3,523 | permissive | [
{
"docstring": "Constructor for the NoSqlLogData class",
"name": "__init__",
"signature": "def __init__(self, contains_change_event=None, end_seq_number=None, log_file_name=None, log_rollover=None, start_seq_number=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Arg... | 2 | null | Implement the Python class `NoSqlLogData` described below.
Class description:
Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The star... | Implement the Python class `NoSqlLogData` described below.
Class description:
Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The star... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond to the range o... | the_stack_v2_python_sparse | cohesity_management_sdk/models/no_sql_log_data.py | cohesity/management-sdk-python | train | 24 |
22967d5ae9a84b89ccf0c31c0200765a1c308a72 | [
"if null_default_value is None:\n null_default_value = math.log2(min_included)\nelse:\n null_default_value = math.log2(null_default_value)\nself.min_included: float = min_included\nself.max_included: float = max_included\nself.log2_min_included = math.log2(min_included)\nself.log2_max_included = math.log2(max... | <|body_start_0|>
if null_default_value is None:
null_default_value = math.log2(min_included)
else:
null_default_value = math.log2(null_default_value)
self.min_included: float = min_included
self.max_included: float = max_included
self.log2_min_included = m... | Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`, | ScipyLogUniform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
... | stack_v2_sparse_classes_10k_train_007568 | 19,816 | permissive | [
{
"docstring": "Create a quantized random log uniform distribution. A random float between the two values inclusively will be returned. :param min_included: minimum integer, should be somehow included. :param max_included: maximum integer, should be somehow included. :param null_default_value: null default valu... | 2 | stack_v2_sparse_classes_30k_train_007104 | Implement the Python class `ScipyLogUniform` described below.
Class description:
Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,
Method signatures and docstrings:
- def __init__(self, min_i... | Implement the Python class `ScipyLogUniform` described below.
Class description:
Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,
Method signatures and docstrings:
- def __init__(self, min_i... | af917c984241178436a759be3b830e6d8b03245f | <|skeleton|>
class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScipyLogUniform:
"""Get a LogUniform distribution. Refer to: :class:`scipy.stats.loguniform`. .. seealso:: :func:`~neuraxle.base.BaseStep.set_hyperparams_space`, :class:`ScipyDistributionWrapper`,"""
def __init__(self, min_included: float, max_included: float, null_default_value=None):
"""Create ... | the_stack_v2_python_sparse | neuraxle/hyperparams/scipy_distributions.py | Neuraxio/Neuraxle | train | 597 |
ea8e48ee03ef06a913aa6b02068065f5808793cf | [
"spark.sparkContext.setLogLevel('INFO')\nlog4jLogger = spark.sparkContext._jvm.org.apache.log4j\nlogger = log4jLogger.LogManager.getLogger(__name__)\nindex_mapper_handle = globals()['XML2kvpMapper']\n\ndef es_mapper_pt_udf(pt):\n mapper = index_mapper_handle(field_mapper_config=field_mapper_config)\n for row ... | <|body_start_0|>
spark.sparkContext.setLogLevel('INFO')
log4jLogger = spark.sparkContext._jvm.org.apache.log4j
logger = log4jLogger.LogManager.getLogger(__name__)
index_mapper_handle = globals()['XML2kvpMapper']
def es_mapper_pt_udf(pt):
mapper = index_mapper_handle(... | Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES) | ESIndex | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESIndex:
"""Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)"""
def index_job_to_es_spark(spark, job, records_df, field_mapper_config):
"""Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance ... | stack_v2_sparse_classes_10k_train_007569 | 11,830 | permissive | [
{
"docstring": "Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance from static job methods job (core.models.Job): Job for records records_df (pyspark.sql.DataFrame): records as pyspark DataFrame field_mapper_config (dict): XML2kvp field mapper configurations... | 2 | stack_v2_sparse_classes_30k_train_004231 | Implement the Python class `ESIndex` described below.
Class description:
Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)
Method signatures and docstrings:
- def index_job_to_es_spark(spark, job, records_df, field_mapper_config): Method to index records dataframe into ES Args: ... | Implement the Python class `ESIndex` described below.
Class description:
Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)
Method signatures and docstrings:
- def index_job_to_es_spark(spark, job, records_df, field_mapper_config): Method to index records dataframe into ES Args: ... | eb100ea17193d65485aa6c4a7f05a41b4cab7515 | <|skeleton|>
class ESIndex:
"""Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)"""
def index_job_to_es_spark(spark, job, records_df, field_mapper_config):
"""Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ESIndex:
"""Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)"""
def index_job_to_es_spark(spark, job, records_df, field_mapper_config):
"""Method to index records dataframe into ES Args: spark (pyspark.sql.session.SparkSession): spark instance from static j... | the_stack_v2_python_sparse | core/spark/es.py | tulibraries/combine | train | 1 |
fb63a824c4bf5f1ab1b465f2c9269fa7ccd1568c | [
"need, missing = (collections.Counter(t), len(t))\ncur_left = res_left = res_right = 0\nfor cur_right, c in enumerate(s, 1):\n missing -= need[c] > 0\n need[c] -= 1\n if not missing:\n while cur_left < cur_right and need[s[cur_left]] < 0:\n need[s[cur_left]] += 1\n cur_left += ... | <|body_start_0|>
need, missing = (collections.Counter(t), len(t))
cur_left = res_left = res_right = 0
for cur_right, c in enumerate(s, 1):
missing -= need[c] > 0
need[c] -= 1
if not missing:
while cur_left < cur_right and need[s[cur_left]] < 0:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minWindow(self, s, t):
""":type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still mis... | stack_v2_sparse_classes_10k_train_007570 | 2,478 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still missing. In the loop, first add the new character t... | 2 | stack_v2_sparse_classes_30k_train_006221 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow(self, s, t): :type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how ma... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow(self, s, t): :type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how ma... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def minWindow(self, s, t):
""":type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still mis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minWindow(self, s, t):
""":type s: str :type t: str :rtype: str current window is s[cur_left:cur_right] and the result window is s[res_left:res_right]. In need[c] I store how many times I need character c (can be negative) and missing tells how many characters are still missing. In the l... | the_stack_v2_python_sparse | LeetCode/076_minimum_window_substring.py | yao23/Machine_Learning_Playground | train | 12 | |
75a2af4fa6a4557a64082fdee5b9b2b2d49ee7ed | [
"wx.Panel.__init__(self, parent)\nself.number_of_grids = 0\nself.frame = parent\nself.mainSizer = wx.BoxSizer(wx.VERTICAL)\ncontrolSizer = wx.BoxSizer(wx.HORIZONTAL)\nself.widgetSizer = wx.BoxSizer(wx.VERTICAL)\nself.addButton = wx.Button(self, label='Add')\nself.addButton.Bind(wx.EVT_BUTTON, self.onAddWidget)\ncon... | <|body_start_0|>
wx.Panel.__init__(self, parent)
self.number_of_grids = 0
self.frame = parent
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
controlSizer = wx.BoxSizer(wx.HORIZONTAL)
self.widgetSizer = wx.BoxSizer(wx.VERTICAL)
self.addButton = wx.Button(self, label='Ad... | MyPanel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPanel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onAddWidget(self, event):
"""Add widget."""
<|body_1|>
def onRemoveWidget(self, event):
"""Remove widget."""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
wx.P... | stack_v2_sparse_classes_10k_train_007571 | 6,784 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Add widget.",
"name": "onAddWidget",
"signature": "def onAddWidget(self, event)"
},
{
"docstring": "Remove widget.",
"name": "onRemoveWidget",
"signature": "def ... | 3 | null | Implement the Python class `MyPanel` described below.
Class description:
Implement the MyPanel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onAddWidget(self, event): Add widget.
- def onRemoveWidget(self, event): Remove widget. | Implement the Python class `MyPanel` described below.
Class description:
Implement the MyPanel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onAddWidget(self, event): Add widget.
- def onRemoveWidget(self, event): Remove widget.
<|skeleton|>
class MyPanel:
def __init__... | 5a07e02588b1b7c8ebf7458b10e81b8ecf84ad13 | <|skeleton|>
class MyPanel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onAddWidget(self, event):
"""Add widget."""
<|body_1|>
def onRemoveWidget(self, event):
"""Remove widget."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyPanel:
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.number_of_grids = 0
self.frame = parent
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
controlSizer = wx.BoxSizer(wx.HORIZONTAL)
self.widgetSizer = wx.BoxSizer(wx.VERT... | the_stack_v2_python_sparse | sandbox/dynamic_widgets2.py | baluneboy/pims | train | 0 | |
4a4d476322af18b2a234d0cbdc72c13b320f00a6 | [
"self.header.append(CDF_LABEL)\nkey_list = []\nfor cube in self.cube_list:\n scenario = self.vocab.get_collection_term_label(InputType.SCENARIO, cube.attributes['scenario'])\n var = self.input_data.get_value_label(InputType.VARIABLE)[0].encode('utf-8')\n self.header.append('{var}({scenario})'.format(scenar... | <|body_start_0|>
self.header.append(CDF_LABEL)
key_list = []
for cube in self.cube_list:
scenario = self.vocab.get_collection_term_label(InputType.SCENARIO, cube.attributes['scenario'])
var = self.input_data.get_value_label(InputType.VARIABLE)[0].encode('utf-8')
... | The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self). | CdfCsvWriter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
<|body_0|>
def _read_percentile_cube(self, cube, key_list):
"""Slice... | stack_v2_sparse_classes_10k_train_007572 | 1,782 | permissive | [
{
"docstring": "Write out the data, in CSV format, associated with a CDF plot.",
"name": "_write_csv",
"signature": "def _write_csv(self)"
},
{
"docstring": "Slice the cube over 'percentile' and update data_dict",
"name": "_read_percentile_cube",
"signature": "def _read_percentile_cube(s... | 2 | stack_v2_sparse_classes_30k_train_006069 | Implement the Python class `CdfCsvWriter` described below.
Class description:
The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self).
Method signatures and docstrings:
- def _write_csv(self): Write out the data, in CSV format, associated with a CDF plot.
- def _read_percentile_cube(self, c... | Implement the Python class `CdfCsvWriter` described below.
Class description:
The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self).
Method signatures and docstrings:
- def _write_csv(self): Write out the data, in CSV format, associated with a CDF plot.
- def _read_percentile_cube(self, c... | e400e97feffe6ea59b4f75a32b93f686168d1d58 | <|skeleton|>
class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
<|body_0|>
def _read_percentile_cube(self, cube, key_list):
"""Slice... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
self.header.append(CDF_LABEL)
key_list = []
for cube in self.cube_list:
... | the_stack_v2_python_sparse | ukcp_dp/file_writers/_write_csv_cdf.py | tim779281/ukcp-data-processor | train | 0 |
ebf3cc3dd453c3b141b815afd099e23938d46c17 | [
"stack, node, last, depths = ([], root, None, {})\nprint(node.val, stack, last, depths)\nwhile stack or node:\n if node:\n print(node.val, stack, last, depths)\n stack.append(node)\n node = node.left\n else:\n node = stack[-1]\n if not node.right or last == node.right:\n ... | <|body_start_0|>
stack, node, last, depths = ([], root, None, {})
print(node.val, stack, last, depths)
while stack or node:
if node:
print(node.val, stack, last, depths)
stack.append(node)
node = node.left
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced_iterative(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isBalanced_recursive(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack, node, last, depths =... | stack_v2_sparse_classes_10k_train_007573 | 2,113 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced_iterative",
"signature": "def isBalanced_iterative(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced_recursive",
"signature": "def isBalanced_recursive(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced_iterative(self, root): :type root: TreeNode :rtype: bool
- def isBalanced_recursive(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced_iterative(self, root): :type root: TreeNode :rtype: bool
- def isBalanced_recursive(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def isBalanced_iterative(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isBalanced_recursive(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced_iterative(self, root):
""":type root: TreeNode :rtype: bool"""
stack, node, last, depths = ([], root, None, {})
print(node.val, stack, last, depths)
while stack or node:
if node:
print(node.val, stack, last, depths)
... | the_stack_v2_python_sparse | 110_isBalance.py | jennyChing/leetCode | train | 2 | |
e450c49fe17810a666b80082b8f3e659f88b3a74 | [
"urls = ['http://lab.scrapyd.cn/']\nfor url in urls:\n yield scrapy.Request(url=url, callback=self.parse)",
"page = self.page_index\nself.page_index += 1\nfilename = 'parse_html/scrapyd-%s.html' % page\nbody = response.body\nwith open(filename, 'wb') as fp:\n fp.write(body)\nselect_quote = response.css('div... | <|body_start_0|>
urls = ['http://lab.scrapyd.cn/']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
<|end_body_0|>
<|body_start_1|>
page = self.page_index
self.page_index += 1
filename = 'parse_html/scrapyd-%s.html' % page
body = response.b... | 定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里 | MySpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySpider:
"""定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里"""
def start_requests(self):
"""蜘蛛运行的方法,请求页面 :return:"""
<|body_0|>
def parse(self, response):
"""蜘蛛运行后的回调方法,页面的解析会在这里 :param response... | stack_v2_sparse_classes_10k_train_007574 | 2,087 | no_license | [
{
"docstring": "蜘蛛运行的方法,请求页面 :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "蜘蛛运行后的回调方法,页面的解析会在这里 :param response: :return:",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000013 | Implement the Python class `MySpider` described below.
Class description:
定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里
Method signatures and docstrings:
- def start_requests(self): 蜘蛛运行的方法,请求页面 :return:
- def parse(self, response): 蜘蛛运行后的回调方法,页面的解... | Implement the Python class `MySpider` described below.
Class description:
定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里
Method signatures and docstrings:
- def start_requests(self): 蜘蛛运行的方法,请求页面 :return:
- def parse(self, response): 蜘蛛运行后的回调方法,页面的解... | e4c4fe67009bf9d61af8c86a64689e1e011b9573 | <|skeleton|>
class MySpider:
"""定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里"""
def start_requests(self):
"""蜘蛛运行的方法,请求页面 :return:"""
<|body_0|>
def parse(self, response):
"""蜘蛛运行后的回调方法,页面的解析会在这里 :param response... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MySpider:
"""定义一个蜘蛛类,类名随意,必须继承scrapy.Spider var name:蜘蛛的名称,唯一 fun start_requests:蜘蛛运行的方法,请求对应的页面 fun parse:页面请求后的回调方法,后续的解析都会在这里"""
def start_requests(self):
"""蜘蛛运行的方法,请求页面 :return:"""
urls = ['http://lab.scrapyd.cn/']
for url in urls:
yield scrapy.Request(url=url, ca... | the_stack_v2_python_sparse | 13-4 scrapy/myfirst/myfirst/spiders/myfirst_spider.py | ZGCdeGithub/python-study | train | 0 |
0a93421684c42fe385e9b477fa47cd680587e965 | [
"assert isinstance(public_key, str), type(public_key)\nsuper(MultiChainPaymentProvider, self).__init__()\nself.multi_chain_community = multi_chain_community\nself.public_key = public_key",
"assert isinstance(candidate, Candidate), type(candidate)\nassert isinstance(quantity, Quantity), type(quantity)\nif self.bal... | <|body_start_0|>
assert isinstance(public_key, str), type(public_key)
super(MultiChainPaymentProvider, self).__init__()
self.multi_chain_community = multi_chain_community
self.public_key = public_key
<|end_body_0|>
<|body_start_1|>
assert isinstance(candidate, Candidate), type(c... | "Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers | MultiChainPaymentProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiChainPaymentProvider:
""""Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers"""
def __init__(self, multi_chain_community, public_key):
""":param multi_chain_community: The multi chain community whi... | stack_v2_sparse_classes_10k_train_007575 | 3,445 | no_license | [
{
"docstring": ":param multi_chain_community: The multi chain community which manages multi chain transfers :param public_key: The public key of this peer",
"name": "__init__",
"signature": "def __init__(self, multi_chain_community, public_key)"
},
{
"docstring": "Transfers the selected quantity... | 3 | stack_v2_sparse_classes_30k_val_000108 | Implement the Python class `MultiChainPaymentProvider` described below.
Class description:
"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers
Method signatures and docstrings:
- def __init__(self, multi_chain_community, public_key): :p... | Implement the Python class `MultiChainPaymentProvider` described below.
Class description:
"Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers
Method signatures and docstrings:
- def __init__(self, multi_chain_community, public_key): :p... | cc4d1c27166d68c39e5c38e77bb70093f34e19e5 | <|skeleton|>
class MultiChainPaymentProvider:
""""Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers"""
def __init__(self, multi_chain_community, public_key):
""":param multi_chain_community: The multi chain community whi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiChainPaymentProvider:
""""Multi chain payment provider which enables checking the multi chain balance of this peer and transferring multi chain to other peers"""
def __init__(self, multi_chain_community, public_key):
""":param multi_chain_community: The multi chain community which manages mu... | the_stack_v2_python_sparse | market/core/payment_provider.py | devos50/decentralized-market | train | 0 |
0021b7b30eff4399d0674ee7f96ece172067dc06 | [
"self.analyzer = analyzer\nself.data = self.analyzer.data\nself.hashtags = self.analyzer.hashtags\nreturn",
"data = self.data\ntret = pd.Series(data=data['RTs'].values, index=data['Date'])\nplt.title('Retweets along time')\ntret.plot(figsize=(16, 4), label='Retweets', color='g', legend=True)\nreturn",
"data = s... | <|body_start_0|>
self.analyzer = analyzer
self.data = self.analyzer.data
self.hashtags = self.analyzer.hashtags
return
<|end_body_0|>
<|body_start_1|>
data = self.data
tret = pd.Series(data=data['RTs'].values, index=data['Date'])
plt.title('Retweets along time')
... | TweetsVisualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetsVisualizer:
def __init__(self, analyzer):
"""Constructor function using a TweetsExtractor object."""
<|body_0|>
def retweets(self):
"""Function to plot time series of retweets."""
<|body_1|>
def likes(self):
"""Function to plot time series ... | stack_v2_sparse_classes_10k_train_007576 | 4,029 | no_license | [
{
"docstring": "Constructor function using a TweetsExtractor object.",
"name": "__init__",
"signature": "def __init__(self, analyzer)"
},
{
"docstring": "Function to plot time series of retweets.",
"name": "retweets",
"signature": "def retweets(self)"
},
{
"docstring": "Function ... | 6 | null | Implement the Python class `TweetsVisualizer` described below.
Class description:
Implement the TweetsVisualizer class.
Method signatures and docstrings:
- def __init__(self, analyzer): Constructor function using a TweetsExtractor object.
- def retweets(self): Function to plot time series of retweets.
- def likes(sel... | Implement the Python class `TweetsVisualizer` described below.
Class description:
Implement the TweetsVisualizer class.
Method signatures and docstrings:
- def __init__(self, analyzer): Constructor function using a TweetsExtractor object.
- def retweets(self): Function to plot time series of retweets.
- def likes(sel... | 02b77652d0901e6e06cb9b1e7cb3e59c675445c2 | <|skeleton|>
class TweetsVisualizer:
def __init__(self, analyzer):
"""Constructor function using a TweetsExtractor object."""
<|body_0|>
def retweets(self):
"""Function to plot time series of retweets."""
<|body_1|>
def likes(self):
"""Function to plot time series ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TweetsVisualizer:
def __init__(self, analyzer):
"""Constructor function using a TweetsExtractor object."""
self.analyzer = analyzer
self.data = self.analyzer.data
self.hashtags = self.analyzer.hashtags
return
def retweets(self):
"""Function to plot time ser... | the_stack_v2_python_sparse | 47/RodolfoFerro/scripts/visualizer.py | pybites/challenges | train | 764 | |
feada690bdbf32241921ed938f937eaaa5ed25ee | [
"assert isinstance(converter, Converter), 'Invalid converter %s' % converter\nassert isinstance(baseTimeZone, tzinfo), 'Invalid base time zone %s' % baseTimeZone\nassert isinstance(timeZoneStr, tzinfo), 'Invalid time zone %s' % timeZoneStr\nassert isinstance(timeZoneVal, tzinfo), 'Invalid time zone %s' % timeZoneVa... | <|body_start_0|>
assert isinstance(converter, Converter), 'Invalid converter %s' % converter
assert isinstance(baseTimeZone, tzinfo), 'Invalid base time zone %s' % baseTimeZone
assert isinstance(timeZoneStr, tzinfo), 'Invalid time zone %s' % timeZoneStr
assert isinstance(timeZoneVal, tzi... | Provides the converter time zone support. | ConverterTimeZone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConverterTimeZone:
"""Provides the converter time zone support."""
def __init__(self, converter, baseTimeZone, timeZoneStr, timeZoneVal):
"""Construct the GMT converter. @param converter: Converter The wrapped converter. @param baseTimeZone: tzinfo The time zone of the dates to be co... | stack_v2_sparse_classes_10k_train_007577 | 5,482 | no_license | [
{
"docstring": "Construct the GMT converter. @param converter: Converter The wrapped converter. @param baseTimeZone: tzinfo The time zone of the dates to be converted. @param timeZoneStr: tzinfo The time zone to convert to string values. @param timeZoneVal: tzinfo The time zone to convert the string values.",
... | 3 | null | Implement the Python class `ConverterTimeZone` described below.
Class description:
Provides the converter time zone support.
Method signatures and docstrings:
- def __init__(self, converter, baseTimeZone, timeZoneStr, timeZoneVal): Construct the GMT converter. @param converter: Converter The wrapped converter. @param... | Implement the Python class `ConverterTimeZone` described below.
Class description:
Provides the converter time zone support.
Method signatures and docstrings:
- def __init__(self, converter, baseTimeZone, timeZoneStr, timeZoneVal): Construct the GMT converter. @param converter: Converter The wrapped converter. @param... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class ConverterTimeZone:
"""Provides the converter time zone support."""
def __init__(self, converter, baseTimeZone, timeZoneStr, timeZoneVal):
"""Construct the GMT converter. @param converter: Converter The wrapped converter. @param baseTimeZone: tzinfo The time zone of the dates to be co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConverterTimeZone:
"""Provides the converter time zone support."""
def __init__(self, converter, baseTimeZone, timeZoneStr, timeZoneVal):
"""Construct the GMT converter. @param converter: Converter The wrapped converter. @param baseTimeZone: tzinfo The time zone of the dates to be converted. @par... | the_stack_v2_python_sparse | components/ally-core-http/ally/core/http/impl/processor/time_zone.py | cristidomsa/Ally-Py | train | 0 |
d0a6a39dd60bea10526e952203637ff086a093e1 | [
"if not email:\n raise ValueError('A user must have an email address!')\nif not email:\n raise ValueError('A user must have a email!')\nemail = self.normalize_email(email)\nuser = self.model(email=email, **kwargs)\nif password:\n user.set_password(password)\nelse:\n user.set_unusable_password()\n use... | <|body_start_0|>
if not email:
raise ValueError('A user must have an email address!')
if not email:
raise ValueError('A user must have a email!')
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
if password:
user.set... | Model manager for customized user model UserProfile | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
<|body_0|>
def create_superuser(self, email, password):
"""Create a new su... | stack_v2_sparse_classes_10k_train_007578 | 2,727 | no_license | [
{
"docstring": "Create a new user profile with no special permissions.",
"name": "create_user",
"signature": "def create_user(self, email, password, **kwargs)"
},
{
"docstring": "Create a new super user",
"name": "create_superuser",
"signature": "def create_superuser(self, email, passwor... | 2 | stack_v2_sparse_classes_30k_train_001539 | Implement the Python class `UserProfileManager` described below.
Class description:
Model manager for customized user model UserProfile
Method signatures and docstrings:
- def create_user(self, email, password, **kwargs): Create a new user profile with no special permissions.
- def create_superuser(self, email, passw... | Implement the Python class `UserProfileManager` described below.
Class description:
Model manager for customized user model UserProfile
Method signatures and docstrings:
- def create_user(self, email, password, **kwargs): Create a new user profile with no special permissions.
- def create_superuser(self, email, passw... | dc046f42a4d570abd7837490e41062eb43387816 | <|skeleton|>
class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
<|body_0|>
def create_superuser(self, email, password):
"""Create a new su... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
if not email:
raise ValueError('A user must have an email address!')
if not emai... | the_stack_v2_python_sparse | src/usuarios/models.py | overflow/canchas | train | 0 |
ba6cf20004e4b9c543a487e4bc16c4dbd5b57dbd | [
"def cal(s1: str, s2: str) -> int:\n res = 0\n curSum, curSumWithS2 = (0, -int(1e+18))\n for char in s:\n if char == s1:\n curSum += 1\n curSumWithS2 += 1\n elif char == s2:\n curSum -= 1\n curSumWithS2 = curSum\n if curSum < 0:\n ... | <|body_start_0|>
def cal(s1: str, s2: str) -> int:
res = 0
curSum, curSumWithS2 = (0, -int(1e+18))
for char in s:
if char == s1:
curSum += 1
curSumWithS2 += 1
elif char == s2:
curSum -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestVariance(self, s: str) -> int:
"""时间复杂度O(26*26*n)"""
<|body_0|>
def largestVariance2(self, s: str) -> int:
"""时间复杂度O(26*n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def cal(s1: str, s2: str) -> int:
res = 0
... | stack_v2_sparse_classes_10k_train_007579 | 2,204 | no_license | [
{
"docstring": "时间复杂度O(26*26*n)",
"name": "largestVariance",
"signature": "def largestVariance(self, s: str) -> int"
},
{
"docstring": "时间复杂度O(26*n)",
"name": "largestVariance2",
"signature": "def largestVariance2(self, s: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_000731 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestVariance(self, s: str) -> int: 时间复杂度O(26*26*n)
- def largestVariance2(self, s: str) -> int: 时间复杂度O(26*n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestVariance(self, s: str) -> int: 时间复杂度O(26*26*n)
- def largestVariance2(self, s: str) -> int: 时间复杂度O(26*n)
<|skeleton|>
class Solution:
def largestVariance(self, s... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def largestVariance(self, s: str) -> int:
"""时间复杂度O(26*26*n)"""
<|body_0|>
def largestVariance2(self, s: str) -> int:
"""时间复杂度O(26*n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestVariance(self, s: str) -> int:
"""时间复杂度O(26*26*n)"""
def cal(s1: str, s2: str) -> int:
res = 0
curSum, curSumWithS2 = (0, -int(1e+18))
for char in s:
if char == s1:
curSum += 1
curS... | the_stack_v2_python_sparse | 11_动态规划/子数组/最大子数组和/6069. 最大波动的子字符串-kanade.py | 981377660LMT/algorithm-study | train | 225 | |
a8c55b3ddd7df48597f06f47a0b647cc95e6dfdb | [
"pygame.sprite.Sprite.__init__(self)\nsprite_sheet = SpriteSheet('Golem.png')\nimage = sprite_sheet.get_image(262, 471, 272, 47)\nself.image = image\nself.rect = self.image.get_rect()\nself.rect.x = 400\nself.rect.y = -47\nself.change_y = 0\nself.bounce = 0\nself.count = 0\nself.beginCount = False",
"if self.rect... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
sprite_sheet = SpriteSheet('Golem.png')
image = sprite_sheet.get_image(262, 471, 272, 47)
self.image = image
self.rect = self.image.get_rect()
self.rect.x = 400
self.rect.y = -47
self.change_y = 0
... | win | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite ... | stack_v2_sparse_classes_10k_train_007580 | 2,788 | no_license | [
{
"docstring": "This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite self.rect.y: The y-position of the s... | 2 | stack_v2_sparse_classes_30k_train_005288 | Implement the Python class `win` described below.
Class description:
Implement the win class.
Method signatures and docstrings:
- def __init__(self): This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represen... | Implement the Python class `win` described below.
Class description:
Implement the win class.
Method signatures and docstrings:
- def __init__(self): This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represen... | 56fbcfc786dfc373f477270468f06e31b6271749 | <|skeleton|>
class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite self.rect.y: T... | the_stack_v2_python_sparse | Doki Doki Island/winning.py | cashpop5000/DokiProject | train | 0 | |
8e2828d8b44921476b5ac8f523d1ca777d70a368 | [
"DE = 0.001\nCHI = 10\nN = 108\nLAM = 306.3\nBETA = 16\nTHC_DIM = 350\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)\nstps1 = output[0]\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)\nassert output == (10912, 5250145120, 2142)",
"DE = 0.001\nCHI = 10\nN = 152\nLAM = 1201... | <|body_start_0|>
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stps1 = output[0]
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)
assert... | THCCostTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
DE = 0.001
... | stack_v2_sparse_classes_10k_train_007581 | 1,527 | permissive | [
{
"docstring": "Reproduce Reiher et al orbital THC FT costs from paper",
"name": "test_reiher_thc",
"signature": "def test_reiher_thc(self)"
},
{
"docstring": "Reproduce Li et al orbital THC FT costs from paper",
"name": "test_li_thc",
"signature": "def test_li_thc(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004955 | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper
<|skeleton|>
... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stp... | the_stack_v2_python_sparse | src/openfermion/resource_estimates/thc/compute_cost_thc_test.py | quantumlib/OpenFermion | train | 1,481 | |
43d76d82a3febc268f235315ece3a3e5423d0b62 | [
"if fx is None:\n\n def fx(x):\n np.logical_not(np.isnan(x).sum(0))\nself._fx = fx",
"mask = self._fx(ds.samples)\nds_ = ds[:, mask]\nreturn ds_"
] | <|body_start_0|>
if fx is None:
def fx(x):
np.logical_not(np.isnan(x).sum(0))
self._fx = fx
<|end_body_0|>
<|body_start_1|>
mask = self._fx(ds.samples)
ds_ = ds[:, mask]
return ds_
<|end_body_1|>
| FeatureExpressionSlicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str... | stack_v2_sparse_classes_10k_train_007582 | 7,736 | no_license | [
{
"docstring": "This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str The sample attribute to use for slicing and calculating values. compar... | 2 | stack_v2_sparse_classes_30k_train_003414 | Implement the Python class `FeatureExpressionSlicer` described below.
Class description:
Implement the FeatureExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, fx=np.greater): This object is used when we want to slice samples based on some values and thresholds. For example if we want to ... | Implement the Python class `FeatureExpressionSlicer` described below.
Class description:
Implement the FeatureExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, fx=np.greater): This object is used when we want to slice samples based on some values and thresholds. For example if we want to ... | 3adbbd4feaaac4d1bb00e88f9ed62debef2a0483 | <|skeleton|>
class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureExpressionSlicer:
def __init__(self, fx=np.greater):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude features with some common characteristics, for example those with nans. Parameters ---------- attr : str The sample at... | the_stack_v2_python_sparse | pyitab/preprocessing/slicers.py | robbisg/pyitab | train | 1 | |
8f628d9883f132531e7589e207ab2ae7091bff3e | [
"print(\"'%s' is a scalar value of type '%s'.\" % (expr, value.type))\nprint('%s = %s' % (expr, str(value)))\nif is_child:\n Explorer.return_to_parent_value_prompt()\n Explorer.return_to_parent_value()\nreturn False",
"if datatype.code == gdb.TYPE_CODE_ENUM:\n if is_child:\n print(\"%s is of an en... | <|body_start_0|>
print("'%s' is a scalar value of type '%s'." % (expr, value.type))
print('%s = %s' % (expr, str(value)))
if is_child:
Explorer.return_to_parent_value_prompt()
Explorer.return_to_parent_value()
return False
<|end_body_0|>
<|body_start_1|>
... | Internal class used to explore scalar values. | ScalarExplorer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarExplorer:
"""Internal class used to explore scalar values."""
def explore_expr(expr, value, is_child):
"""Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information."""
<|body_0|>
def explore_type(name, datatype, i... | stack_v2_sparse_classes_10k_train_007583 | 26,692 | permissive | [
{
"docstring": "Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information.",
"name": "explore_expr",
"signature": "def explore_expr(expr, value, is_child)"
},
{
"docstring": "Function to explore scalar types. See Explorer.explore_type and Explo... | 2 | stack_v2_sparse_classes_30k_test_000164 | Implement the Python class `ScalarExplorer` described below.
Class description:
Internal class used to explore scalar values.
Method signatures and docstrings:
- def explore_expr(expr, value, is_child): Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information.
- de... | Implement the Python class `ScalarExplorer` described below.
Class description:
Internal class used to explore scalar values.
Method signatures and docstrings:
- def explore_expr(expr, value, is_child): Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information.
- de... | b90664de0bd4c1897a9f1f5d9e360a9631d38b34 | <|skeleton|>
class ScalarExplorer:
"""Internal class used to explore scalar values."""
def explore_expr(expr, value, is_child):
"""Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information."""
<|body_0|>
def explore_type(name, datatype, i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScalarExplorer:
"""Internal class used to explore scalar values."""
def explore_expr(expr, value, is_child):
"""Function to explore scalar values. See Explorer.explore_expr and Explorer.is_scalar_type for more information."""
print("'%s' is a scalar value of type '%s'." % (expr, value.typ... | the_stack_v2_python_sparse | toolchain/riscv/Linux/share/gdb/python/gdb/command/explore.py | bouffalolab/bl_iot_sdk | train | 244 |
74e1196e322b18981339e8a17f085eeba04e6ebf | [
"argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')\nargument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u'store', default=cls._DEFAULT... | <|body_start_0|>
argument_group.add_argument(u'--case_name', dest=u'case_name', type=str, action=u'store', default=cls._DEFAULT_CASE, help=u'Add a case name. This will be the name of the index in ElasticSearch.')
argument_group.add_argument(u'--document_type', dest=u'document_type', type=str, action=u's... | CLI arguments helper class for an Elastic Search output module. | ElasticOutputHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_10k_train_007584 | 2,989 | permissive | [
{
"docstring": "Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group: the argparse group (instance of argparse._ArgumentGroup or or argparse... | 2 | stack_v2_sparse_classes_30k_train_002207 | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | Implement the Python class `ElasticOutputHelper` described below.
Class description:
CLI arguments helper class for an Elastic Search output module.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Add command line arguments the helper supports to an argument group. This function takes an ar... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElasticOutputHelper:
"""CLI arguments helper class for an Elastic Search output module."""
def AddArguments(cls, argument_group):
"""Add command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the comma... | the_stack_v2_python_sparse | plaso/cli/helpers/elastic_output.py | CNR-ITTIG/plasodfaxp | train | 1 |
fbf5c273959467d628a58aac69b42c79f4532202 | [
"dummy = ListNode(0)\ndummy.next = head\nlength = 0\nnode = dummy\nwhile node.next:\n length += 1\n node = node.next\nlength -= n\nnode = dummy\nwhile length > 0:\n length -= 1\n node = node.next\nnode.next = node.next.next\nreturn dummy.next",
"dummy = ListNode(0)\ndummy.next = head\nfirst = dummy\ns... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
length = 0
node = dummy
while node.next:
length += 1
node = node.next
length -= n
node = dummy
while length > 0:
length -= 1
node = node.next
nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode11"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007585 | 1,751 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode11",
"name": "removeNthFromEnd2",
"signature": "def removeNthFromEnd2(s... | 2 | stack_v2_sparse_classes_30k_train_002628 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | 628654fad22589b15350622084e8c69d58e3563b | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode11"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
dummy = ListNode(0)
dummy.next = head
length = 0
node = dummy
while node.next:
length += 1
node = node.next
length -= n
... | the_stack_v2_python_sparse | code/19 删除链表的倒数第n个节点.py | lmzzzzz1/leetcode | train | 0 | |
95ee67a269e813e23d273cef3779dad7371532cd | [
"if s in self.canWinTable:\n return self.canWinTable[s]\nnextStates = self.generatePossibleNextMoves(s)\nfor state in nextStates:\n if not self.canWin(state):\n self.canWinTable[s] = True\n return True\nself.canWinTable[s] = False\nreturn False",
"result = []\nfor i in range(len(s) - 1):\n ... | <|body_start_0|>
if s in self.canWinTable:
return self.canWinTable[s]
nextStates = self.generatePossibleNextMoves(s)
for state in nextStates:
if not self.canWin(state):
self.canWinTable[s] = True
return True
self.canWinTable[s] = Fa... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def generatePossibleNextMoves(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s in self.canWinTable:
return self.can... | stack_v2_sparse_classes_10k_train_007586 | 1,057 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "canWin",
"signature": "def canWin(self, s)"
},
{
"docstring": ":type s: str :rtype: List[str]",
"name": "generatePossibleNextMoves",
"signature": "def generatePossibleNextMoves(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def generatePossibleNextMoves(self, s): :type s: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def generatePossibleNextMoves(self, s): :type s: str :rtype: List[str]
<|skeleton|>
class Solution:
def canWin(self, s):
... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def generatePossibleNextMoves(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
if s in self.canWinTable:
return self.canWinTable[s]
nextStates = self.generatePossibleNextMoves(s)
for state in nextStates:
if not self.canWin(state):
self.canWinTable[s] = T... | the_stack_v2_python_sparse | Python_leetcode/294_flip_game_II.py | xiangcao/Leetcode | train | 0 | |
847cf4a956b4a2610e67be186ecf144e59a0c819 | [
"if not height:\n return 0\narea, left, right, L = (0, 0, len(height) - 1, len(height) - 1)\nwhile left < right:\n if height[left] < height[right]:\n area = max(area, height[left] * L)\n left += 1\n else:\n area = max(area, height[right] * L)\n right -= 1\n L -= 1\nreturn are... | <|body_start_0|>
if not height:
return 0
area, left, right, L = (0, 0, len(height) - 1, len(height) - 1)
while left < right:
if height[left] < height[right]:
area = max(area, height[left] * L)
left += 1
else:
are... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
"""选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:"""
<|body_0|>
def maxAreaWithWall(self, height):
"""每个位置i都有一条高度为heigh[i]的隔板 :param height: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not height:
... | stack_v2_sparse_classes_10k_train_007587 | 4,454 | permissive | [
{
"docstring": "选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": "每个位置i都有一条高度为heigh[i]的隔板 :param height: :return:",
"name": "maxAreaWithWall",
"signature": "def maxAreaWithWall(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): 选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:
- def maxAreaWithWall(self, height): 每个位置i都有一条高度为heigh[i]的隔板 :param height: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): 选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:
- def maxAreaWithWall(self, height): 每个位置i都有一条高度为heigh[i]的隔板 :param height: :return:
<|skeleton|>
class ... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def maxArea(self, height):
"""选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:"""
<|body_0|>
def maxAreaWithWall(self, height):
"""每个位置i都有一条高度为heigh[i]的隔板 :param height: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
"""选择两条竖线隔板之后他们之间是没有隔板的。 :param height: :return:"""
if not height:
return 0
area, left, right, L = (0, 0, len(height) - 1, len(height) - 1)
while left < right:
if height[left] < height[right]:
area = m... | the_stack_v2_python_sparse | leetcode/hard/Container_With_Most_Water.py | shhuan/algorithms | train | 0 | |
3b015eb59532f512ab2aab084c2d59d635c5a009 | [
"if k > len(nums):\n return ()\npreSum = 0\nmaxSum = -float('Inf')\nfor i in range(0, len(nums) - k + 1):\n preSum = sum(nums[i:i + k])\n maxSum = max(maxSum, preSum)\nreturn maxSum / k",
"if k > len(nums):\n return ()\npreSum = sum(nums[0:k])\nmaxSum = preSum\nfor i in range(k, len(nums)):\n preSu... | <|body_start_0|>
if k > len(nums):
return ()
preSum = 0
maxSum = -float('Inf')
for i in range(0, len(nums) - k + 1):
preSum = sum(nums[i:i + k])
maxSum = max(maxSum, preSum)
return maxSum / k
<|end_body_0|>
<|body_start_1|>
if k > len(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def findMaxAverage2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if... | stack_v2_sparse_classes_10k_train_007588 | 1,288 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: float",
"name": "findMaxAverage",
"signature": "def findMaxAverage(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: float",
"name": "findMaxAverage2",
"signature": "def findMaxAverage2(self, nums, k)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def findMaxAverage2(self, nums, k): :type nums: List[int] :type k: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def findMaxAverage2(self, nums, k): :type nums: List[int] :type k: int :rtype: float
<|skel... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def findMaxAverage2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
if k > len(nums):
return ()
preSum = 0
maxSum = -float('Inf')
for i in range(0, len(nums) - k + 1):
preSum = sum(nums[i:i + k])
maxSum... | the_stack_v2_python_sparse | 643_MaximumAverageSubarrayI.py | fxy1018/Leetcode | train | 1 | |
533090537ef05fc6faa3738b6a8c8bfa6c2ca461 | [
"buf = self.value[:]\nwhile True:\n if len(buf) <= 8:\n break\n next_entry_offset, flags, ea_name_length, ea_value_length = struct.unpack('<LBBH', buf[:8])\n if 9 + ea_name_length + ea_value_length > len(buf) or next_entry_offset > len(buf):\n break\n name = buf[8:8 + ea_name_length + 1]\n... | <|body_start_0|>
buf = self.value[:]
while True:
if len(buf) <= 8:
break
next_entry_offset, flags, ea_name_length, ea_value_length = struct.unpack('<LBBH', buf[:8])
if 9 + ea_name_length + ea_value_length > len(buf) or next_entry_offset > len(buf):
... | $EA. | EA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EA:
"""$EA."""
def data_parsed(self):
"""Attempt to parse the extended attribute and yield (name, flags, value) tuples."""
<|body_0|>
def print_information(self):
"""Print all information in a human-readable form."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_007589 | 36,119 | permissive | [
{
"docstring": "Attempt to parse the extended attribute and yield (name, flags, value) tuples.",
"name": "data_parsed",
"signature": "def data_parsed(self)"
},
{
"docstring": "Print all information in a human-readable form.",
"name": "print_information",
"signature": "def print_informati... | 2 | null | Implement the Python class `EA` described below.
Class description:
$EA.
Method signatures and docstrings:
- def data_parsed(self): Attempt to parse the extended attribute and yield (name, flags, value) tuples.
- def print_information(self): Print all information in a human-readable form. | Implement the Python class `EA` described below.
Class description:
$EA.
Method signatures and docstrings:
- def data_parsed(self): Attempt to parse the extended attribute and yield (name, flags, value) tuples.
- def print_information(self): Print all information in a human-readable form.
<|skeleton|>
class EA:
... | f9299b8ad0cb2a6bbbd5e65f01d2ba06406c70ac | <|skeleton|>
class EA:
"""$EA."""
def data_parsed(self):
"""Attempt to parse the extended attribute and yield (name, flags, value) tuples."""
<|body_0|>
def print_information(self):
"""Print all information in a human-readable form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EA:
"""$EA."""
def data_parsed(self):
"""Attempt to parse the extended attribute and yield (name, flags, value) tuples."""
buf = self.value[:]
while True:
if len(buf) <= 8:
break
next_entry_offset, flags, ea_name_length, ea_value_length = st... | the_stack_v2_python_sparse | modules/NTFS/dfir_ntfs/Attributes.py | dfrc-korea/carpe | train | 75 |
50d2d7513af61a00e7d9971fb3a8bff6ab45661d | [
"self.m = MPRester(api_key)\nself.dff = None\nself.ids = None",
"print('Will fetch %s inorganic compounds from Materials Project' % len(mp_ids))\n\ndef grouper(iterable, n, fillvalue=None):\n \"\"\"\"\n Split requests into fixed number groups\n eg: grouper('ABCDEFG', 3, 'x') --> ABC DEF G... | <|body_start_0|>
self.m = MPRester(api_key)
self.dff = None
self.ids = None
<|end_body_0|>
<|body_start_1|>
print('Will fetch %s inorganic compounds from Materials Project' % len(mp_ids))
def grouper(iterable, n, fillvalue=None):
""""
Split reque... | API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props=['material_id', "cif"]) Will fetch ... | MpAccess | [
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props... | stack_v2_sparse_classes_10k_train_007590 | 6,563 | permissive | [
{
"docstring": "Parameters ---------- api_key:str: pymatgen key.",
"name": "__init__",
"signature": "def __init__(self, api_key: str='Di28ZMunseR8vr46')"
},
{
"docstring": "Fetch file from pymatgen. prop_name=['band_gap','density',\"icsd_ids\"'volume','material_id','pretty_formula','elements',\"... | 5 | stack_v2_sparse_classes_30k_train_002461 | Implement the Python class `MpAccess` described below.
Class description:
API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df ... | Implement the Python class `MpAccess` described below.
Class description:
API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df ... | 47eea268d59fb036c4db0387fd845e53c7991178 | <|skeleton|>
class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MpAccess:
"""API for pymatgen database, access pymatgen to get data. Examples -------- >>> mpa = MpAccess("Di28ZMunseR8vr57") # change yourself key. >>> ids = mpa.get_ids({"elements": {"$in": ["Al","O"]},'nelements': {"$lt": 2, "$gte": 1}}) number 29 >>> df = mpa.data_fetcher(mp_ids=ids, mp_props=['material_i... | the_stack_v2_python_sparse | featurebox/data/mp_access.py | boliqq07/featurebox | train | 1 |
dcb6183f960faaf186f21ccad580cba644c5a288 | [
"obj = Invoice.objects.select_for_update().filter(slug=slug).first()\nif obj is None:\n raise Http404()\nclient_ip, is_routable = get_client_ip(self.request)\nself.check_object_permissions(request, obj)\nserializer = InvoiceRetrieveUpdateSerializer(obj, many=False)\nreturn Response(data=serializer.data, status=s... | <|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permissions(request, obj)
serializer = InvoiceRetrieveUpdateSerializer(obj, many... | InvoiceRetrieveDestroyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = Invoice.objects.select_for_update().filter(slug=slug).first(... | stack_v2_sparse_classes_10k_train_007591 | 7,213 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, slug=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, pk=None)"
}
] | 2 | null | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update | Implement the Python class `InvoiceRetrieveDestroyAPIView` described below.
Class description:
Implement the InvoiceRetrieveDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, pk=None): Update
<|skeleton|>
class InvoiceRetrieveDestroyAPIView:... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, pk=None):
"""Update"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InvoiceRetrieveDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
obj = Invoice.objects.select_for_update().filter(slug=slug).first()
if obj is None:
raise Http404()
client_ip, is_routable = get_client_ip(self.request)
self.check_object_permis... | the_stack_v2_python_sparse | mikaponics/ecommerce/views/resources/invoice_views.py | mikaponics/mikaponics-back | train | 4 | |
fbf73fe4de2533d49992a3312390a173168fd486 | [
"self.disable_network = disable_network\nself.preserve_mac_address = preserve_mac_address\nself.source_network_id = source_network_id\nself.target_network_id = target_network_id",
"if dictionary is None:\n return None\ndisable_network = dictionary.get('disableNetwork')\npreserve_mac_address = dictionary.get('p... | <|body_start_0|>
self.disable_network = disable_network
self.preserve_mac_address = preserve_mac_address
self.source_network_id = source_network_id
self.target_network_id = target_network_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
d... | Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, if the network should be kept in disabled s... | NetworkMapping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, i... | stack_v2_sparse_classes_10k_train_007592 | 2,789 | permissive | [
{
"docstring": "Constructor for the NetworkMapping class",
"name": "__init__",
"signature": "def __init__(self, disable_network=None, preserve_mac_address=None, source_network_id=None, target_network_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | null | Implement the Python class `NetworkMapping` described below.
Class description:
Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be dis... | Implement the Python class `NetworkMapping` described below.
Class description:
Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be dis... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, if the network... | the_stack_v2_python_sparse | cohesity_management_sdk/models/network_mapping.py | cohesity/management-sdk-python | train | 24 |
d3c4973ebb4599aae04a88b822e28d65139846dc | [
"active_object = context.active_object\nif active_object and active_object.type == 'ARMATURE' and active_object.animation_data:\n action = active_object.animation_data.action\n if action:\n _animation_utils.set_fps_for_preview(context.scene, self.length, self.anim_start, self.anim_end)",
"active_obje... | <|body_start_0|>
active_object = context.active_object
if active_object and active_object.type == 'ARMATURE' and active_object.animation_data:
action = active_object.animation_data.action
if action:
_animation_utils.set_fps_for_preview(context.scene, self.length, ... | Animation property inventory, which gets saved into *.blend file. | ObjectAnimationInventoryItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s... | stack_v2_sparse_classes_10k_train_007593 | 48,834 | no_license | [
{
"docstring": "If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the game engine. :param context: Blender Context :type context: bpy.types.Context",
"name": "length_update",
"signature": "def length_u... | 3 | null | Implement the Python class `ObjectAnimationInventoryItem` described below.
Class description:
Animation property inventory, which gets saved into *.blend file.
Method signatures and docstrings:
- def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba... | Implement the Python class `ObjectAnimationInventoryItem` described below.
Class description:
Animation property inventory, which gets saved into *.blend file.
Method signatures and docstrings:
- def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the g... | the_stack_v2_python_sparse | All_In_One/addons/io_scs_tools/properties/object.py | 2434325680/Learnbgame | train | 0 |
fe8e4d2b10cb644bb5e60d97d2a77470648f8818 | [
"if self.config.model_arch == ModelArchitecture.F_NET:\n self._init_fourier_transform()\nkey = random.PRNGKey(self.random_seed)\nencoder_blocks = []\nfor layer in range(self.config.num_layers):\n key, mixing_key = random.split(key)\n mixing_arch = ModelArchitecture.BERT if self._is_attention_layer(layer) e... | <|body_start_0|>
if self.config.model_arch == ModelArchitecture.F_NET:
self._init_fourier_transform()
key = random.PRNGKey(self.random_seed)
encoder_blocks = []
for layer in range(self.config.num_layers):
key, mixing_key = random.split(key)
mixing_arch... | Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture. | EncoderModel | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_10k_train_007594 | 15,842 | permissive | [
{
"docstring": "Initializes encoder with config-dependent mixing layer.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Applies model on the inputs. Args: input_ids: Tokenized inputs of shape <int>[BATCH_SIZE, MAX_SEQ_LENGTH]. input_mask: <bool>[BATCH_SIZE, MAX_SEQ_LENGTH] m... | 5 | stack_v2_sparse_classes_30k_train_000804 | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | Implement the Python class `EncoderModel` described below.
Class description:
Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture.
Method signatures and docstrings:
- def setup(self): Ini... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncoderModel:
"""Encoder model without any task-specific heads. Attributes: config: Model specifications. random_seed: Random number generator seed. Only used by ModelArchitecture.RANDOM architecture."""
def setup(self):
"""Initializes encoder with config-dependent mixing layer."""
if sel... | the_stack_v2_python_sparse | f_net/models.py | Jimmy-INL/google-research | train | 1 |
c7482a4492bc592cc99600fee56a50122fb06b53 | [
"self.kw = kwargs\nStep.__init__(self, *args, routine=routine, **kwargs)\nqscale_settings = self.parse_settings(self.get_requested_settings())\nqbcal.QScale.__init__(self, dev=self.dev, **qscale_settings)",
"kwargs = {}\ntask_list = []\nfor qb in self.qubits:\n task = {}\n task_list_fields = requested_kwarg... | <|body_start_0|>
self.kw = kwargs
Step.__init__(self, *args, routine=routine, **kwargs)
qscale_settings = self.parse_settings(self.get_requested_settings())
qbcal.QScale.__init__(self, dev=self.dev, **qscale_settings)
<|end_body_0|>
<|body_start_1|>
kwargs = {}
task_list... | A wrapper class for the QScale experiment. | QScaleStep | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QScaleStep:
"""A wrapper class for the QScale experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): Lis... | stack_v2_sparse_classes_10k_train_007595 | 48,290 | permissive | [
{
"docstring": "Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits to be used in the routine. Configuration parameters (coming from the configuration parameter dictionary): tran... | 3 | stack_v2_sparse_classes_30k_train_005610 | Implement the Python class `QScaleStep` described below.
Class description:
A wrapper class for the QScale experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (St... | Implement the Python class `QScaleStep` described below.
Class description:
A wrapper class for the QScale experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (St... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class QScaleStep:
"""A wrapper class for the QScale experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): Lis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QScaleStep:
"""A wrapper class for the QScale experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the QScaleStep class, which also includes initialization of the QScale experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits t... | the_stack_v2_python_sparse | pycqed/measurement/calibration/automatic_calibration_routines/single_qubit_routines.py | QudevETH/PycQED_py3 | train | 8 |
4d866359ebc5ac83258332ebea965fb946d93db7 | [
"self.func = func\nself.args = args or list()\nself.kwargs = kwargs or dict()\nself.name = name or 'Generic'\nself.is_complete = Event()\nself.output = None",
"if not self.is_complete.isSet():\n if self.name != 'Parsing':\n zdslog.debug('Performing %s Task' % self.name)\n try:\n self.output = ... | <|body_start_0|>
self.func = func
self.args = args or list()
self.kwargs = kwargs or dict()
self.name = name or 'Generic'
self.is_complete = Event()
self.output = None
<|end_body_0|>
<|body_start_1|>
if not self.is_complete.isSet():
if self.name != 'P... | Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of this task, default 'Generic' .. att... | Task | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of thi... | stack_v2_sparse_classes_10k_train_007596 | 2,478 | permissive | [
{
"docstring": "Initializes a Task. :param func: what this Task calls when it's performed :type func: function :param args: A list of positional arguments to pass to func, default None :param kwargs: A list of keyword arguments to pass to func, default None :param name: The (optional) name of this task, default... | 2 | stack_v2_sparse_classes_30k_train_005703 | Implement the Python class `Task` described below.
Class description:
Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attr... | Implement the Python class `Task` described below.
Class description:
Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attr... | 2d0c88778f1dd1f820a9685032fc68d3f91f3532 | <|skeleton|>
class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of thi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Task:
"""Represents a Task to be performed. .. attribute:: func The function this Task will call when it is performed .. attribute:: args A list of positional arguments to pass to func .. attribute:: kwargs A list of keyword arguments to pass to func .. attribute:: name The (optional) name of this task, defau... | the_stack_v2_python_sparse | trunk/ZDStack/ZDSTask.py | camgunz/zdstack | train | 2 |
c6953f40c6acd800332b638779a4d58b278fe4ca | [
"m, n = (len(board), len(board[0]))\ndie_to_live, live_to_die = ([], [])\n\ndef numOfLives(i, j):\n lives_count = 0\n for r, c in ((i + 1, j), (i - 1, j), (i + 1, j + 1), (i - 1, j + 1), (i + 1, j - 1), (i, j + 1), (i, j - 1), (i - 1, j - 1)):\n if 0 <= r < m and 0 <= c < n and (board[r][c] == 1):\n ... | <|body_start_0|>
m, n = (len(board), len(board[0]))
die_to_live, live_to_die = ([], [])
def numOfLives(i, j):
lives_count = 0
for r, c in ((i + 1, j), (i - 1, j), (i + 1, j + 1), (i - 1, j + 1), (i + 1, j - 1), (i, j + 1), (i, j - 1), (i - 1, j - 1)):
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def gameOfLife_I(self, board) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def gameOfLife_II(self, board) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_007597 | 2,680 | no_license | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "gameOfLife_I",
"signature": "def gameOfLife_I(self, board) -> None"
},
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "gameOfLife_II",
"signature": "def gameOfLife_II(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gameOfLife_I(self, board) -> None: Do not return anything, modify board in-place instead.
- def gameOfLife_II(self, board) -> None: Do not return anything, modify board in-pl... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gameOfLife_I(self, board) -> None: Do not return anything, modify board in-place instead.
- def gameOfLife_II(self, board) -> None: Do not return anything, modify board in-pl... | 1461b10b8910fa90a311939c6df9082a8526f9b1 | <|skeleton|>
class Solution:
def gameOfLife_I(self, board) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def gameOfLife_II(self, board) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def gameOfLife_I(self, board) -> None:
"""Do not return anything, modify board in-place instead."""
m, n = (len(board), len(board[0]))
die_to_live, live_to_die = ([], [])
def numOfLives(i, j):
lives_count = 0
for r, c in ((i + 1, j), (i - 1, j... | the_stack_v2_python_sparse | Medium/289_gameOfLife.py | Yucheng7713/CodingPracticeByYuch | train | 0 | |
9ee2298062fb0153b54bfb6f616e084551999668 | [
"if root == None:\n return True\nelse:\n return self.judge(root.left, root.right)",
"if left == None and right != None:\n return False\nelif left != None and right == None:\n return False\nelif left == None and right == None:\n return True\nelif left.val != right.val:\n return False\nelse:\n ... | <|body_start_0|>
if root == None:
return True
else:
return self.judge(root.left, root.right)
<|end_body_0|>
<|body_start_1|>
if left == None and right != None:
return False
elif left != None and right == None:
return False
elif lef... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_symmetric_1(self, root: TreeNode) -> bool:
"""递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:"""
<|body_0|>
def judge(self, left, right):
"""递归法判断左右节点是否对称, 左节点的右孩子和右节点的左孩子是否相等 左节点的左孩子和右节点的右孩子是否想等 :param left: :param right: :return:"""
... | stack_v2_sparse_classes_10k_train_007598 | 3,606 | no_license | [
{
"docstring": "递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:",
"name": "is_symmetric_1",
"signature": "def is_symmetric_1(self, root: TreeNode) -> bool"
},
{
"docstring": "递归法判断左右节点是否对称, 左节点的右孩子和右节点的左孩子是否相等 左节点的左孩子和右节点的右孩子是否想等 :param left: :param right: :return:",
"name": "judge",
... | 3 | stack_v2_sparse_classes_30k_train_004027 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_symmetric_1(self, root: TreeNode) -> bool: 递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:
- def judge(self, left, right): 递归法判断左右节点是否对称, 左节点的右孩子和右节点的左孩子是否相等 左节点的左孩... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_symmetric_1(self, root: TreeNode) -> bool: 递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:
- def judge(self, left, right): 递归法判断左右节点是否对称, 左节点的右孩子和右节点的左孩子是否相等 左节点的左孩... | f68e60dd1d8bb010cdae88e6273b3fac4ea48776 | <|skeleton|>
class Solution:
def is_symmetric_1(self, root: TreeNode) -> bool:
"""递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:"""
<|body_0|>
def judge(self, left, right):
"""递归法判断左右节点是否对称, 左节点的右孩子和右节点的左孩子是否相等 左节点的左孩子和右节点的右孩子是否想等 :param left: :param right: :return:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def is_symmetric_1(self, root: TreeNode) -> bool:
"""递归法判断是不是镜像二叉树 分支法,看左子树和右子树是不是相等的 :param root: :return:"""
if root == None:
return True
else:
return self.judge(root.left, root.right)
def judge(self, left, right):
"""递归法判断左右节点是否对称, 左节点的... | the_stack_v2_python_sparse | tree/101_isSymmetric.py | liying123456/python_leetcode | train | 0 | |
c6f1d8f18f6bb58b8469fe31665ab3dc27218ea6 | [
"self.min = np.array([-10.0, 1.0])\nself.value = 0.0\nself.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])\nself.n = 2\nself.smooth = False\nself.info = [True, False, False]\nself.latex_name = 'Bukin Function No.6'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = 100\\\\sqrt{\\\\l... | <|body_start_0|>
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])
self.n = 2
self.smooth = False
self.info = [True, False, False]
self.latex_name = 'Bukin Function No.6'
self.latex_type = 'Many Local M... | Bukin No. 6 Function. | Bukin6 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.do... | stack_v2_sparse_classes_10k_train_007599 | 1,037 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006904 | Implement the Python class `Bukin6` described below.
Class description:
Bukin No. 6 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Bukin6` described below.
Class description:
Bukin No. 6 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])
self.n = 2
self.smooth = False
self.info = [True, False, False]
... | the_stack_v2_python_sparse | ctf/functions2d/bukin_6.py | cntaylor/ctf | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.