blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccbe77f60ae3df66e50284001bd2bcef0ba6a6d8 | [
"self.server = server\nself.modules = {}\nself.commands = {}\nself.events = {}\nself.module_handler = None",
"allmsgs = ['privmsg', 'privnotice', 'pubmsg', 'pubnotice']\nparsed_event = self.parse_event(event, connection)\nif event.type in allmsgs:\n self.message_handler(parsed_event)\ntry:\n for module, act... | <|body_start_0|>
self.server = server
self.modules = {}
self.commands = {}
self.events = {}
self.module_handler = None
<|end_body_0|>
<|body_start_1|>
allmsgs = ['privmsg', 'privnotice', 'pubmsg', 'pubnotice']
parsed_event = self.parse_event(event, connection)
... | Class to handle irc events. | EventHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventHandler:
"""Class to handle irc events."""
def __init__(self, server):
"""Constructor @param the irclib server object"""
<|body_0|>
def dispatcher(self, connection, event):
"""Dispatches an event to an event handler function. Taken from the irclib source."""... | stack_v2_sparse_classes_36k_train_029500 | 3,884 | permissive | [
{
"docstring": "Constructor @param the irclib server object",
"name": "__init__",
"signature": "def __init__(self, server)"
},
{
"docstring": "Dispatches an event to an event handler function. Taken from the irclib source.",
"name": "dispatcher",
"signature": "def dispatcher(self, connec... | 5 | stack_v2_sparse_classes_30k_train_011410 | Implement the Python class `EventHandler` described below.
Class description:
Class to handle irc events.
Method signatures and docstrings:
- def __init__(self, server): Constructor @param the irclib server object
- def dispatcher(self, connection, event): Dispatches an event to an event handler function. Taken from ... | Implement the Python class `EventHandler` described below.
Class description:
Class to handle irc events.
Method signatures and docstrings:
- def __init__(self, server): Constructor @param the irclib server object
- def dispatcher(self, connection, event): Dispatches an event to an event handler function. Taken from ... | a254459af73475dd321c5bd9188ac9d9e7bb667d | <|skeleton|>
class EventHandler:
"""Class to handle irc events."""
def __init__(self, server):
"""Constructor @param the irclib server object"""
<|body_0|>
def dispatcher(self, connection, event):
"""Dispatches an event to an event handler function. Taken from the irclib source."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventHandler:
"""Class to handle irc events."""
def __init__(self, server):
"""Constructor @param the irclib server object"""
self.server = server
self.modules = {}
self.commands = {}
self.events = {}
self.module_handler = None
def dispatcher(self, con... | the_stack_v2_python_sparse | piebot/handlers/eventhandler.py | klnusbaum/piebot | train | 0 |
1c4e2fd34033973c51d13e82d5ea3f5609ce3716 | [
"try:\n return ContactInformation.objects.get(pk=pk)\nexcept ContactInformation.DoesNotExist:\n raise Http404",
"contact_info = self.get_object(pk)\nserializer = ContactInformationSerializer(contact_info)\nreturn Response(serializer.data)",
"contact_info = self.get_object(pk)\nserializer = ContactInformat... | <|body_start_0|>
try:
return ContactInformation.objects.get(pk=pk)
except ContactInformation.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
contact_info = self.get_object(pk)
serializer = ContactInformationSerializer(contact_info)
return Resp... | Retrieve, update or delete a ContactInformation instance. | ContactInformationDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactInformationDetails:
"""Retrieve, update or delete a ContactInformation instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info content a... | stack_v2_sparse_classes_36k_train_029501 | 15,222 | permissive | [
{
"docstring": "Get the particular row from the table.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "We are going to add the contact info content along with this pull request",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_015712 | Implement the Python class `ContactInformationDetails` described below.
Class description:
Retrieve, update or delete a ContactInformation instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to add the c... | Implement the Python class `ContactInformationDetails` described below.
Class description:
Retrieve, update or delete a ContactInformation instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to add the c... | b0635e72338e14dad24f1ee0329212cd60a3e83a | <|skeleton|>
class ContactInformationDetails:
"""Retrieve, update or delete a ContactInformation instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info content a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactInformationDetails:
"""Retrieve, update or delete a ContactInformation instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
try:
return ContactInformation.objects.get(pk=pk)
except ContactInformation.DoesNotExist:
raise... | the_stack_v2_python_sparse | environment/views.py | faisaltheparttimecoder/carelogBackend | train | 1 |
35ce505d9abbc2926d4ea59da3b1b58ac65d3ac4 | [
"bin_path = '/home/cephuser/venv/bin/'\nself.prefix = bin_path + 's3cmd'\nif options is None:\n options = []\nself.operation = operation\nself.options = ' '.join(options)",
"if params is None:\n params = []\ncommand_list = [self.prefix, self.options, self.operation] + params\ncmd = list(filter(lambda cmd: l... | <|body_start_0|>
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
options = []
self.operation = operation
self.options = ' '.join(options)
<|end_body_0|>
<|body_start_1|>
if params is None:
params = []
... | S3CMD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_36k_train_029502 | 1,012 | permissive | [
{
"docstring": "Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command",
"name": "__init__",
"signature": "def __init__(self, operation, options=None)"
},
{
"docstring": "Args: params(list): list of params to be passed in ... | 2 | stack_v2_sparse_classes_30k_train_000569 | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | Implement the Python class `S3CMD` described below.
Class description:
Implement the S3CMD class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command
- def comm... | 4c3b9b3e8e7f42d43270a9b79299a8b404a76046 | <|skeleton|>
class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3CMD:
def __init__(self, operation, options=None):
"""Constructor for S3CMD class operation(str): S3CMD operation, E.g: ls, mb, etc... options(list): Optional options for the command"""
bin_path = '/home/cephuser/venv/bin/'
self.prefix = bin_path + 's3cmd'
if options is None:
... | the_stack_v2_python_sparse | rgw/v2/lib/s3cmd/resource_op.py | red-hat-storage/ceph-qe-scripts | train | 9 | |
0fdcae69d53dbf467230c741959afe9fb38de696 | [
"from metaci.build.models import BuildFlow\nDATE_FORMAT = '%Y-%m-%d'\nif start_string:\n start = datetime.datetime.strptime(start_string, DATE_FORMAT)\n start = start.replace(tzinfo=gettz()).date()\nelse:\n last_already_created = cls.objects.order_by('week_start').last()\n if last_already_created:\n ... | <|body_start_0|>
from metaci.build.models import BuildFlow
DATE_FORMAT = '%Y-%m-%d'
if start_string:
start = datetime.datetime.strptime(start_string, DATE_FORMAT)
start = start.replace(tzinfo=gettz()).date()
else:
last_already_created = cls.objects.ord... | Weekly summary table/model | TestResultPerfWeeklySummary | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestResultPerfWeeklySummary:
"""Weekly summary table/model"""
def _parse_start_and_date_dates(cls, start_string, end_string):
"""This code can be called from command lines, periodic jobs or other code. This function provides helpful default behaviours and date parsing to all of those... | stack_v2_sparse_classes_36k_train_029503 | 23,499 | permissive | [
{
"docstring": "This code can be called from command lines, periodic jobs or other code. This function provides helpful default behaviours and date parsing to all of those contexts.",
"name": "_parse_start_and_date_dates",
"signature": "def _parse_start_and_date_dates(cls, start_string, end_string)"
}... | 5 | null | Implement the Python class `TestResultPerfWeeklySummary` described below.
Class description:
Weekly summary table/model
Method signatures and docstrings:
- def _parse_start_and_date_dates(cls, start_string, end_string): This code can be called from command lines, periodic jobs or other code. This function provides he... | Implement the Python class `TestResultPerfWeeklySummary` described below.
Class description:
Weekly summary table/model
Method signatures and docstrings:
- def _parse_start_and_date_dates(cls, start_string, end_string): This code can be called from command lines, periodic jobs or other code. This function provides he... | 1e643462eb822b57648b391dc07ab4e8977726c8 | <|skeleton|>
class TestResultPerfWeeklySummary:
"""Weekly summary table/model"""
def _parse_start_and_date_dates(cls, start_string, end_string):
"""This code can be called from command lines, periodic jobs or other code. This function provides helpful default behaviours and date parsing to all of those... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestResultPerfWeeklySummary:
"""Weekly summary table/model"""
def _parse_start_and_date_dates(cls, start_string, end_string):
"""This code can be called from command lines, periodic jobs or other code. This function provides helpful default behaviours and date parsing to all of those contexts."""... | the_stack_v2_python_sparse | metaci/testresults/models.py | Digital-Innovations-Group/MetaCI | train | 0 |
d86b04f8b7f7686f3a3e2ab85d54fe858cd4e882 | [
"if not matrix or not matrix[0]:\n return 0\nres = 0\nfor i in range(len(matrix)):\n heights = []\n for j in range(len(matrix[0])):\n cur = 0\n for k in range(i, len(matrix)):\n if matrix[k][j] == '0':\n break\n cur += 1\n heights.append(cur)\n r... | <|body_start_0|>
if not matrix or not matrix[0]:
return 0
res = 0
for i in range(len(matrix)):
heights = []
for j in range(len(matrix[0])):
cur = 0
for k in range(i, len(matrix)):
if matrix[k][j] == '0':
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix o... | stack_v2_sparse_classes_36k_train_029504 | 1,659 | permissive | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class ... | 5097f69bb0050d963c784d6bc0e88a7e871568ed | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
if not matrix or not matrix[0]:
return 0
res = 0
for i in range(len(matrix)):
heights = []
for j in range(len(matrix[0])):
cur = 0
... | the_stack_v2_python_sparse | 51-100/85.py | yshshadow/Leetcode | train | 0 | |
9e3d3cfd491d98cc28042f02a8b7422c3819d7b6 | [
"business_schema = BusinessSchema()\nbusiness_data = request.get_json()\nvalidated_business_data, errors = business_schema.load(business_data)\nif errors:\n return (dict(status='fail', message=errors), 400)\nbusiness = Business(**validated_business_data)\nsaved_business = business.save()\nif not saved_business:\... | <|body_start_0|>
business_schema = BusinessSchema()
business_data = request.get_json()
validated_business_data, errors = business_schema.load(business_data)
if errors:
return (dict(status='fail', message=errors), 400)
business = Business(**validated_business_data)
... | BusinessView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessView:
def post(self):
"""Creating an Business ad"""
<|body_0|>
def get(self):
"""Getting All businesses"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
business_schema = BusinessSchema()
business_data = request.get_json()
val... | stack_v2_sparse_classes_36k_train_029505 | 3,207 | no_license | [
{
"docstring": "Creating an Business ad",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Getting All businesses",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003819 | Implement the Python class `BusinessView` described below.
Class description:
Implement the BusinessView class.
Method signatures and docstrings:
- def post(self): Creating an Business ad
- def get(self): Getting All businesses | Implement the Python class `BusinessView` described below.
Class description:
Implement the BusinessView class.
Method signatures and docstrings:
- def post(self): Creating an Business ad
- def get(self): Getting All businesses
<|skeleton|>
class BusinessView:
def post(self):
"""Creating an Business ad"... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class BusinessView:
def post(self):
"""Creating an Business ad"""
<|body_0|>
def get(self):
"""Getting All businesses"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessView:
def post(self):
"""Creating an Business ad"""
business_schema = BusinessSchema()
business_data = request.get_json()
validated_business_data, errors = business_schema.load(business_data)
if errors:
return (dict(status='fail', message=errors), 40... | the_stack_v2_python_sparse | app/controllers/business.py | MutegekiHenry/project-cohort-backend | train | 0 | |
e9af86f6c1091cc9e7270711bba8db7bc0151066 | [
"msg = '\\n\\nRunning SMA strategy | SMA1 = %d & SMA2 = %d' % (SMA1, SMA2)\nmsg += '\\nfixed costs %.2f | ' % self.ftc\nmsg += 'proportional costs %.4f' % self.ptc\nprint(msg)\nprint('=' * 55)\nself.position = 0\nself.amount = self._amount\nself.data['SMA1'] = self.data['price'].rolling(SMA1).mean()\nself.data['SMA... | <|body_start_0|>
msg = '\n\nRunning SMA strategy | SMA1 = %d & SMA2 = %d' % (SMA1, SMA2)
msg += '\nfixed costs %.2f | ' % self.ftc
msg += 'proportional costs %.4f' % self.ptc
print(msg)
print('=' * 55)
self.position = 0
self.amount = self._amount
self.data... | BacktestLongOnly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BacktestLongOnly:
def run_sma_strategy(self, SMA1, SMA2):
"""Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in days)"""
<|body_0|>
def run_momentum_strategy(self, momentum):
"""Backtesting a mome... | stack_v2_sparse_classes_36k_train_029506 | 4,494 | no_license | [
{
"docstring": "Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in days)",
"name": "run_sma_strategy",
"signature": "def run_sma_strategy(self, SMA1, SMA2)"
},
{
"docstring": "Backtesting a momentum-based strategy. Parameters... | 3 | stack_v2_sparse_classes_30k_train_002503 | Implement the Python class `BacktestLongOnly` described below.
Class description:
Implement the BacktestLongOnly class.
Method signatures and docstrings:
- def run_sma_strategy(self, SMA1, SMA2): Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in ... | Implement the Python class `BacktestLongOnly` described below.
Class description:
Implement the BacktestLongOnly class.
Method signatures and docstrings:
- def run_sma_strategy(self, SMA1, SMA2): Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in ... | bfc8baa153aec70caa8981b8e9215bb0be7f3163 | <|skeleton|>
class BacktestLongOnly:
def run_sma_strategy(self, SMA1, SMA2):
"""Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in days)"""
<|body_0|>
def run_momentum_strategy(self, momentum):
"""Backtesting a mome... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BacktestLongOnly:
def run_sma_strategy(self, SMA1, SMA2):
"""Backtesting a SMA-based strategy. Parameters ========== SMA1, SMA2: int shorter and longer term simple moving average (in days)"""
msg = '\n\nRunning SMA strategy | SMA1 = %d & SMA2 = %d' % (SMA1, SMA2)
msg += '\nfixed costs ... | the_stack_v2_python_sparse | code/pyquants/pyalgo/ch06/BacktestLongOnly.py | godknowspe/NoahsArk | train | 1 | |
2dc8e0fd62d0de356c9407fe172a4de37203eccf | [
"if isinstance(source, bytes):\n try:\n self.source = source.decode('utf-8')\n except UnicodeDecodeError as err:\n self.source = source.decode('latin-1')\nelse:\n self.source = source\nassert isinstance(self.source, unicode)",
"data = data.splitlines()\ntitle = []\nblock = []\nfor line in d... | <|body_start_0|>
if isinstance(source, bytes):
try:
self.source = source.decode('utf-8')
except UnicodeDecodeError as err:
self.source = source.decode('latin-1')
else:
self.source = source
assert isinstance(self.source, unicode)... | Parser for parsing OpenGL specifications for interesting information | Specification | [
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-newlib-historical",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Specification:
"""Parser for parsing OpenGL specifications for interesting information"""
def __init__(self, source):
"""Store the source text for the specification"""
<|body_0|>
def blocks(self, data):
"""Retrieve the set of all blocks"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_029507 | 22,465 | permissive | [
{
"docstring": "Store the source text for the specification",
"name": "__init__",
"signature": "def __init__(self, source)"
},
{
"docstring": "Retrieve the set of all blocks",
"name": "blocks",
"signature": "def blocks(self, data)"
},
{
"docstring": "Retrieve the set of constant ... | 4 | stack_v2_sparse_classes_30k_train_015089 | Implement the Python class `Specification` described below.
Class description:
Parser for parsing OpenGL specifications for interesting information
Method signatures and docstrings:
- def __init__(self, source): Store the source text for the specification
- def blocks(self, data): Retrieve the set of all blocks
- def... | Implement the Python class `Specification` described below.
Class description:
Parser for parsing OpenGL specifications for interesting information
Method signatures and docstrings:
- def __init__(self, source): Store the source text for the specification
- def blocks(self, data): Retrieve the set of all blocks
- def... | 29b79e8966ba2930a5c44829b02dffc1ca600752 | <|skeleton|>
class Specification:
"""Parser for parsing OpenGL specifications for interesting information"""
def __init__(self, source):
"""Store the source text for the specification"""
<|body_0|>
def blocks(self, data):
"""Retrieve the set of all blocks"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Specification:
"""Parser for parsing OpenGL specifications for interesting information"""
def __init__(self, source):
"""Store the source text for the specification"""
if isinstance(source, bytes):
try:
self.source = source.decode('utf-8')
except Un... | the_stack_v2_python_sparse | src/codegenerator.py | mcfletch/pyopengl | train | 276 |
b2c8849b114ffbfe4722b43a1884203fb935c767 | [
"self._num_classes = num_classes\nself._mask_target_size = mask_target_size\nself._num_convs = num_convs\nself._num_filters = num_filters\nif use_separable_conv:\n self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initializer=tf.zeros_initializer())\nelse:\n self._conv2d... | <|body_start_0|>
self._num_classes = num_classes
self._mask_target_size = mask_target_size
self._num_convs = num_convs
self._num_filters = num_filters
if use_separable_conv:
self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initi... | Mask R-CNN head. | MaskrcnnHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskrcnnHead:
"""Mask R-CNN head."""
def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_mask_pred=False):
... | stack_v2_sparse_classes_36k_train_029508 | 46,218 | permissive | [
{
"docstring": "Initialize params to build Fast R-CNN head. Args: num_classes: an integer for the number of classes. mask_target_size: an integer that is the resolution of masks. num_convs: `int` number that represents the number of the intermediate conv layers before the prediction. num_filters: `int` number t... | 2 | null | Implement the Python class `MaskrcnnHead` described below.
Class description:
Mask R-CNN head.
Method signatures and docstrings:
- def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormAct... | Implement the Python class `MaskrcnnHead` described below.
Class description:
Mask R-CNN head.
Method signatures and docstrings:
- def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormAct... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class MaskrcnnHead:
"""Mask R-CNN head."""
def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_mask_pred=False):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskrcnnHead:
"""Mask R-CNN head."""
def __init__(self, num_classes, mask_target_size, num_convs=4, num_filters=256, use_separable_conv=False, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_mask_pred=False):
"""Initializ... | the_stack_v2_python_sparse | models/official/detection/modeling/architecture/heads.py | tensorflow/tpu | train | 5,627 |
4f2487efd3bb2d56cb4e502bf08783ff5ef3f2a4 | [
"pre_head = ListNode(-1)\nprev = pre_head\nwhile l1 and l2:\n if l1.val <= l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\nprev.next = l1 if l1 is not None else l2\nreturn pre_head.next",
"if not l1:\n return l2\nif not l2... | <|body_start_0|>
pre_head = ListNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre_head = ListNode(-... | stack_v2_sparse_classes_36k_train_029509 | 2,635 | no_license | [
{
"docstring": "迭代",
"name": "merge_two_lists",
"signature": "def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "递归",
"name": "merge_two_lists_2",
"signature": "def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_003734 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 迭代
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 迭代
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归
<|skeleton|>
clas... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""迭代"""
pre_head = ListNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
... | the_stack_v2_python_sparse | 0021_merge-two-sorted-lists.py | Nigirimeshi/leetcode | train | 0 | |
ad348972f1000131c537436478b1d79b9c00950b | [
"self.num_filters = num_filters\nself._build_layer_components()\nsuper(ReductionB, self).__init__(**kwargs)",
"self.max_pool1 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid')\nself.conv_block1 = [Conv2D(self.num_filters, kernel_size=1, strides=1, padding='same', activation=tf.nn.relu)]\nself.conv_block1.... | <|body_start_0|>
self.num_filters = num_filters
self._build_layer_components()
super(ReductionB, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
self.max_pool1 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid')
self.conv_block1 = [Conv2D(self.num_filters, kernel_... | Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers. | ReductionB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReductionB:
"""Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."... | stack_v2_sparse_classes_36k_train_029510 | 17,354 | permissive | [
{
"docstring": "Parameters ---------- num_filters: int, Number of convolutional filters",
"name": "__init__",
"signature": "def __init__(self, num_filters, **kwargs)"
},
{
"docstring": "Builds the layers components and set _layers attribute.",
"name": "_build_layer_components",
"signatur... | 3 | null | Implement the Python class `ReductionB` described below.
Class description:
Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computati... | Implement the Python class `ReductionB` described below.
Class description:
Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computati... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class ReductionB:
"""Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReductionB:
"""Variant B of the two Reduction layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters, to reduce the spatial extent of the image and reduce computational complexity for downstream layers."""
def _... | the_stack_v2_python_sparse | deepchem/models/chemnet_layers.py | deepchem/deepchem | train | 4,876 |
87ef6ce3e9c468b4dadbb7bcf696f0c47d51f73e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessReviewNotificationRecipientQueryScope()",
"from .access_review_notification_recipient_scope import AccessReviewNotificationRecipientScope\nfrom .access_review_notification_recipient_scope import AccessReviewNotificationRecipientS... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessReviewNotificationRecipientQueryScope()
<|end_body_0|>
<|body_start_1|>
from .access_review_notification_recipient_scope import AccessReviewNotificationRecipientScope
from .access_... | AccessReviewNotificationRecipientQueryScope | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessReviewNotificationRecipientQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewNotificationRecipientQueryScope:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use t... | stack_v2_sparse_classes_36k_train_029511 | 3,167 | 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: AccessReviewNotificationRecipientQueryScope",
"name": "create_from_discriminator_value",
"signature": "def c... | 3 | null | Implement the Python class `AccessReviewNotificationRecipientQueryScope` described below.
Class description:
Implement the AccessReviewNotificationRecipientQueryScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewNotificationRecipie... | Implement the Python class `AccessReviewNotificationRecipientQueryScope` described below.
Class description:
Implement the AccessReviewNotificationRecipientQueryScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewNotificationRecipie... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessReviewNotificationRecipientQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewNotificationRecipientQueryScope:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessReviewNotificationRecipientQueryScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewNotificationRecipientQueryScope:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the dis... | the_stack_v2_python_sparse | msgraph/generated/models/access_review_notification_recipient_query_scope.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b47f32ffeef53ff13b2856ed4ed02651d05282e6 | [
"self._payment_dates = payment_dates\nself._payment_steps = payment_steps\nself._exercise_dates = exercise_dates\nself._exercise_steps = exercise_steps\nself._steps = int(exercise_steps[len(exercise_steps) - 1])\nself._frequency = frequency\nself._the_tree = {}",
"coupon_rates = np.ones_like(self._payment_steps) ... | <|body_start_0|>
self._payment_dates = payment_dates
self._payment_steps = payment_steps
self._exercise_dates = exercise_dates
self._exercise_steps = exercise_steps
self._steps = int(exercise_steps[len(exercise_steps) - 1])
self._frequency = frequency
self._the_tr... | Representation of a simple swaption product such as European or Bermudan Swaption | SimpleSwaption | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleSwaption:
"""Representation of a simple swaption product such as European or Bermudan Swaption"""
def __init__(self, payment_dates, payment_steps, exercise_dates, exercise_steps, frequency=2):
"""Initialize a SimpleSwaption object Parameters ---------- payment_dates : array_lik... | stack_v2_sparse_classes_36k_train_029512 | 11,731 | no_license | [
{
"docstring": "Initialize a SimpleSwaption object Parameters ---------- payment_dates : array_like of shape (M, ) with datetime payment dates payment_steps : array_like of shape (M, ) with integer payment steps that corresponds to the tree exercise_dates : array_like of shape (M, ) with datetime exercise dates... | 2 | stack_v2_sparse_classes_30k_test_000117 | Implement the Python class `SimpleSwaption` described below.
Class description:
Representation of a simple swaption product such as European or Bermudan Swaption
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps, exercise_dates, exercise_steps, frequency=2): Initialize a SimpleSwapti... | Implement the Python class `SimpleSwaption` described below.
Class description:
Representation of a simple swaption product such as European or Bermudan Swaption
Method signatures and docstrings:
- def __init__(self, payment_dates, payment_steps, exercise_dates, exercise_steps, frequency=2): Initialize a SimpleSwapti... | 9f710a8de56fb9b4456c6f98be91f4b22ef5ede5 | <|skeleton|>
class SimpleSwaption:
"""Representation of a simple swaption product such as European or Bermudan Swaption"""
def __init__(self, payment_dates, payment_steps, exercise_dates, exercise_steps, frequency=2):
"""Initialize a SimpleSwaption object Parameters ---------- payment_dates : array_lik... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleSwaption:
"""Representation of a simple swaption product such as European or Bermudan Swaption"""
def __init__(self, payment_dates, payment_steps, exercise_dates, exercise_steps, frequency=2):
"""Initialize a SimpleSwaption object Parameters ---------- payment_dates : array_like of shape (M... | the_stack_v2_python_sparse | Hull-White Model/simple_derivatives.py | jesusmramirez/Term-Structure-Models | train | 1 |
bf6d8918c1a7576fb03f77911844b99b85431d92 | [
"ObjectManager.__init__(self)\nself.getters.update({'name': 'get_general', 'forums': 'get_many_to_many'})\nself.setters.update({'name': 'set_general'})\nself.my_django_model = facade.models.ForumCategory\nself.setter = facade.subsystems.Setter",
"if optional_attributes is None:\n optional_attributes = dict()\n... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'name': 'get_general', 'forums': 'get_many_to_many'})
self.setters.update({'name': 'set_general'})
self.my_django_model = facade.models.ForumCategory
self.setter = facade.subsystems.Setter
<|end_body_0|>
<|body_s... | Manage Categorys in the Power Reg system | ForumCategoryManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForumCategoryManager:
"""Manage Categorys in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, optional_attributes=None):
"""Create a new Category @param name name of the Category @return a reference to th... | stack_v2_sparse_classes_36k_train_029513 | 1,342 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new Category @param name name of the Category @return a reference to the newly created Category",
"name": "create",
"signature": "def create(self, auth_token, name, optional_at... | 2 | stack_v2_sparse_classes_30k_train_018058 | Implement the Python class `ForumCategoryManager` described below.
Class description:
Manage Categorys in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, optional_attributes=None): Create a new Category @param name name of the Category @ret... | Implement the Python class `ForumCategoryManager` described below.
Class description:
Manage Categorys in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, optional_attributes=None): Create a new Category @param name name of the Category @ret... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class ForumCategoryManager:
"""Manage Categorys in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, optional_attributes=None):
"""Create a new Category @param name name of the Category @return a reference to th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForumCategoryManager:
"""Manage Categorys in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'name': 'get_general', 'forums': 'get_many_to_many'})
self.setters.update({'name': 'set_general'})
self.my_d... | the_stack_v2_python_sparse | forum/managers/category.py | ninemoreminutes/openassign-server | train | 0 |
f4faea1703ca807d89b302c4c802f51cd427e89a | [
"curr = head\ncache = set()\nwhile curr:\n cache.add(curr)\n curr = curr.next\n if curr in cache:\n return curr\nreturn None",
"fast = slow = head\nwhile fast and slow and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n ptr = head\n while ptr != sl... | <|body_start_0|>
curr = head
cache = set()
while curr:
cache.add(curr)
curr = curr.next
if curr in cache:
return curr
return None
<|end_body_0|>
<|body_start_1|>
fast = slow = head
while fast and slow and fast.next:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""set based"""
<|body_0|>
def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""two pointers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
curr ... | stack_v2_sparse_classes_36k_train_029514 | 2,648 | permissive | [
{
"docstring": "set based",
"name": "detectCycle",
"signature": "def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]"
},
{
"docstring": "two pointers",
"name": "detectCycle2",
"signature": "def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]"
}
] | 2 | stack_v2_sparse_classes_30k_test_000454 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: set based
- def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]: two pointers | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: set based
- def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]: two pointers
<|skeleto... | 8504db89a3f6a1596c0bb7343a4936884b44e6ea | <|skeleton|>
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""set based"""
<|body_0|>
def detectCycle2(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""two pointers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""set based"""
curr = head
cache = set()
while curr:
cache.add(curr)
curr = curr.next
if curr in cache:
return curr
return None
def... | the_stack_v2_python_sparse | array_linked_list/142.py | fimh/dsa-py | train | 2 | |
32f9d59b11d0474392c4eb5ce7ed8fa09a6c5f32 | [
"super().__init__(event, arg_string)\nself.bot = SlackHandler()\nself.ka = KarmaAssistant()",
"how_many = 5\nif self.arg_string:\n try:\n how_many = int(self.arg_string)\n except ValueError:\n self.bot.make_post(self.event, '{} is not a valid number.'.format(self.arg_string))\n return\n... | <|body_start_0|>
super().__init__(event, arg_string)
self.bot = SlackHandler()
self.ka = KarmaAssistant()
<|end_body_0|>
<|body_start_1|>
how_many = 5
if self.arg_string:
try:
how_many = int(self.arg_string)
except ValueError:
... | Post recently-created karma entries. | KarmaNewestPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KarmaNewestPlugin:
"""Post recently-created karma entries."""
def __init__(self, event, arg_string):
"""Config."""
<|body_0|>
def run(self):
"""Run the plugin."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(event, arg_string)
... | stack_v2_sparse_classes_36k_train_029515 | 11,809 | permissive | [
{
"docstring": "Config.",
"name": "__init__",
"signature": "def __init__(self, event, arg_string)"
},
{
"docstring": "Run the plugin.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017435 | Implement the Python class `KarmaNewestPlugin` described below.
Class description:
Post recently-created karma entries.
Method signatures and docstrings:
- def __init__(self, event, arg_string): Config.
- def run(self): Run the plugin. | Implement the Python class `KarmaNewestPlugin` described below.
Class description:
Post recently-created karma entries.
Method signatures and docstrings:
- def __init__(self, event, arg_string): Config.
- def run(self): Run the plugin.
<|skeleton|>
class KarmaNewestPlugin:
"""Post recently-created karma entries.... | 715c14d3a06d8a7a8771572371b67cc87c7e17fb | <|skeleton|>
class KarmaNewestPlugin:
"""Post recently-created karma entries."""
def __init__(self, event, arg_string):
"""Config."""
<|body_0|>
def run(self):
"""Run the plugin."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KarmaNewestPlugin:
"""Post recently-created karma entries."""
def __init__(self, event, arg_string):
"""Config."""
super().__init__(event, arg_string)
self.bot = SlackHandler()
self.ka = KarmaAssistant()
def run(self):
"""Run the plugin."""
how_many = ... | the_stack_v2_python_sparse | src/dungeonbot/plugins/karma.py | DungeonBot/dungeonbot | train | 0 |
16c58f3166cf8f5e6f19fe0d6fafcf27d3e534d0 | [
"for feature_arch in feature_nets.NAMES:\n sub_test = trySubTest(self, feature_arch=feature_arch)\n with sub_test:\n feature_fn = feature_nets.BY_NAME[feature_arch]\n with tf.Graph().as_default():\n image = tf.placeholder(tf.float32, (None, None, None, 32), name='image')\n ... | <|body_start_0|>
for feature_arch in feature_nets.NAMES:
sub_test = trySubTest(self, feature_arch=feature_arch)
with sub_test:
feature_fn = feature_nets.BY_NAME[feature_arch]
with tf.Graph().as_default():
image = tf.placeholder(tf.float... | TestFeatureNets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
<|body_0|>
def test_desired_output_size_from_receptive_field(self):
"""Uses the receptive field to get the input size for desired output size."""
<|b... | stack_v2_sparse_classes_36k_train_029516 | 7,655 | no_license | [
{
"docstring": "Instantiates the network with unknown spatial dimensions.",
"name": "test_unknown_size",
"signature": "def test_unknown_size(self)"
},
{
"docstring": "Uses the receptive field to get the input size for desired output size.",
"name": "test_desired_output_size_from_receptive_fi... | 5 | null | Implement the Python class `TestFeatureNets` described below.
Class description:
Implement the TestFeatureNets class.
Method signatures and docstrings:
- def test_unknown_size(self): Instantiates the network with unknown spatial dimensions.
- def test_desired_output_size_from_receptive_field(self): Uses the receptive... | Implement the Python class `TestFeatureNets` described below.
Class description:
Implement the TestFeatureNets class.
Method signatures and docstrings:
- def test_unknown_size(self): Instantiates the network with unknown spatial dimensions.
- def test_desired_output_size_from_receptive_field(self): Uses the receptive... | 6e0c70647aa58581ed749a79bfa75baca5754ac0 | <|skeleton|>
class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
<|body_0|>
def test_desired_output_size_from_receptive_field(self):
"""Uses the receptive field to get the input size for desired output size."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFeatureNets:
def test_unknown_size(self):
"""Instantiates the network with unknown spatial dimensions."""
for feature_arch in feature_nets.NAMES:
sub_test = trySubTest(self, feature_arch=feature_arch)
with sub_test:
feature_fn = feature_nets.BY_NAME[... | the_stack_v2_python_sparse | python/seqtrack/models/test_feature_nets.py | torrvision/seqtrack | train | 1 | |
b8af26faeb4444367f05b43d3ffe9fba193942e1 | [
"obj = context.object\nif obj is None:\n return False\nreturn all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT'])",
"scene = context.scene\npg = scene.pdt_pg\nobj = bpy.context.view_layer.objects.active\nif obj is None:\n self.report({'ERROR'}, PDT_ERR_NO_ACT_OBJ)\n return {'FINISHED'}\nif obj.mode ... | <|body_start_0|>
obj = context.object
if obj is None:
return False
return all([bool(obj), obj.type == 'MESH', obj.mode == 'EDIT'])
<|end_body_0|>
<|body_start_1|>
scene = context.scene
pg = scene.pdt_pg
obj = bpy.context.view_layer.objects.active
if o... | Set Pivot Point to Selected Geometry | PDT_OT_PivotSelected | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDT_OT_PivotSelected:
"""Set Pivot Point to Selected Geometry"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def execute(self, context):
"""Moves Pivot Point centroid of Selected Geo... | stack_v2_sparse_classes_36k_train_029517 | 13,734 | permissive | [
{
"docstring": "Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "Moves Pivot Point centroid of Selected Geometry. Note: Moves Pivot Point centroid of Selected Geometry in active scene us... | 2 | stack_v2_sparse_classes_30k_train_017224 | Implement the Python class `PDT_OT_PivotSelected` described below.
Class description:
Set Pivot Point to Selected Geometry
Method signatures and docstrings:
- def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.
- def execute(self, context): Moves Pivot Point cen... | Implement the Python class `PDT_OT_PivotSelected` described below.
Class description:
Set Pivot Point to Selected Geometry
Method signatures and docstrings:
- def poll(cls, context): Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing.
- def execute(self, context): Moves Pivot Point cen... | 4d5c304878c1e0018d97c1b07bcaa3981632265a | <|skeleton|>
class PDT_OT_PivotSelected:
"""Set Pivot Point to Selected Geometry"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def execute(self, context):
"""Moves Pivot Point centroid of Selected Geo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDT_OT_PivotSelected:
"""Set Pivot Point to Selected Geometry"""
def poll(cls, context):
"""Check Object Status. Args: context: Blender bpy.context instance. Returns: Nothing."""
obj = context.object
if obj is None:
return False
return all([bool(obj), obj.type ... | the_stack_v2_python_sparse | src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_pivot_point.py | RnoB/3DVisualSwarm | train | 0 |
356c6ffc4a888d2e3975fe89550e6a56433155f3 | [
"data = {}\nr_data = r\ndata['video_num'] = len(re.findall(REG_VIDEO_NUM, r_data))\ndata['pic_num'] = len(re.findall(REG_PIC_NUM, r_data))\ndata['comment_id'] = re.findall(REG_COMMENT_ID, r_data)\nif len(data['comment_id']) == 1:\n data['comment_id'] = data['comment_id'][0].split('\"')[1]\nelse:\n data['comme... | <|body_start_0|>
data = {}
r_data = r
data['video_num'] = len(re.findall(REG_VIDEO_NUM, r_data))
data['pic_num'] = len(re.findall(REG_PIC_NUM, r_data))
data['comment_id'] = re.findall(REG_COMMENT_ID, r_data)
if len(data['comment_id']) == 1:
data['comment_id'] ... | 解析文章内容 | DecodeArticle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodeArticle:
"""解析文章内容"""
def decode_content(r):
""":param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息"""
<|body_0|>
def part_of_html(raw_html, x_path='//div[@id="js_content"]'):
""":param x_path:xpat... | stack_v2_sparse_classes_36k_train_029518 | 4,659 | no_license | [
{
"docstring": ":param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息",
"name": "decode_content",
"signature": "def decode_content(r)"
},
{
"docstring": ":param x_path:xpath表达式默认获取微信公众号的正文xpath :param raw_html:r.text :return: 截取html的一部分",... | 2 | null | Implement the Python class `DecodeArticle` described below.
Class description:
解析文章内容
Method signatures and docstrings:
- def decode_content(r): :param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息
- def part_of_html(raw_html, x_path='//div[@id="js_content"]'... | Implement the Python class `DecodeArticle` described below.
Class description:
解析文章内容
Method signatures and docstrings:
- def decode_content(r): :param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息
- def part_of_html(raw_html, x_path='//div[@id="js_content"]'... | 6d2b4db3d34183d729f6fd30555c6d6f04514260 | <|skeleton|>
class DecodeArticle:
"""解析文章内容"""
def decode_content(r):
""":param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息"""
<|body_0|>
def part_of_html(raw_html, x_path='//div[@id="js_content"]'):
""":param x_path:xpat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecodeArticle:
"""解析文章内容"""
def decode_content(r):
""":param r:html字符串 :return:解析文章html 文章html中包含的信息非常丰富 不仅仅只有文章文本等基本数据还有comment_id video_num pic_num 还有原文的markdown信息"""
data = {}
r_data = r
data['video_num'] = len(re.findall(REG_VIDEO_NUM, r_data))
data['pic_num'] ... | the_stack_v2_python_sparse | weixin_crawler/project/crawler_assist/decode_response.py | cassieeric/python_crawler | train | 322 |
24ac6603657fae4fa2e157d1ffb24168d7bf5604 | [
"kwargs.setdefault('label_suffix', '')\nsuper(CaffeForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = u'Nazwa kawiarni'\nself.fields['city'].label = u'Miasto'\nself.fields['street'].label = u'Ulica'\nself.fields['postal_code'].label = u'Kod pocztowy'\nself.fields['building_number'].label = u'Numer b... | <|body_start_0|>
kwargs.setdefault('label_suffix', '')
super(CaffeForm, self).__init__(*args, **kwargs)
self.fields['name'].label = u'Nazwa kawiarni'
self.fields['city'].label = u'Miasto'
self.fields['street'].label = u'Ulica'
self.fields['postal_code'].label = u'Kod pocz... | Responsible for setting up a Caffe. | CaffeForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaffeForm:
"""Responsible for setting up a Caffe."""
def __init__(self, *args, **kwargs):
"""Initialize all Caffe's fields."""
<|body_0|>
def clean(self):
"""Clean data and check validation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kwargs... | stack_v2_sparse_classes_36k_train_029519 | 1,907 | permissive | [
{
"docstring": "Initialize all Caffe's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Clean data and check validation.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000909 | Implement the Python class `CaffeForm` described below.
Class description:
Responsible for setting up a Caffe.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Caffe's fields.
- def clean(self): Clean data and check validation. | Implement the Python class `CaffeForm` described below.
Class description:
Responsible for setting up a Caffe.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Caffe's fields.
- def clean(self): Clean data and check validation.
<|skeleton|>
class CaffeForm:
"""Responsible f... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CaffeForm:
"""Responsible for setting up a Caffe."""
def __init__(self, *args, **kwargs):
"""Initialize all Caffe's fields."""
<|body_0|>
def clean(self):
"""Clean data and check validation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaffeForm:
"""Responsible for setting up a Caffe."""
def __init__(self, *args, **kwargs):
"""Initialize all Caffe's fields."""
kwargs.setdefault('label_suffix', '')
super(CaffeForm, self).__init__(*args, **kwargs)
self.fields['name'].label = u'Nazwa kawiarni'
self.... | the_stack_v2_python_sparse | caffe/caffe/forms.py | VirrageS/io-kawiarnie | train | 3 |
143516f0c1cbe9e5d280822c102df747ff2b87f9 | [
"super().__init__(**kwargs)\nself.priority = NotifyProwl.template_args['priority']['default'] if not priority else next((v for k, v in PROWL_PRIORITY_MAP.items() if str(priority).lower().startswith(k)), NotifyProwl.template_args['priority']['default'])\nself.apikey = validate_regex(apikey, *self.template_tokens['ap... | <|body_start_0|>
super().__init__(**kwargs)
self.priority = NotifyProwl.template_args['priority']['default'] if not priority else next((v for k, v in PROWL_PRIORITY_MAP.items() if str(priority).lower().startswith(k)), NotifyProwl.template_args['priority']['default'])
self.apikey = validate_regex... | A wrapper for Prowl Notifications | NotifyProwl | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifyProwl:
"""A wrapper for Prowl Notifications"""
def __init__(self, apikey, providerkey=None, priority=None, **kwargs):
"""Initialize Prowl Object"""
<|body_0|>
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""Perform Prowl Notificati... | stack_v2_sparse_classes_36k_train_029520 | 9,987 | permissive | [
{
"docstring": "Initialize Prowl Object",
"name": "__init__",
"signature": "def __init__(self, apikey, providerkey=None, priority=None, **kwargs)"
},
{
"docstring": "Perform Prowl Notification",
"name": "send",
"signature": "def send(self, body, title='', notify_type=NotifyType.INFO, **k... | 4 | stack_v2_sparse_classes_30k_train_020100 | Implement the Python class `NotifyProwl` described below.
Class description:
A wrapper for Prowl Notifications
Method signatures and docstrings:
- def __init__(self, apikey, providerkey=None, priority=None, **kwargs): Initialize Prowl Object
- def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): Per... | Implement the Python class `NotifyProwl` described below.
Class description:
A wrapper for Prowl Notifications
Method signatures and docstrings:
- def __init__(self, apikey, providerkey=None, priority=None, **kwargs): Initialize Prowl Object
- def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): Per... | be3baed7e3d33bae973f1714df4ebbf65aa33f85 | <|skeleton|>
class NotifyProwl:
"""A wrapper for Prowl Notifications"""
def __init__(self, apikey, providerkey=None, priority=None, **kwargs):
"""Initialize Prowl Object"""
<|body_0|>
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""Perform Prowl Notificati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotifyProwl:
"""A wrapper for Prowl Notifications"""
def __init__(self, apikey, providerkey=None, priority=None, **kwargs):
"""Initialize Prowl Object"""
super().__init__(**kwargs)
self.priority = NotifyProwl.template_args['priority']['default'] if not priority else next((v for k,... | the_stack_v2_python_sparse | apprise/plugins/NotifyProwl.py | caronc/apprise | train | 8,426 |
f8c482af8bc577ffbcdf2cdf72ebfe9ad2c58f8e | [
"if not 0 < min_factor <= max_factor:\n raise ValueError('It must be `0 < min_factor <= max_factor`.')\nif not (isinstance(image_validator, ImageValidator) or image_validator is None):\n raise ValueError('`image_validator` must be either `None` or an `ImageValidator` object.')\nself.min_factor = min_factor\ns... | <|body_start_0|>
if not 0 < min_factor <= max_factor:
raise ValueError('It must be `0 < min_factor <= max_factor`.')
if not (isinstance(image_validator, ImageValidator) or image_validator is None):
raise ValueError('`image_validator` must be either `None` or an `ImageValidator` o... | Randomly scales images. | RandomScale | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomScale:
"""Randomly scales images."""
def __init__(self, min_factor=0.5, max_factor=1.5, prob=0.5, clip_boxes=True, box_filter=None, image_validator=None, n_trials_max=3, background=(0, 0, 0), labels_format=('class_id', 'xmin', 'ymin', 'xmax', 'ymax')):
"""Arguments: min_factor ... | stack_v2_sparse_classes_36k_train_029521 | 38,139 | permissive | [
{
"docstring": "Arguments: min_factor (float, optional): The minimum fraction of the image size by which to scale images. Must be positive. max_factor (float, optional): The maximum fraction of the image size by which to scale images. Must be positive. prob (float, optional): `(1 - prob)` determines the probabi... | 2 | stack_v2_sparse_classes_30k_train_018306 | Implement the Python class `RandomScale` described below.
Class description:
Randomly scales images.
Method signatures and docstrings:
- def __init__(self, min_factor=0.5, max_factor=1.5, prob=0.5, clip_boxes=True, box_filter=None, image_validator=None, n_trials_max=3, background=(0, 0, 0), labels_format=('class_id',... | Implement the Python class `RandomScale` described below.
Class description:
Randomly scales images.
Method signatures and docstrings:
- def __init__(self, min_factor=0.5, max_factor=1.5, prob=0.5, clip_boxes=True, box_filter=None, image_validator=None, n_trials_max=3, background=(0, 0, 0), labels_format=('class_id',... | 681e936b834b6a3786562ee8d22f7b07b409bd17 | <|skeleton|>
class RandomScale:
"""Randomly scales images."""
def __init__(self, min_factor=0.5, max_factor=1.5, prob=0.5, clip_boxes=True, box_filter=None, image_validator=None, n_trials_max=3, background=(0, 0, 0), labels_format=('class_id', 'xmin', 'ymin', 'xmax', 'ymax')):
"""Arguments: min_factor ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomScale:
"""Randomly scales images."""
def __init__(self, min_factor=0.5, max_factor=1.5, prob=0.5, clip_boxes=True, box_filter=None, image_validator=None, n_trials_max=3, background=(0, 0, 0), labels_format=('class_id', 'xmin', 'ymin', 'xmax', 'ymax')):
"""Arguments: min_factor (float, optio... | the_stack_v2_python_sparse | data_generator/object_detection_2d_geometric_ops.py | lylaaa/ssd_keras | train | 1 |
4f0181ec3b5332c3b2f8a7e49a65d1758685124b | [
"course_key = validate_course_key(course_key_str)\nat_time = datetime.now(timezone.utc)\nforce_on = request.GET.get('force_on')\nif not force_on and (not can_call_public_api(course_key)):\n raise PermissionDenied()\ntry:\n outline_user = self._determine_user(request, course_key)\n user_course_outline_detai... | <|body_start_0|>
course_key = validate_course_key(course_key_str)
at_time = datetime.now(timezone.utc)
force_on = request.GET.get('force_on')
if not force_on and (not can_call_public_api(course_key)):
raise PermissionDenied()
try:
outline_user = self._dete... | Display all CourseOutline information for a given user. | CourseOutlineView | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseOutlineView:
"""Display all CourseOutline information for a given user."""
def get(self, request, course_key_str, format=None):
"""The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar to imitate, see: https://github.com/edx/edx-platform/blo... | stack_v2_sparse_classes_36k_train_029522 | 11,389 | permissive | [
{
"docstring": "The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar to imitate, see: https://github.com/edx/edx-platform/blob/master/lms/djangoapps/program_enrollments/rest_api/v1/views.py#L792-L820",
"name": "get",
"signature": "def get(self, request, course_key_s... | 2 | null | Implement the Python class `CourseOutlineView` described below.
Class description:
Display all CourseOutline information for a given user.
Method signatures and docstrings:
- def get(self, request, course_key_str, format=None): The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar... | Implement the Python class `CourseOutlineView` described below.
Class description:
Display all CourseOutline information for a given user.
Method signatures and docstrings:
- def get(self, request, course_key_str, format=None): The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CourseOutlineView:
"""Display all CourseOutline information for a given user."""
def get(self, request, course_key_str, format=None):
"""The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar to imitate, see: https://github.com/edx/edx-platform/blo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseOutlineView:
"""Display all CourseOutline information for a given user."""
def get(self, request, course_key_str, format=None):
"""The CourseOutline, customized for a given user. TODO: Swagger docs of API. For an exemplar to imitate, see: https://github.com/edx/edx-platform/blob/master/lms/... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content/learning_sequences/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
b0fe876bfdc8ca0a4daf5eafbe3f783bc62a2b50 | [
"inputs = np.random.rand(2, input_size, input_size, 3)\ntf.keras.backend.set_image_data_format('channels_last')\nbackbone = backbones.ResNet(model_id=resnet_model_id, activation=activation)\nself.assertEqual(backbone.count_params(), 23561152)\nnum_classes = 1000\nmodel = classification_model.ClassificationModel(bac... | <|body_start_0|>
inputs = np.random.rand(2, input_size, input_size, 3)
tf.keras.backend.set_image_data_format('channels_last')
backbone = backbones.ResNet(model_id=resnet_model_id, activation=activation)
self.assertEqual(backbone.count_params(), 23561152)
num_classes = 1000
... | ClassificationNetworkTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationNetworkTest:
def test_resnet_network_creation(self, input_size, resnet_model_id, activation):
"""Test for creation of a ResNet-50 classifier."""
<|body_0|>
def test_revnet_network_creation(self):
"""Test for creation of a RevNet-56 classifier."""
... | stack_v2_sparse_classes_36k_train_029523 | 6,878 | permissive | [
{
"docstring": "Test for creation of a ResNet-50 classifier.",
"name": "test_resnet_network_creation",
"signature": "def test_resnet_network_creation(self, input_size, resnet_model_id, activation)"
},
{
"docstring": "Test for creation of a RevNet-56 classifier.",
"name": "test_revnet_network... | 6 | null | Implement the Python class `ClassificationNetworkTest` described below.
Class description:
Implement the ClassificationNetworkTest class.
Method signatures and docstrings:
- def test_resnet_network_creation(self, input_size, resnet_model_id, activation): Test for creation of a ResNet-50 classifier.
- def test_revnet_... | Implement the Python class `ClassificationNetworkTest` described below.
Class description:
Implement the ClassificationNetworkTest class.
Method signatures and docstrings:
- def test_resnet_network_creation(self, input_size, resnet_model_id, activation): Test for creation of a ResNet-50 classifier.
- def test_revnet_... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class ClassificationNetworkTest:
def test_resnet_network_creation(self, input_size, resnet_model_id, activation):
"""Test for creation of a ResNet-50 classifier."""
<|body_0|>
def test_revnet_network_creation(self):
"""Test for creation of a RevNet-56 classifier."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationNetworkTest:
def test_resnet_network_creation(self, input_size, resnet_model_id, activation):
"""Test for creation of a ResNet-50 classifier."""
inputs = np.random.rand(2, input_size, input_size, 3)
tf.keras.backend.set_image_data_format('channels_last')
backbone ... | the_stack_v2_python_sparse | models/official/vision/beta/modeling/classification_model_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
e8554fad1c7997a78c3e31e3a08ccda16f32c8e7 | [
"self.ground_filter_offset = config.ground_filter_offset\nself.offset_filter_distance = config.offset_filter_distance\nself.std_dev_multiplier = config.std_dev_multiplier\nself.kitti_utils = kitti_utils",
"slice_filter = self.kitti_utils.create_slice_filter(point_cloud, area_extents, ground_plane, self.ground_fil... | <|body_start_0|>
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_filter_distance
self.std_dev_multiplier = config.std_dev_multiplier
self.kitti_utils = kitti_utils
<|end_body_0|>
<|body_start_1|>
slice_filter = self.kitti_utils... | BevHeightPriors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_36k_train_029524 | 4,840 | no_license | [
{
"docstring": "BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object",
"name": "__init__",
"signature": "def __init__(self, config, kitti_utils)"
},
{
"docstring": "Generates the BEV maps dictionary. One height map is created f... | 2 | stack_v2_sparse_classes_30k_train_006174 | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | ac8256bd76fe4b81cfc48dc4c0b9d9dc92bc61c6 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_... | the_stack_v2_python_sparse | mlod/core/bev_generators/bev_height_priors.py | songsanling/MLOD | train | 0 | |
e19679697db0d431b119fbc05b965a283abb6204 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cxiao_jchew1', 'cxiao_jchew1')\nCR = repo['cxiao_jchew1.crime_reports'].find()\nFR = repo['cxiao_jchew1.firearm_recovery'].find()\ncrimeRate = []\nfor i in CR:\n try:\n crimeRate.append({'offen... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
CR = repo['cxiao_jchew1.crime_reports'].find()
FR = repo['cxiao_jchew1.firearm_recovery'].find()
crimeRate ... | mergeCrime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mergeCrime:
def execute(trial=False):
"""Merging data sets"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script will generat... | stack_v2_sparse_classes_36k_train_029525 | 4,600 | no_license | [
{
"docstring": "Merging data sets",
"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 document describing that invocation event.",
"name": "pr... | 2 | null | Implement the Python class `mergeCrime` described below.
Class description:
Implement the mergeCrime class.
Method signatures and docstrings:
- def execute(trial=False): Merging data sets
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document describing everythin... | Implement the Python class `mergeCrime` described below.
Class description:
Implement the mergeCrime class.
Method signatures and docstrings:
- def execute(trial=False): Merging data sets
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document describing everythin... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class mergeCrime:
def execute(trial=False):
"""Merging data sets"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script will generat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mergeCrime:
def execute(trial=False):
"""Merging data sets"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('cxiao_jchew1', 'cxiao_jchew1')
CR = repo['cxiao_jchew1.crime_reports'].find()
FR = ... | the_stack_v2_python_sparse | cxiao_jchew1/mergeCrime.py | lingyigu/course-2017-spr-proj | train | 0 | |
455912b33abc587b0bd4ea135ce2da724d12d645 | [
"n_x = int(np.sqrt(stations))\nn_y = int(stations / n_x)\ndx = station_separation\ndy = station_separation\nfor i in range(n_x):\n x = -dx * n_x / 2 + dx / 2 + dx * i\n for j in range(n_y):\n y = -dy * n_y / 2 + dy / 2 + dy * j\n self.subsets.append(station_type(x, y, **station_kwargs))",
"sta... | <|body_start_0|>
n_x = int(np.sqrt(stations))
n_y = int(stations / n_x)
dx = station_separation
dy = station_separation
for i in range(n_x):
x = -dx * n_x / 2 + dx / 2 + dx * i
for j in range(n_y):
y = -dy * n_y / 2 + dy / 2 + dy * j
... | Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class. | StationGrid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationGrid:
"""Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class."""
def set_positions(self, stations=1, station_separation=500, s... | stack_v2_sparse_classes_36k_train_029526 | 6,416 | permissive | [
{
"docstring": "Generates rectangular grid of stations.",
"name": "set_positions",
"signature": "def set_positions(self, stations=1, station_separation=500, station_type=IREXString, **station_kwargs)"
},
{
"docstring": "Test whether the number of hit stations meets the given station trigger requ... | 2 | stack_v2_sparse_classes_30k_train_007245 | Implement the Python class `StationGrid` described below.
Class description:
Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class.
Method signatures and docstri... | Implement the Python class `StationGrid` described below.
Class description:
Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class.
Method signatures and docstri... | 80798ec2c4fd2e27f40843e37013765ee6a4e551 | <|skeleton|>
class StationGrid:
"""Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class."""
def set_positions(self, stations=1, station_separation=500, s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StationGrid:
"""Rectangular grid of stations or strings, in a square layout if possible, separated by the given distance. Supports any station or string type and passes extra keyword arguments on to the station or string class."""
def set_positions(self, stations=1, station_separation=500, station_type=I... | the_stack_v2_python_sparse | pyrex/custom/irex/detector.py | shrishabh/pyrex | train | 0 |
f68040a1f5cbf7e0a85ceca508e3688b44c6d9e4 | [
"super(_QuantileGrid, self).__init__(num_bins)\nn = len(theta)\nindex = np.argsort(theta)\nself._index = index\nself._theta = theta\nself._sorted_theta = theta[index]\nbin_start = np.concatenate(([0], np.cumsum([n // num_bins] * (num_bins - n % num_bins) + [n // num_bins + 1] * (n % num_bins))))\nself._bin_start = ... | <|body_start_0|>
super(_QuantileGrid, self).__init__(num_bins)
n = len(theta)
index = np.argsort(theta)
self._index = index
self._theta = theta
self._sorted_theta = theta[index]
bin_start = np.concatenate(([0], np.cumsum([n // num_bins] * (num_bins - n % num_bins)... | An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of each person. bin: array<array<int>>, shape=(num_bins,) list of bins, each of which ... | _QuantileGrid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _QuantileGrid:
"""An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of each person. bin: array<array<int>>, shape... | stack_v2_sparse_classes_36k_train_029527 | 9,018 | no_license | [
{
"docstring": "Creates a quantile grid. Args: theta: array<int>, shape=(N,) person latent abilities along a particular dimension. num_bins: int, number of bins (quantile intervals).",
"name": "__init__",
"signature": "def __init__(self, theta: np.array, num_bins: int) -> None"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_016494 | Implement the Python class `_QuantileGrid` described below.
Class description:
An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of eac... | Implement the Python class `_QuantileGrid` described below.
Class description:
An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of eac... | 0fd8e0058b981a8540c5fe2076eb8c3bcb3a39a3 | <|skeleton|>
class _QuantileGrid:
"""An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of each person. bin: array<array<int>>, shape... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _QuantileGrid:
"""An adaptive grid of quantile bins of N theta values in one dimension (sub-scale). By definition, all bins have the same size. Attributes: num_bins: int, number of bins (quantile intervals). bin_index: array<int>, shape=(N,) bin index of each person. bin: array<array<int>>, shape=(num_bins,) ... | the_stack_v2_python_sparse | nirt/grid.py | ETS-Next-Gen/irt-mcmc | train | 0 |
0309c140249b6c506b66f4fb3960977397f36597 | [
"for i in range(len(nums)):\n start = i\n if nums[i] == 0:\n continue\n positive = nums[start] > 0\n if nums[start] % len(nums) == 0:\n continue\n i_next = (i + nums[start]) % len(nums)\n while nums[i_next] % len(nums) != 0:\n if positive != (nums[i_next] > 0):\n br... | <|body_start_0|>
for i in range(len(nums)):
start = i
if nums[i] == 0:
continue
positive = nums[start] > 0
if nums[start] % len(nums) == 0:
continue
i_next = (i + nums[start]) % len(nums)
while nums[i_next] %... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def circularArrayLoop(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def circularArrayLoop2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(len(nums)):
... | stack_v2_sparse_classes_36k_train_029528 | 2,818 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "circularArrayLoop",
"signature": "def circularArrayLoop(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "circularArrayLoop2",
"signature": "def circularArrayLoop2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005064 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def circularArrayLoop(self, nums): :type nums: List[int] :rtype: bool
- def circularArrayLoop2(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def circularArrayLoop(self, nums): :type nums: List[int] :rtype: bool
- def circularArrayLoop2(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def circularArrayLoop(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def circularArrayLoop2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def circularArrayLoop(self, nums):
""":type nums: List[int] :rtype: bool"""
for i in range(len(nums)):
start = i
if nums[i] == 0:
continue
positive = nums[start] > 0
if nums[start] % len(nums) == 0:
conti... | the_stack_v2_python_sparse | code457CircularArrayLoop.py | cybelewang/leetcode-python | train | 0 | |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(Encoder, self).__init__()\nK = sampling_rate // 8000\nself.spectrogram = Spectrogram(n_fft=1024 * K, hop=256 * K, mels=num_mels, sr=sampling_rate)\nself.filters = nn.ModuleList([])\nfilter_width = num_mels\nfor l in range(layers):\n n = N // 4\n k = kernel_size * 2 ** l\n self.filters.append(nn.Conv... | <|body_start_0|>
super(Encoder, self).__init__()
K = sampling_rate // 8000
self.spectrogram = Spectrogram(n_fft=1024 * K, hop=256 * K, mels=num_mels, sr=sampling_rate)
self.filters = nn.ModuleList([])
filter_width = num_mels
for l in range(layers):
n = N // 4
... | Encodes the waveforms into the latent representation | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encodes the waveforms into the latent representation"""
def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate):
"""Arguments: N {int} -- Dimension of the output latent representation kernel_size {int} -- Base convolutional kernel size stride {int} -- ... | stack_v2_sparse_classes_36k_train_029529 | 37,269 | no_license | [
{
"docstring": "Arguments: N {int} -- Dimension of the output latent representation kernel_size {int} -- Base convolutional kernel size stride {int} -- Stride of the convolutions layers {int} -- Number of parallel convolutions with different kernel sizes num_mels {int} -- Number of mel filters in the mel spectr... | 2 | stack_v2_sparse_classes_30k_train_007139 | Implement the Python class `Encoder` described below.
Class description:
Encodes the waveforms into the latent representation
Method signatures and docstrings:
- def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate): Arguments: N {int} -- Dimension of the output latent representation kernel_size... | Implement the Python class `Encoder` described below.
Class description:
Encodes the waveforms into the latent representation
Method signatures and docstrings:
- def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate): Arguments: N {int} -- Dimension of the output latent representation kernel_size... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Encoder:
"""Encodes the waveforms into the latent representation"""
def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate):
"""Arguments: N {int} -- Dimension of the output latent representation kernel_size {int} -- Base convolutional kernel size stride {int} -- ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encodes the waveforms into the latent representation"""
def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate):
"""Arguments: N {int} -- Dimension of the output latent representation kernel_size {int} -- Base convolutional kernel size stride {int} -- Stride of the... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
26785751065b87146ccd135f98b0c68a1ef80a91 | [
"url = '/api/v1.2/graph-connections/%d/async-tasks' % graph_id\ncode, res = Request().request(method='get', path=url, params=param, types='hubble')\nreturn (code, res)",
"url = '/api/v1.2/graph-connections/%d/async-tasks/%d' % (graph_id, async_task_id)\ncode, res = Request().request(method='get', path=url, types=... | <|body_start_0|>
url = '/api/v1.2/graph-connections/%d/async-tasks' % graph_id
code, res = Request().request(method='get', path=url, params=param, types='hubble')
return (code, res)
<|end_body_0|>
<|body_start_1|>
url = '/api/v1.2/graph-connections/%d/async-tasks/%d' % (graph_id, async_... | 查看任务结果 | Task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Task:
"""查看任务结果"""
def view_async_tasks_all(graph_id, param=None, auth=None):
"""查看所有异步任务 :param param: :param auth: :param graph_id: :return:"""
<|body_0|>
def view_async_tasks_results(graph_id, async_task_id, auth=None):
"""查看异步任务结果 :param auth: :param async_ta... | stack_v2_sparse_classes_36k_train_029530 | 26,078 | no_license | [
{
"docstring": "查看所有异步任务 :param param: :param auth: :param graph_id: :return:",
"name": "view_async_tasks_all",
"signature": "def view_async_tasks_all(graph_id, param=None, auth=None)"
},
{
"docstring": "查看异步任务结果 :param auth: :param async_task_id: :param graph_id: :return:",
"name": "view_as... | 2 | stack_v2_sparse_classes_30k_train_003356 | Implement the Python class `Task` described below.
Class description:
查看任务结果
Method signatures and docstrings:
- def view_async_tasks_all(graph_id, param=None, auth=None): 查看所有异步任务 :param param: :param auth: :param graph_id: :return:
- def view_async_tasks_results(graph_id, async_task_id, auth=None): 查看异步任务结果 :param ... | Implement the Python class `Task` described below.
Class description:
查看任务结果
Method signatures and docstrings:
- def view_async_tasks_all(graph_id, param=None, auth=None): 查看所有异步任务 :param param: :param auth: :param graph_id: :return:
- def view_async_tasks_results(graph_id, async_task_id, auth=None): 查看异步任务结果 :param ... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Task:
"""查看任务结果"""
def view_async_tasks_all(graph_id, param=None, auth=None):
"""查看所有异步任务 :param param: :param auth: :param graph_id: :return:"""
<|body_0|>
def view_async_tasks_results(graph_id, async_task_id, auth=None):
"""查看异步任务结果 :param auth: :param async_ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Task:
"""查看任务结果"""
def view_async_tasks_all(graph_id, param=None, auth=None):
"""查看所有异步任务 :param param: :param auth: :param graph_id: :return:"""
url = '/api/v1.2/graph-connections/%d/async-tasks' % graph_id
code, res = Request().request(method='get', path=url, params=param, types... | the_stack_v2_python_sparse | src/common/hubble_api.py | hugegraph/hugegraph-test | train | 1 |
fe7db0c87f6dc5a5471c1f07560a9fb0da7b0ea6 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('xcao19', 'xcao19')\nurl = 'https://data.boston.gov/dataset/52b0fdad-4037-460c-9c92-290f5774ab2b/resource/c2fcc1e3-c38f-44ad-a0cf-e5ea2a6585b5/download/streetlight-locations.csv'\ndf = pd.read_csv(url, en... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'https://data.boston.gov/dataset/52b0fdad-4037-460c-9c92-290f5774ab2b/resource/c2fcc1e3-c38f-44ad-a0cf-e5ea2a6585b5/download/stre... | streetlights | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class streetlights:
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_36k_train_029531 | 3,325 | 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_005342 | Implement the Python class `streetlights` described below.
Class description:
Implement the streetlights 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 `streetlights` described below.
Class description:
Implement the streetlights 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... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class streetlights:
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_36k | data/stack_v2_sparse_classes_30k | class streetlights:
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('xcao19', 'xcao19')
url = 'http... | the_stack_v2_python_sparse | xcao19/streetlights.py | maximega/course-2019-spr-proj | train | 2 | |
193061a196cd5d41c25f445d48cdfd41fb64a585 | [
"result = 0\nheights = []\nfor row in matrix:\n if not heights:\n heights = [int(num) for num in row]\n else:\n heights = [heights[i] + 1 if int(num) else 0 for i, num in enumerate(row)]\n result = max(result, self.largestRectangleArea(heights))\nreturn result",
"stack = []\nresult = 0\nhei... | <|body_start_0|>
result = 0
heights = []
for row in matrix:
if not heights:
heights = [int(num) for num in row]
else:
heights = [heights[i] + 1 if int(num) else 0 for i, num in enumerate(row)]
result = max(result, self.largestRe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 0
... | stack_v2_sparse_classes_36k_train_029532 | 1,056 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011151 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class ... | e223ca0ba7b3d095e456cc43b0d90a868f63e53b | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
result = 0
heights = []
for row in matrix:
if not heights:
heights = [int(num) for num in row]
else:
heights = [heights[i] + 1 i... | the_stack_v2_python_sparse | 85_maximal-rectangle.py | rabbitzbx/LeetCode-solutions | train | 1 | |
e5cbbb808d80236dbc35501ed585e854891895fd | [
"if self.list_endpoint_attr is None:\n raise ValueError('AllMixin requires `list_endpoint_attr` to be set')\nif not hasattr(self, self.list_endpoint_attr):\n raise ValueError('%s does not have the required list attribute `%s`' % (self.__class__, self.list_endpoint_attr))\nreturn getattr(self, self.list_endpoi... | <|body_start_0|>
if self.list_endpoint_attr is None:
raise ValueError('AllMixin requires `list_endpoint_attr` to be set')
if not hasattr(self, self.list_endpoint_attr):
raise ValueError('%s does not have the required list attribute `%s`' % (self.__class__, self.list_endpoint_attr... | Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number | AllMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllMixin:
"""Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number"""
def get_list_endpoint(self) -> Callable... | stack_v2_sparse_classes_36k_train_029533 | 2,617 | permissive | [
{
"docstring": "Method for getting the callable API's endpoint that is responsible for returning paged results :return: Callable API's list endpoint method.",
"name": "get_list_endpoint",
"signature": "def get_list_endpoint(self) -> Callable"
},
{
"docstring": "Method for going through all the p... | 2 | stack_v2_sparse_classes_30k_train_013500 | Implement the Python class `AllMixin` described below.
Class description:
Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number
Method ... | Implement the Python class `AllMixin` described below.
Class description:
Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number
Method ... | 168f2e9459020212213ed0291882a285ebb53839 | <|skeleton|>
class AllMixin:
"""Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number"""
def get_list_endpoint(self) -> Callable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllMixin:
"""Mixin for API endpoint classes to have an all() method for returning objects from all pages. :attr list_endpoint_attr: API endpoint's method for returning paged results :attr evr_page_param: Argument name that determines the page number"""
def get_list_endpoint(self) -> Callable:
"""... | the_stack_v2_python_sparse | pyevr/apis.py | thorgate/pyevr | train | 3 |
36c0812e15b950c2db9d11533e70345292929f8a | [
"self.function = function\nself.use_threads = use_threads\nself.synchronous = synchronous\nself._result = None\nif self.use_threads:\n self._event_start = threading.Event()\n self._event_finish = threading.Event()\n self._event_finish.set()\n self._thread = threading.Thread(target=self._worker_function,... | <|body_start_0|>
self.function = function
self.use_threads = use_threads
self.synchronous = synchronous
self._result = None
if self.use_threads:
self._event_start = threading.Event()
self._event_finish = threading.Event()
self._event_finish.set... | class that launches a worker thread as a daemon that applies a given function | WorkerThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkerThread:
"""class that launches a worker thread as a daemon that applies a given function"""
def __init__(self, function, use_threads=True, synchronous=True):
"""initializes the worker thread with the supplied function that will be called subsequently. `synchronous` is a flag de... | stack_v2_sparse_classes_36k_train_029534 | 7,625 | permissive | [
{
"docstring": "initializes the worker thread with the supplied function that will be called subsequently. `synchronous` is a flag determining whether the result from the worker thread will be synchronized with the input. If it is not, it can be that a call to `get` returns the result from a previous worker thr... | 4 | null | Implement the Python class `WorkerThread` described below.
Class description:
class that launches a worker thread as a daemon that applies a given function
Method signatures and docstrings:
- def __init__(self, function, use_threads=True, synchronous=True): initializes the worker thread with the supplied function tha... | Implement the Python class `WorkerThread` described below.
Class description:
class that launches a worker thread as a daemon that applies a given function
Method signatures and docstrings:
- def __init__(self, function, use_threads=True, synchronous=True): initializes the worker thread with the supplied function tha... | 2afae32df4fe9609c792a3b608cad79833f4178f | <|skeleton|>
class WorkerThread:
"""class that launches a worker thread as a daemon that applies a given function"""
def __init__(self, function, use_threads=True, synchronous=True):
"""initializes the worker thread with the supplied function that will be called subsequently. `synchronous` is a flag de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkerThread:
"""class that launches a worker thread as a daemon that applies a given function"""
def __init__(self, function, use_threads=True, synchronous=True):
"""initializes the worker thread with the supplied function that will be called subsequently. `synchronous` is a flag determining whe... | the_stack_v2_python_sparse | utils/concurrency.py | david-zwicker/py-utils | train | 0 |
b26d4d62529c117c735be73b8f1dd51803015f18 | [
"self.arr = arr\nself.a2i = collections.defaultdict(list)\nfor i, x in enumerate(arr):\n self.a2i[x].append(i)",
"for i in xrange(10):\n major = self.arr[random.randint(left, right)]\n l = bisect.bisect_left(self.a2i[major], left)\n r = bisect.bisect_right(self.a2i[major], right)\n if r - l >= thre... | <|body_start_0|>
self.arr = arr
self.a2i = collections.defaultdict(list)
for i, x in enumerate(arr):
self.a2i[x].append(i)
<|end_body_0|>
<|body_start_1|>
for i in xrange(10):
major = self.arr[random.randint(left, right)]
l = bisect.bisect_left(self.a... | MajorityChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.arr = ... | stack_v2_sparse_classes_36k_train_029535 | 1,008 | no_license | [
{
"docstring": ":type arr: List[int]",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": ":type left: int :type right: int :type threshold: int :rtype: int",
"name": "query",
"signature": "def query(self, left, right, threshold)"
}
] | 2 | null | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int
<|skelet... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
self.arr = arr
self.a2i = collections.defaultdict(list)
for i, x in enumerate(arr):
self.a2i[x].append(i)
def query(self, left, right, threshold):
""":type left: int :type right: int :... | the_stack_v2_python_sparse | _1157_Online_Majority_Element_In_Subarray.py | mingweihe/leetcode | train | 3 | |
e3ff90a71a15710d4608bdf47b9176c96da7b30a | [
"address = None\nfor impl in ExternalAddress.implementations:\n if impl == Hostname:\n continue\n obj = impl(False, 5)\n if address is None:\n address = obj.lookup_external_address()\n else:\n lookup = obj.lookup_external_address()\n self.assertEqual(address, lookup, \"invali... | <|body_start_0|>
address = None
for impl in ExternalAddress.implementations:
if impl == Hostname:
continue
obj = impl(False, 5)
if address is None:
address = obj.lookup_external_address()
else:
lookup = obj.l... | Run tests against external address functionality. | TestExternalAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExternalAddress:
"""Run tests against external address functionality."""
def test_implementations(self):
"""Test lookup implementations. They should all work within five seconds and return the same external IP."""
<|body_0|>
def test_benchmark(self):
"""Verif... | stack_v2_sparse_classes_36k_train_029536 | 7,283 | no_license | [
{
"docstring": "Test lookup implementations. They should all work within five seconds and return the same external IP.",
"name": "test_implementations",
"signature": "def test_implementations(self)"
},
{
"docstring": "Verify that the implemenatations have been added in order of response time.",
... | 4 | stack_v2_sparse_classes_30k_train_012222 | Implement the Python class `TestExternalAddress` described below.
Class description:
Run tests against external address functionality.
Method signatures and docstrings:
- def test_implementations(self): Test lookup implementations. They should all work within five seconds and return the same external IP.
- def test_b... | Implement the Python class `TestExternalAddress` described below.
Class description:
Run tests against external address functionality.
Method signatures and docstrings:
- def test_implementations(self): Test lookup implementations. They should all work within five seconds and return the same external IP.
- def test_b... | 112c0459626a5e74367ff9fc512c04ea2226ea89 | <|skeleton|>
class TestExternalAddress:
"""Run tests against external address functionality."""
def test_implementations(self):
"""Test lookup implementations. They should all work within five seconds and return the same external IP."""
<|body_0|>
def test_benchmark(self):
"""Verif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestExternalAddress:
"""Run tests against external address functionality."""
def test_implementations(self):
"""Test lookup implementations. They should all work within five seconds and return the same external IP."""
address = None
for impl in ExternalAddress.implementations:
... | the_stack_v2_python_sparse | src/sittercommon/address.py | ZachGoldberg/Cerebro | train | 4 |
046d76758e1b005faef5dcfa3d772c11ab50a958 | [
"if not start_end_points:\n detail = \"Can't create a graph with the empty start line.\"\n raise TableLineEmptyException(detail)\nif columns_width:\n assert len(columns_width) == column_count, 'Columns count and list with they widths must be the same length.'\nself.horizontal_line = [ShapePoint(start_end_p... | <|body_start_0|>
if not start_end_points:
detail = "Can't create a graph with the empty start line."
raise TableLineEmptyException(detail)
if columns_width:
assert len(columns_width) == column_count, 'Columns count and list with they widths must be the same length.'
... | Table class. Built from Lines | Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table class. Built from Lines"""
def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.2, column_count: int=0, visible_row_count: int=0, columns_width: tuple=None, lines_color: Color=BLACK, stroke_width: Union[int, float]=1, *ar... | stack_v2_sparse_classes_36k_train_029537 | 9,066 | no_license | [
{
"docstring": "Class initialization. Args: start_end_points (Tuple[tuple, tuple]): Left top and right top points. ((x1,y1), (x2,y2)). row_count (int, optional): Table row count. Defaults to 0. row_height (Union[int, float], optional): Table row height. Defaults to 0.2. column_count (int, optional): Table colum... | 2 | stack_v2_sparse_classes_30k_train_009221 | Implement the Python class `Table` described below.
Class description:
Table class. Built from Lines
Method signatures and docstrings:
- def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.2, column_count: int=0, visible_row_count: int=0, columns_width: tuple=No... | Implement the Python class `Table` described below.
Class description:
Table class. Built from Lines
Method signatures and docstrings:
- def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.2, column_count: int=0, visible_row_count: int=0, columns_width: tuple=No... | 290bf56ef888283a0225939ed8b1f87445e506d0 | <|skeleton|>
class Table:
"""Table class. Built from Lines"""
def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.2, column_count: int=0, visible_row_count: int=0, columns_width: tuple=None, lines_color: Color=BLACK, stroke_width: Union[int, float]=1, *ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""Table class. Built from Lines"""
def __init__(self, start_end_points: Tuple[tuple, tuple], row_count: int=0, row_height: Union[int, float]=0.2, column_count: int=0, visible_row_count: int=0, columns_width: tuple=None, lines_color: Color=BLACK, stroke_width: Union[int, float]=1, *args, **kwargs)... | the_stack_v2_python_sparse | classes/table.py | mohovkm/habr_manim | train | 0 |
a23cd4d90338cf67c3466c238547fd7b09d858c1 | [
"self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)\nself.ax = self.fig.add_subplot(111)\nFigureCanvasQTAgg.__init__(self, self.fig)\nFigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\nFigureCanvasQTAgg.updateGeometry(self)\nself.setParent(parent)\nself.plot()",
"sel... | <|body_start_0|>
self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)
self.ax = self.fig.add_subplot(111)
FigureCanvasQTAgg.__init__(self, self.fig)
FigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvasQTAgg.updateGeometry(sel... | The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Axes of the TimeStack figure. | TSCanvas | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSCanvas:
"""The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Axes of the TimeStack figure."""
def... | stack_v2_sparse_classes_36k_train_029538 | 22,292 | permissive | [
{
"docstring": "Initialization of the Time-Stack canvas. It makes a bridge between Matplotlib and the window, creates the figure to display and then show a part of the TimeStack. Args: parent (QWidget): Parent of the canvas (default: None). width (int): Width of the canvas (default: 800). height (int): Height o... | 2 | stack_v2_sparse_classes_30k_train_016979 | Implement the Python class `TSCanvas` described below.
Class description:
The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Ax... | Implement the Python class `TSCanvas` described below.
Class description:
The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Ax... | 0b39cd5e499f6168f10906d29ef826ab9aaa45c4 | <|skeleton|>
class TSCanvas:
"""The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Axes of the TimeStack figure."""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TSCanvas:
"""The TimeStack canvas (only a part of the Hovmöller diagram). The canvas is static and the size of the image is adapted to show n_ts lines of the diagram. Attributes: fig (matplotlib.figure.Figure): TimeStack figure. ax (matplotlib.axes.Axes): Axes of the TimeStack figure."""
def __init__(sel... | the_stack_v2_python_sparse | src/graphics/ApplicationWindow.py | GregoireThoumyre/Bathymetry-Inversion | train | 1 |
3232b3ee62cd5600d1a8b7ddb4e81a415b91930e | [
"self.max_madays = max_mean_days\nif trange.is_inf:\n self.trange = self.trange_ensure_not_inf(days_collected, trange, tzinfo)\n self.trange.set_start_day_offset(-max_mean_days)\nelse:\n self.trange = trange\nself.dates = self.date_list(days_collected, tzinfo, start=self.trange.start, end=self.trange.end)\... | <|body_start_0|>
self.max_madays = max_mean_days
if trange.is_inf:
self.trange = self.trange_ensure_not_inf(days_collected, trange, tzinfo)
self.trange.set_start_day_offset(-max_mean_days)
else:
self.trange = trange
self.dates = self.date_list(days_col... | Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Generated result by calling ``generate_result()``. Check ... | MeanMessageResultGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Gen... | stack_v2_sparse_classes_36k_train_029539 | 25,000 | permissive | [
{
"docstring": "Initializing method of :class:`MeanMessageResultGenerator`. :param cursor: cursor of the aggregated data :param days_collected: \"claimed\" days collected on the data :param tzinfo: timezone info to separate the data by their date :param trange: time range of the data :param max_mean_days: maxim... | 2 | stack_v2_sparse_classes_30k_train_004487 | Implement the Python class `MeanMessageResultGenerator` described below.
Class description:
Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-c... | Implement the Python class `MeanMessageResultGenerator` described below.
Class description:
Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-c... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Gen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeanMessageResultGenerator:
"""Result object for mean days message count. -------- **Sample data** Assume that the messages were sent as follows, and ``max_mean_days`` are set to ``5``: - Day 1: 10 - Day 2: 20 ... - Day 5: 50 ... - Day 9: 90 -------- **Sub-classes** :class:`MeanMessageResult` Generated result... | the_stack_v2_python_sparse | models/stats/msg.py | RxJellyBot/Jelly-Bot | train | 5 |
779f18702309bfdc9981b58850807a5c9594af85 | [
"if 'pix' in string_rep:\n return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)\nif 'h' in string_rep or 'rad' in string_rep:\n return coordinates.Angle(string_rep)\nif len(string_rep.split('.')) >= 3:\n string_rep = string_rep.replace('.', ':', 2)\nreturn coordinates.Angle(string_rep, u.deg)",
"... | <|body_start_0|>
if 'pix' in string_rep:
return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)
if 'h' in string_rep or 'rad' in string_rep:
return coordinates.Angle(string_rep)
if len(string_rep.split('.')) >= 3:
string_rep = string_rep.replace('.', ':'... | Helper class to structure coordinate parser | CoordinateParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoordinateParser:
"""Helper class to structure coordinate parser"""
def parse_coordinate(string_rep):
"""Parse a single coordinate"""
<|body_0|>
def parse_angular_length_quantity(string_rep):
"""Given a string that is a number and a unit, return a Quantity of tha... | stack_v2_sparse_classes_36k_train_029540 | 18,136 | permissive | [
{
"docstring": "Parse a single coordinate",
"name": "parse_coordinate",
"signature": "def parse_coordinate(string_rep)"
},
{
"docstring": "Given a string that is a number and a unit, return a Quantity of that string.Raise an Error If there is no unit. e.g.: 50\" -> 50*u.arcsec 50 -> CRTFRegionPa... | 2 | stack_v2_sparse_classes_30k_train_000422 | Implement the Python class `CoordinateParser` described below.
Class description:
Helper class to structure coordinate parser
Method signatures and docstrings:
- def parse_coordinate(string_rep): Parse a single coordinate
- def parse_angular_length_quantity(string_rep): Given a string that is a number and a unit, ret... | Implement the Python class `CoordinateParser` described below.
Class description:
Helper class to structure coordinate parser
Method signatures and docstrings:
- def parse_coordinate(string_rep): Parse a single coordinate
- def parse_angular_length_quantity(string_rep): Given a string that is a number and a unit, ret... | 55cb07f3ae54759637ba26d35bfcdf6043b825fb | <|skeleton|>
class CoordinateParser:
"""Helper class to structure coordinate parser"""
def parse_coordinate(string_rep):
"""Parse a single coordinate"""
<|body_0|>
def parse_angular_length_quantity(string_rep):
"""Given a string that is a number and a unit, return a Quantity of tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoordinateParser:
"""Helper class to structure coordinate parser"""
def parse_coordinate(string_rep):
"""Parse a single coordinate"""
if 'pix' in string_rep:
return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)
if 'h' in string_rep or 'rad' in string_rep:
... | the_stack_v2_python_sparse | regions/io/crtf/read.py | kakirastern/regions | train | 1 |
de443b6685ad8c2ffcfa4b1c4e683e6b5f38d27c | [
"if file_path is None:\n raise ValueError('A file path is required')\nself._file_path = platform_util.readahead_file_path(file_path)\nself._detect_file_replacement = detect_file_replacement\nself._file_size = None\nself._iterator = _make_tf_record_iterator(self._file_path)\nif self._detect_file_replacement and (... | <|body_start_0|>
if file_path is None:
raise ValueError('A file path is required')
self._file_path = platform_util.readahead_file_path(file_path)
self._detect_file_replacement = detect_file_replacement
self._file_size = None
self._iterator = _make_tf_record_iterator(s... | An iterator that yields Event protos as serialized bytestrings. | RawEventFileLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawEventFileLoader:
"""An iterator that yields Event protos as serialized bytestrings."""
def __init__(self, file_path, detect_file_replacement=False):
"""Constructs a RawEventFileLoader for the given file path. Args: file_path: the event file path to read from detect_file_replacemen... | stack_v2_sparse_classes_36k_train_029541 | 11,831 | permissive | [
{
"docstring": "Constructs a RawEventFileLoader for the given file path. Args: file_path: the event file path to read from detect_file_replacement: if True, when Load() is called, the loader will make a stat() call to check the size of the file. If it sees that the file has grown, it will reopen the file entire... | 3 | null | Implement the Python class `RawEventFileLoader` described below.
Class description:
An iterator that yields Event protos as serialized bytestrings.
Method signatures and docstrings:
- def __init__(self, file_path, detect_file_replacement=False): Constructs a RawEventFileLoader for the given file path. Args: file_path... | Implement the Python class `RawEventFileLoader` described below.
Class description:
An iterator that yields Event protos as serialized bytestrings.
Method signatures and docstrings:
- def __init__(self, file_path, detect_file_replacement=False): Constructs a RawEventFileLoader for the given file path. Args: file_path... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class RawEventFileLoader:
"""An iterator that yields Event protos as serialized bytestrings."""
def __init__(self, file_path, detect_file_replacement=False):
"""Constructs a RawEventFileLoader for the given file path. Args: file_path: the event file path to read from detect_file_replacemen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawEventFileLoader:
"""An iterator that yields Event protos as serialized bytestrings."""
def __init__(self, file_path, detect_file_replacement=False):
"""Constructs a RawEventFileLoader for the given file path. Args: file_path: the event file path to read from detect_file_replacement: if True, w... | the_stack_v2_python_sparse | tensorboard/backend/event_processing/event_file_loader.py | tensorflow/tensorboard | train | 6,766 |
f441fc6de414fc939b58956f535a604f079af177 | [
"diff = 0\nnums.sort()\nwhile True:\n res = self.threeSum(nums, target + diff)\n if res:\n return target + diff\n res = self.threeSum(nums, target - diff)\n if res:\n return target - diff\n diff += 1",
"result, visited = (set(), {})\nfor i in xrange(len(nums) - 2):\n table, target ... | <|body_start_0|>
diff = 0
nums.sort()
while True:
res = self.threeSum(nums, target + diff)
if res:
return target + diff
res = self.threeSum(nums, target - diff)
if res:
return target - diff
diff += 1
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSumClosest(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def threeSum(self, nums, n):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dif... | stack_v2_sparse_classes_36k_train_029542 | 1,176 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "threeSumClosest",
"signature": "def threeSumClosest(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def threeSum(self, nums, n): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumClosest(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def threeSum(self, nums, n): :type nums: List[int] :rtype: List[List[int]]
<|skele... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|skeleton|>
class Solution:
def threeSumClosest(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def threeSum(self, nums, n):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSumClosest(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
diff = 0
nums.sort()
while True:
res = self.threeSum(nums, target + diff)
if res:
return target + diff
res = self.thr... | the_stack_v2_python_sparse | leetcode3/threeSumClosest.py | lizyang95/leetcode | train | 0 | |
2055f0af4262ba8b58df4c8d2bc7b656bc36ec97 | [
"with h5py.File(self.dataset, mode='r') as h5in:\n self.logger.info('Loading the labels...')\n labels = pd.DataFrame.from_records(np.asarray(h5in['labels']))\n labels[['protocol', 'region']] = labels[['protocol', 'region']].transform(lambda col: col.str.decode('ascii'))\n self.logger.info('Loading the f... | <|body_start_0|>
with h5py.File(self.dataset, mode='r') as h5in:
self.logger.info('Loading the labels...')
labels = pd.DataFrame.from_records(np.asarray(h5in['labels']))
labels[['protocol', 'region']] = labels[['protocol', 'region']].transform(lambda col: col.str.decode('asci... | Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples. | EvaluateDistinguisherExperiment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateDistinguisherExperiment:
"""Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples."""
def load_dataset(self) -> tuple:
"""Return a tuple of the labels dataframe and features."""
<|body_0|>
def split_dataset(self, labels,... | stack_v2_sparse_classes_36k_train_029543 | 5,814 | permissive | [
{
"docstring": "Return a tuple of the labels dataframe and features.",
"name": "load_dataset",
"signature": "def load_dataset(self) -> tuple"
},
{
"docstring": "Split the dataset, and yield train, test splits.",
"name": "split_dataset",
"signature": "def split_dataset(self, labels, rando... | 3 | stack_v2_sparse_classes_30k_train_011522 | Implement the Python class `EvaluateDistinguisherExperiment` described below.
Class description:
Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples.
Method signatures and docstrings:
- def load_dataset(self) -> tuple: Return a tuple of the labels dataframe and features.
-... | Implement the Python class `EvaluateDistinguisherExperiment` described below.
Class description:
Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples.
Method signatures and docstrings:
- def load_dataset(self) -> tuple: Return a tuple of the labels dataframe and features.
-... | b5ffa1ad90d6af8b8dc4a5e6878cc85325794842 | <|skeleton|>
class EvaluateDistinguisherExperiment:
"""Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples."""
def load_dataset(self) -> tuple:
"""Return a tuple of the labels dataframe and features."""
<|body_0|>
def split_dataset(self, labels,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluateDistinguisherExperiment:
"""Evaluate the ability of the random-forest classifier to distinguish between QUIC and TCP samples."""
def load_dataset(self) -> tuple:
"""Return a tuple of the labels dataframe and features."""
with h5py.File(self.dataset, mode='r') as h5in:
... | the_stack_v2_python_sparse | workflows/distinguish-protocol/scripts/evaluate-distinguisher | HITdzy/wf-in-the-age-of-quic | train | 0 |
f4c85698963db33c68f79c69790bde9aa2d706c2 | [
"self.v = [v1, v2]\nself.n = [len(v1), len(v2)]\nself.row = 1\nself.col = -1",
"if self.row == 1:\n self.row = 0 if self.col + 1 < self.n[0] else 1\n self.col += 1\nelif self.col < self.n[1]:\n self.row = 1\nelse:\n self.col += 1\nreturn self.v[self.row][self.col]",
"if self.row == 1:\n if self.c... | <|body_start_0|>
self.v = [v1, v2]
self.n = [len(v1), len(v2)]
self.row = 1
self.col = -1
<|end_body_0|>
<|body_start_1|>
if self.row == 1:
self.row = 0 if self.col + 1 < self.n[0] else 1
self.col += 1
elif self.col < self.n[1]:
self.r... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_029544 | 1,338 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_019006 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | fad32c510108d21f78540f8c4ed0295341c0c2dc | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v = [v1, v2]
self.n = [len(v1), len(v2)]
self.row = 1
self.col = -1
def next(self):
""":rtype: int"""
if self.row == ... | the_stack_v2_python_sparse | 281 - Zigzag Iterator/zi.py | huragok/LeetCode-Practce | train | 0 | |
8fdbae7d7714842874626febf30828970049330b | [
"self.x = np.array(x)\nself.y = np.array(y)\nself.data = np.array(data)",
"ix = np.searchsorted(self.x, x).clip(1, len(self.x) - 1)\niy = np.searchsorted(self.y, y).clip(1, len(self.y) - 1)\ndx = (x - self.x[ix - 1]) / (self.x[ix] - self.x[ix - 1])\ndy = (y - self.y[iy - 1]) / (self.y[iy] - self.y[iy - 1])\ndata1... | <|body_start_0|>
self.x = np.array(x)
self.y = np.array(y)
self.data = np.array(data)
<|end_body_0|>
<|body_start_1|>
ix = np.searchsorted(self.x, x).clip(1, len(self.x) - 1)
iy = np.searchsorted(self.y, y).clip(1, len(self.y) - 1)
dx = (x - self.x[ix - 1]) / (self.x[ix]... | Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional. | LinearInterp2D | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two... | stack_v2_sparse_classes_36k_train_029545 | 9,328 | permissive | [
{
"docstring": "x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two coordinates are x and y",
"name": "__init__",
"signature": "def __init__(self, x, y, data)"
},
{
"docstring": "Evaluate data at (x,y)",
"name... | 2 | stack_v2_sparse_classes_30k_train_017511 | Implement the Python class `LinearInterp2D` described below.
Class description:
Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional.
Method signatures and docstrings:
- def __init__(self, x, y, data): x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 o... | Implement the Python class `LinearInterp2D` described below.
Class description:
Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional.
Method signatures and docstrings:
- def __init__(self, x, y, data): x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 o... | fca7d0cd515b756233dfd530e9f779c637730bc4 | <|skeleton|>
class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two coordinates ... | the_stack_v2_python_sparse | desihub/specter/py/specter/util/util.py | michaelJwilson/LBGCMB | train | 2 |
a8e1442a084aba78bbb434009ab5c6463feef871 | [
"self.featstruct = featstruct\nself.readings = []\ntry:\n self.core = featstruct['CORE']\n self.store = featstruct['STORE']\nexcept KeyError:\n print('%s is not a Cooper storage structure' % featstruct)",
"remove = lambda lst0, index: lst0[:index] + lst0[index + 1:]\nif lst:\n for index, x in enumerat... | <|body_start_0|>
self.featstruct = featstruct
self.readings = []
try:
self.core = featstruct['CORE']
self.store = featstruct['STORE']
except KeyError:
print('%s is not a Cooper storage structure' % featstruct)
<|end_body_0|>
<|body_start_1|>
r... | A container for handling quantifier ambiguity via Cooper storage. | CooperStore | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CooperStore:
"""A container for handling quantifier ambiguity via Cooper storage."""
def __init__(self, featstruct):
""":param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: FeatStruct (with features ``core`` and ``store``)"""
... | stack_v2_sparse_classes_36k_train_029546 | 4,086 | permissive | [
{
"docstring": ":param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: FeatStruct (with features ``core`` and ``store``)",
"name": "__init__",
"signature": "def __init__(self, featstruct)"
},
{
"docstring": ":return: An iterator over the permut... | 3 | stack_v2_sparse_classes_30k_train_003140 | Implement the Python class `CooperStore` described below.
Class description:
A container for handling quantifier ambiguity via Cooper storage.
Method signatures and docstrings:
- def __init__(self, featstruct): :param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: ... | Implement the Python class `CooperStore` described below.
Class description:
A container for handling quantifier ambiguity via Cooper storage.
Method signatures and docstrings:
- def __init__(self, featstruct): :param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: ... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class CooperStore:
"""A container for handling quantifier ambiguity via Cooper storage."""
def __init__(self, featstruct):
""":param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: FeatStruct (with features ``core`` and ``store``)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CooperStore:
"""A container for handling quantifier ambiguity via Cooper storage."""
def __init__(self, featstruct):
""":param featstruct: The value of the ``sem`` node in a tree from ``parse_with_bindops()`` :type featstruct: FeatStruct (with features ``core`` and ``store``)"""
self.feat... | the_stack_v2_python_sparse | nltk/sem/cooper_storage.py | nltk/nltk | train | 11,860 |
1c76306cbac0863ca58f76cdcc76a9c657d3fa4a | [
"super(Embedding, self).__init__()\nif len(counts) == 0:\n raise RuntimeError('Embedding must take input' + 'from at least 1 group')\nself.layer1 = nn.ModuleDict()\nfor k, v in counts.items():\n self.layer1[k] = stack_layers(v, layers=1, dropout=0.0, norm=norm)\nnum = sum(counts.values())\nself.layer2 = stack... | <|body_start_0|>
super(Embedding, self).__init__()
if len(counts) == 0:
raise RuntimeError('Embedding must take input' + 'from at least 1 group')
self.layer1 = nn.ModuleDict()
for k, v in counts.items():
self.layer1[k] = stack_layers(v, layers=1, dropout=0.0, norm... | Embedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict() with a superset... | stack_v2_sparse_classes_36k_train_029547 | 5,028 | permissive | [
{
"docstring": ":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization.",
"name": "__init__",
"signature": "def __init__(self, counts, dropout=None, norm=None)"
},
{
"docstring": "x: OrderedDict() with a superset of the key... | 2 | null | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, counts, dropout=None, norm=None): :param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normaliza... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, counts, dropout=None, norm=None): :param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normaliza... | b40e9b147186ca04efd384d05b0f5e27ff8bd71a | <|skeleton|>
class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict() with a superset... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Embedding:
def __init__(self, counts, dropout=None, norm=None):
""":param counts: dictionary of scalar input sizes. :param dropout: scalar dropout rate. :param norm: string type of normalization."""
super(Embedding, self).__init__()
if len(counts) == 0:
raise RuntimeError('... | the_stack_v2_python_sparse | nets/util.py | yuwei-cheng/eBay | train | 0 | |
128089cc38cf0a59d8634b10e2ec91922dccebca | [
"super().__init__()\nassert len(weights) == 2, f'Only 2 weight elements are required for BCE-Dice loss combo, found: {len(weights)}'\nself.weights = weights\nself.bce_with_logits = nn.BCEWithLogitsLoss()\nself.dice_loss = BinaryDiceLoss(apply_sigmoid=True)",
"bce_loss = self.bce_with_logits(detail_out, detail_tar... | <|body_start_0|>
super().__init__()
assert len(weights) == 2, f'Only 2 weight elements are required for BCE-Dice loss combo, found: {len(weights)}'
self.weights = weights
self.bce_with_logits = nn.BCEWithLogitsLoss()
self.dice_loss = BinaryDiceLoss(apply_sigmoid=True)
<|end_body_... | STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss | DetailLoss | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetailLoss:
"""STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss"""
def __init__(self, weights: list=[1.0, 1.0]):
""":param weights: weight to apply for each part of the loss contributions... | stack_v2_sparse_classes_36k_train_029548 | 9,721 | permissive | [
{
"docstring": ":param weights: weight to apply for each part of the loss contributions, [BCE, Dice] respectively.",
"name": "__init__",
"signature": "def __init__(self, weights: list=[1.0, 1.0])"
},
{
"docstring": ":param detail_out: predicted detail map. :param detail_target: ground-truth deta... | 2 | stack_v2_sparse_classes_30k_val_000866 | Implement the Python class `DetailLoss` described below.
Class description:
STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss
Method signatures and docstrings:
- def __init__(self, weights: list=[1.0, 1.0]): :param weights... | Implement the Python class `DetailLoss` described below.
Class description:
STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss
Method signatures and docstrings:
- def __init__(self, weights: list=[1.0, 1.0]): :param weights... | 7240726cf6425b53a26ed2faec03672f30fee6be | <|skeleton|>
class DetailLoss:
"""STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss"""
def __init__(self, weights: list=[1.0, 1.0]):
""":param weights: weight to apply for each part of the loss contributions... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetailLoss:
"""STDC DetailLoss applied on details features from higher resolution and ground-truth details map. Loss combination of BCE loss and BinaryDice loss"""
def __init__(self, weights: list=[1.0, 1.0]):
""":param weights: weight to apply for each part of the loss contributions, [BCE, Dice]... | the_stack_v2_python_sparse | src/super_gradients/training/losses/stdc_loss.py | Deci-AI/super-gradients | train | 3,237 |
fecb3e22946d38845977e65758ca3ade8bc44058 | [
"super().__init__()\nrequire_grad = False\nself.leak = leak\nself.competition = competition\nself.self_excitation = self_excitation\nself.noise = noise\nself.time_step_size = time_step_size\nself.non_decision_time = non_decision_time\nself._sqrt_step_size = torch.sqrt(torch.tensor(0.001, requires_grad=require_grad)... | <|body_start_0|>
super().__init__()
require_grad = False
self.leak = leak
self.competition = competition
self.self_excitation = self_excitation
self.noise = noise
self.time_step_size = time_step_size
self.non_decision_time = non_decision_time
self.... | LCALayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decisi... | stack_v2_sparse_classes_36k_train_029549 | 11,741 | permissive | [
{
"docstring": "An implementation of a Leaky Competing Accumulator as a layer. Each call to forward of this module only implements one time step of the integration. See module LCAModel if you want to simulate an LCA to completion. Args: threshold: The threshold that accumulators must reach to stop integration. ... | 2 | stack_v2_sparse_classes_30k_val_001181 | Implement the Python class `LCALayer` described below.
Class description:
Implement the LCALayer class.
Method signatures and docstrings:
- def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTens... | Implement the Python class `LCALayer` described below.
Class description:
Implement the LCALayer class.
Method signatures and docstrings:
- def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTens... | 424971b04d55a2cddbae4c05a0aae2d7b3502c20 | <|skeleton|>
class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decisi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCALayer:
def __init__(self, threshold: Union[float, torch.FloatTensor, None]=torch.tensor(1.0), leak: Union[torch.FloatTensor, float]=torch.tensor(0.1), competition: Union[torch.FloatTensor, float]=torch.tensor(0.1), self_excitation: Union[torch.FloatTensor, float]=torch.tensor(0.0), non_decision_time: Union... | the_stack_v2_python_sparse | Scripts/Debug/lca/onnx_lca.py | PrincetonUniversity/PsyNeuLink | train | 79 | |
c69c633ed0d4cc30bc8b89190e2c5e9ed0f706b4 | [
"self.rtol = rtol\nself.atol = atol\nsuper(WeightedGraphMatcher, self).__init__(G1, G2)",
"G1_adj = self.G1.adj\nG2_adj = self.G2.adj\ncore_1 = self.core_1\nrtol, atol = (self.rtol, self.atol)\nfor neighbor in G1_adj[G1_node]:\n if neighbor is G1_node:\n if not close(G1_adj[G1_node][G1_node].get('weight... | <|body_start_0|>
self.rtol = rtol
self.atol = atol
super(WeightedGraphMatcher, self).__init__(G1, G2)
<|end_body_0|>
<|body_start_1|>
G1_adj = self.G1.adj
G2_adj = self.G2.adj
core_1 = self.core_1
rtol, atol = (self.rtol, self.atol)
for neighbor in G1_adj... | Implementation of VF2 algorithm for undirected, weighted graphs. | WeightedGraphMatcher | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedGraphMatcher:
"""Implementation of VF2 algorithm for undirected, weighted graphs."""
def __init__(self, G1, G2, rtol=1e-06, atol=1e-09):
"""Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, opti... | stack_v2_sparse_classes_36k_train_029550 | 9,804 | permissive | [
{
"docstring": "Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, optional The relative tolerance used to compare weights. atol : float, optional The absolute tolerance used to compare weights.",
"name": "__init__",
"signa... | 2 | null | Implement the Python class `WeightedGraphMatcher` described below.
Class description:
Implementation of VF2 algorithm for undirected, weighted graphs.
Method signatures and docstrings:
- def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instan... | Implement the Python class `WeightedGraphMatcher` described below.
Class description:
Implementation of VF2 algorithm for undirected, weighted graphs.
Method signatures and docstrings:
- def __init__(self, G1, G2, rtol=1e-06, atol=1e-09): Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instan... | de0cdb26248f6d0d8bea594124c1dd7a155d406d | <|skeleton|>
class WeightedGraphMatcher:
"""Implementation of VF2 algorithm for undirected, weighted graphs."""
def __init__(self, G1, G2, rtol=1e-06, atol=1e-09):
"""Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightedGraphMatcher:
"""Implementation of VF2 algorithm for undirected, weighted graphs."""
def __init__(self, G1, G2, rtol=1e-06, atol=1e-09):
"""Initialize WeightedGraphMatcher. Parameters ---------- G1, G2 : nx.Graph instances G1 and G2 must be weighted graphs. rtol : float, optional The rela... | the_stack_v2_python_sparse | Source/lib/CrossPlatform/networkx/algorithms/isomorphism/vf2weighted.py | JaneliaSciComp/Neuroptikon | train | 9 |
a19c1614fb7c4aeba78ed08c0347715256f8ba60 | [
"self.kconserv = get_kconserv(cell, kpts)\nnkpts = len(kpts)\ntemp = range(0, nkpts)\nkptlist = pyscf.lib.cartesian_prod((temp, temp, temp))\ncompleted = np.zeros((nkpts, nkpts, nkpts), dtype=bool)\nself._operation = np.zeros((nkpts, nkpts, nkpts), dtype=int)\nself.symm_map = OrderedDict()\nfor kpt in kptlist:\n ... | <|body_start_0|>
self.kconserv = get_kconserv(cell, kpts)
nkpts = len(kpts)
temp = range(0, nkpts)
kptlist = pyscf.lib.cartesian_prod((temp, temp, temp))
completed = np.zeros((nkpts, nkpts, nkpts), dtype=bool)
self._operation = np.zeros((nkpts, nkpts, nkpts), dtype=int)
... | KptsHelper | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KptsHelper:
def __init__(self, cell, kpts):
"""Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth momentum-conserving k-point, given indices of three k-points symm_map : OrderedDict of list of (3,) tup... | stack_v2_sparse_classes_36k_train_029551 | 7,250 | permissive | [
{
"docstring": "Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth momentum-conserving k-point, given indices of three k-points symm_map : OrderedDict of list of (3,) tuples Keys are (3,) tuples of symmetry-unique k-point ind... | 2 | null | Implement the Python class `KptsHelper` described below.
Class description:
Implement the KptsHelper class.
Method signatures and docstrings:
- def __init__(self, cell, kpts): Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth mome... | Implement the Python class `KptsHelper` described below.
Class description:
Implement the KptsHelper class.
Method signatures and docstrings:
- def __init__(self, cell, kpts): Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth mome... | 81606c8f384ff1da98a7aa4c817021a78302110a | <|skeleton|>
class KptsHelper:
def __init__(self, cell, kpts):
"""Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth momentum-conserving k-point, given indices of three k-points symm_map : OrderedDict of list of (3,) tup... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KptsHelper:
def __init__(self, cell, kpts):
"""Helper class for handling k-points in correlated calculations. Attributes: kconserv : (nkpts,nkpts,nkpts) ndarray The index of the fourth momentum-conserving k-point, given indices of three k-points symm_map : OrderedDict of list of (3,) tuples Keys are (... | the_stack_v2_python_sparse | pyscf/pbc/lib/kpts_helper.py | xlzan/pyscf | train | 1 | |
8d7fb5a0b2169e6a1c8282cdbb085f7151b7f05c | [
"self.alpha = alpha\nself.n_episodes = n_episodes_param\nself.epsilon = epsilon\nself.epsilon_min = epsilon_min\nself.decay_epsilon = decay_epsilon\nself.discount_factor = discount_factor\nself.max_steps = max_steps\nself.env = env\nself.Q = None",
"self.Q = np.zeros([len(self.env.all_possible_states), len(self.e... | <|body_start_0|>
self.alpha = alpha
self.n_episodes = n_episodes_param
self.epsilon = epsilon
self.epsilon_min = epsilon_min
self.decay_epsilon = decay_epsilon
self.discount_factor = discount_factor
self.max_steps = max_steps
self.env = env
self.Q ... | QLearningAlg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QLearningAlg:
def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max_steps, env):
""":param alpha: :param n_episodes_param: :param epsilon: :param epsilon_min: :param decay_epsilon: :param discount_factor: :param max_steps: :param env:"""
... | stack_v2_sparse_classes_36k_train_029552 | 3,177 | no_license | [
{
"docstring": ":param alpha: :param n_episodes_param: :param epsilon: :param epsilon_min: :param decay_epsilon: :param discount_factor: :param max_steps: :param env:",
"name": "__init__",
"signature": "def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max... | 3 | stack_v2_sparse_classes_30k_train_009865 | Implement the Python class `QLearningAlg` described below.
Class description:
Implement the QLearningAlg class.
Method signatures and docstrings:
- def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max_steps, env): :param alpha: :param n_episodes_param: :param epsilon: ... | Implement the Python class `QLearningAlg` described below.
Class description:
Implement the QLearningAlg class.
Method signatures and docstrings:
- def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max_steps, env): :param alpha: :param n_episodes_param: :param epsilon: ... | fade499272c1cbaeaf28f9e0adb83f7479c825ae | <|skeleton|>
class QLearningAlg:
def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max_steps, env):
""":param alpha: :param n_episodes_param: :param epsilon: :param epsilon_min: :param decay_epsilon: :param discount_factor: :param max_steps: :param env:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QLearningAlg:
def __init__(self, alpha, n_episodes_param, epsilon, epsilon_min, decay_epsilon, discount_factor, max_steps, env):
""":param alpha: :param n_episodes_param: :param epsilon: :param epsilon_min: :param decay_epsilon: :param discount_factor: :param max_steps: :param env:"""
self.alp... | the_stack_v2_python_sparse | QLearning.py | abadied/Pfsa | train | 0 | |
a4d98f5d57b730590af14185b984e342a0cef813 | [
"x = self.lrelu(self.conv1(self.refpad(x_in)))\nx = self.lrelu(self.conv2(self.refpad(x)))\nreturn x",
"super(LocalNet, self).__init__()\nself.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, 0, 1)\nself.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, 0, 1)\nself.lrelu = nn.LeakyReLU()\nself.refpad = nn.Ref... | <|body_start_0|>
x = self.lrelu(self.conv1(self.refpad(x_in)))
x = self.lrelu(self.conv2(self.refpad(x)))
return x
<|end_body_0|>
<|body_start_1|>
super(LocalNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, 0, 1)
self.conv2 = nn.Conv2d(out_ch... | LocalNet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalNet:
def forward(self, x_in):
"""Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor"""
<|body_0|>
def __init__(self, in_channels=16, out_channels=64):
"""Initialisation function :param in_channe... | stack_v2_sparse_classes_36k_train_029553 | 8,922 | permissive | [
{
"docstring": "Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor",
"name": "forward",
"signature": "def forward(self, x_in)"
},
{
"docstring": "Initialisation function :param in_channels: number of input channels :param out_ch... | 2 | null | Implement the Python class `LocalNet` described below.
Class description:
Implement the LocalNet class.
Method signatures and docstrings:
- def forward(self, x_in): Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor
- def __init__(self, in_channels=1... | Implement the Python class `LocalNet` described below.
Class description:
Implement the LocalNet class.
Method signatures and docstrings:
- def forward(self, x_in): Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor
- def __init__(self, in_channels=1... | 82c49c36b76987a46dec8479793f7cf0150839c6 | <|skeleton|>
class LocalNet:
def forward(self, x_in):
"""Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor"""
<|body_0|>
def __init__(self, in_channels=16, out_channels=64):
"""Initialisation function :param in_channe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalNet:
def forward(self, x_in):
"""Defines a double convolution :param x_in: input convolutional features :returns: convolutional features :rtype: Tensor"""
x = self.lrelu(self.conv1(self.refpad(x_in)))
x = self.lrelu(self.conv2(self.refpad(x)))
return x
def __init__(se... | the_stack_v2_python_sparse | CURL/rgb_ted.py | huawei-noah/noah-research | train | 816 | |
c0f3183c2e6059364952387a0aeea4b781730ee7 | [
"if len(intervals) == 0:\n return [newInterval]\nfor i in range(len(intervals)):\n if i == 0 and intervals[0].start >= newInterval.start:\n intervals.insert(0, newInterval)\n break\n if intervals[i].start <= newInterval.start:\n if intervals[i].end >= newInterval.start:\n in... | <|body_start_0|>
if len(intervals) == 0:
return [newInterval]
for i in range(len(intervals)):
if i == 0 and intervals[0].start >= newInterval.start:
intervals.insert(0, newInterval)
break
if intervals[i].start <= newInterval.start:
... | Ex57 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ex57:
def insert(self, intervals, newInterval):
""":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_029554 | 4,210 | no_license | [
{
"docstring": ":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]",
"name": "insert",
"signature": "def insert(self, intervals, newInterval)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge",
"signature": "def me... | 2 | stack_v2_sparse_classes_30k_val_000756 | Implement the Python class `Ex57` described below.
Class description:
Implement the Ex57 class.
Method signatures and docstrings:
- def insert(self, intervals, newInterval): :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]
- def merge(self, intervals): :type intervals: List[Interval]... | Implement the Python class `Ex57` described below.
Class description:
Implement the Ex57 class.
Method signatures and docstrings:
- def insert(self, intervals, newInterval): :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]
- def merge(self, intervals): :type intervals: List[Interval]... | 8f9327a1879949f61b462cc6c82e00e7c27b8b07 | <|skeleton|>
class Ex57:
def insert(self, intervals, newInterval):
""":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ex57:
def insert(self, intervals, newInterval):
""":type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]"""
if len(intervals) == 0:
return [newInterval]
for i in range(len(intervals)):
if i == 0 and intervals[0].start >= newInterval.... | the_stack_v2_python_sparse | LeetCode/Ex0/Ex57.py | JasonVann/CrackingCodingInterview | train | 0 | |
4b8778639d46ad7c6087f5484c271e8b986110f0 | [
"super().__init__(**kw)\nself.sequence = sequence\nself.upload = upload\nself.upload_first = upload_first\nself.start_pulsar = start_pulsar\nself.start_exclude_awgs = start_exclude_awgs\nself.upload_finished_callback = upload_finished_callback",
"if self.upload_first:\n self.upload_sequence()\nif self.start_pu... | <|body_start_0|>
super().__init__(**kw)
self.sequence = sequence
self.upload = upload
self.upload_first = upload_first
self.start_pulsar = start_pulsar
self.start_exclude_awgs = start_exclude_awgs
self.upload_finished_callback = upload_finished_callback
<|end_body... | UploadingSweepFunction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadingSweepFunction:
def __init__(self, sequence=None, upload=True, upload_first=True, start_pulsar=False, start_exclude_awgs=tuple(), upload_finished_callback=None, **kw):
"""Extends any sweep function to be able to upload sequences. Args: sequence (:class:`~pycqed.measurement.wavefo... | stack_v2_sparse_classes_36k_train_029555 | 26,201 | permissive | [
{
"docstring": "Extends any sweep function to be able to upload sequences. Args: sequence (:class:`~pycqed.measurement.waveform_control.sequence.Sequence`): Sequence of segments to sweep over. upload (bool, optional): Whether to upload the sequences before measurement. Defaults to True. start_pulsar (bool, opti... | 4 | null | Implement the Python class `UploadingSweepFunction` described below.
Class description:
Implement the UploadingSweepFunction class.
Method signatures and docstrings:
- def __init__(self, sequence=None, upload=True, upload_first=True, start_pulsar=False, start_exclude_awgs=tuple(), upload_finished_callback=None, **kw)... | Implement the Python class `UploadingSweepFunction` described below.
Class description:
Implement the UploadingSweepFunction class.
Method signatures and docstrings:
- def __init__(self, sequence=None, upload=True, upload_first=True, start_pulsar=False, start_exclude_awgs=tuple(), upload_finished_callback=None, **kw)... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class UploadingSweepFunction:
def __init__(self, sequence=None, upload=True, upload_first=True, start_pulsar=False, start_exclude_awgs=tuple(), upload_finished_callback=None, **kw):
"""Extends any sweep function to be able to upload sequences. Args: sequence (:class:`~pycqed.measurement.wavefo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadingSweepFunction:
def __init__(self, sequence=None, upload=True, upload_first=True, start_pulsar=False, start_exclude_awgs=tuple(), upload_finished_callback=None, **kw):
"""Extends any sweep function to be able to upload sequences. Args: sequence (:class:`~pycqed.measurement.waveform_control.seq... | the_stack_v2_python_sparse | pycqed/measurement/sweep_functions.py | QudevETH/PycQED_py3 | train | 8 | |
6d36876cfb54b81bb67d3e61f70f60e4df48e2e2 | [
"dic = set()\nwhile headA and headB:\n if headA not in dic and headB not in dic:\n dic.add(headA)\n if headB not in dic:\n dic.add(headB)\n else:\n return headB\n headA = headA.next\n headB = headB.next\n elif headA in dic:\n return headA\n el... | <|body_start_0|>
dic = set()
while headA and headB:
if headA not in dic and headB not in dic:
dic.add(headA)
if headB not in dic:
dic.add(headB)
else:
return headB
headA = headA.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode_2_pointers(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
def getIntersecti... | stack_v2_sparse_classes_36k_train_029556 | 3,332 | no_license | [
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode_2_pointers",
"signature": "def getInte... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode_2_pointers(self, headA, headB): :type head1, head1: ListNode ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
- def getIntersectionNode_2_pointers(self, headA, headB): :type head1, head1: ListNode ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode_2_pointers(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
def getIntersecti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
dic = set()
while headA and headB:
if headA not in dic and headB not in dic:
dic.add(headA)
if headB not in dic:
di... | the_stack_v2_python_sparse | LeetCode/LinkedList/160_intersection_of_two_linked_lists.py | XyK0907/for_work | train | 0 | |
1c638bd85742de8807de404dd2df1a56102f7271 | [
"if not value.startswith('arxiv:///'):\n value = f\"arxiv:///{value.lstrip('/')}\"\nkey: Key = super(Key, cls).__new__(cls, value)\nreturn key",
"if not value.startswith('arxiv:///'):\n value = f\"arxiv:///{value.lstrip('/')}\"\nsuper(Key, self).__init__(value)\n_, self.filename = os.path.split(self.path)"
... | <|body_start_0|>
if not value.startswith('arxiv:///'):
value = f"arxiv:///{value.lstrip('/')}"
key: Key = super(Key, cls).__new__(cls, value)
return key
<|end_body_0|>
<|body_start_1|>
if not value.startswith('arxiv:///'):
value = f"arxiv:///{value.lstrip('/')}"
... | The unique identifier for a bitstream in the canonical record. | Key | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Key:
"""The unique identifier for a bitstream in the canonical record."""
def __new__(cls, value: str) -> 'Key':
"""Make a new key."""
<|body_0|>
def __init__(self, value: str) -> None:
"""Initialize a key with a str value."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_029557 | 4,598 | permissive | [
{
"docstring": "Make a new key.",
"name": "__new__",
"signature": "def __new__(cls, value: str) -> 'Key'"
},
{
"docstring": "Initialize a key with a str value.",
"name": "__init__",
"signature": "def __init__(self, value: str) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_010361 | Implement the Python class `Key` described below.
Class description:
The unique identifier for a bitstream in the canonical record.
Method signatures and docstrings:
- def __new__(cls, value: str) -> 'Key': Make a new key.
- def __init__(self, value: str) -> None: Initialize a key with a str value. | Implement the Python class `Key` described below.
Class description:
The unique identifier for a bitstream in the canonical record.
Method signatures and docstrings:
- def __new__(cls, value: str) -> 'Key': Make a new key.
- def __init__(self, value: str) -> None: Initialize a key with a str value.
<|skeleton|>
clas... | 407cb0b2cef83c7f653dabdf998e797b18475b13 | <|skeleton|>
class Key:
"""The unique identifier for a bitstream in the canonical record."""
def __new__(cls, value: str) -> 'Key':
"""Make a new key."""
<|body_0|>
def __init__(self, value: str) -> None:
"""Initialize a key with a str value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Key:
"""The unique identifier for a bitstream in the canonical record."""
def __new__(cls, value: str) -> 'Key':
"""Make a new key."""
if not value.startswith('arxiv:///'):
value = f"arxiv:///{value.lstrip('/')}"
key: Key = super(Key, cls).__new__(cls, value)
r... | the_stack_v2_python_sparse | arxiv/canonical/domain/file.py | arXiv/arxiv-canonical | train | 5 |
38557bf46621be600e97b4bf5151940405698bc0 | [
"self.MessageObj = Message(input_info, n_frames)\nself.input_info = self.MessageObj.input_info\nself.bitstream_frames = self.MessageObj.bitstream_frames\nself.number_of_frames = self.MessageObj.number_of_frames\nself.rx_bitstream_frames = self.MessageObj.rx_bitstream_frames\nself.output_info = self.MessageObj.outpu... | <|body_start_0|>
self.MessageObj = Message(input_info, n_frames)
self.input_info = self.MessageObj.input_info
self.bitstream_frames = self.MessageObj.bitstream_frames
self.number_of_frames = self.MessageObj.number_of_frames
self.rx_bitstream_frames = self.MessageObj.rx_bitstream_... | TestMessageTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMessageTypes:
def setUp(self):
"""Setup function TestTypes for class Message"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Message"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.MessageObj = Message(input_inf... | stack_v2_sparse_classes_36k_train_029558 | 1,569 | permissive | [
{
"docstring": "Setup function TestTypes for class Message",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Function to test data types for class Message",
"name": "test_types",
"signature": "def test_types(self)"
}
] | 2 | null | Implement the Python class `TestMessageTypes` described below.
Class description:
Implement the TestMessageTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Message
- def test_types(self): Function to test data types for class Message | Implement the Python class `TestMessageTypes` described below.
Class description:
Implement the TestMessageTypes class.
Method signatures and docstrings:
- def setUp(self): Setup function TestTypes for class Message
- def test_types(self): Function to test data types for class Message
<|skeleton|>
class TestMessageT... | 825a0eab64be709efe161b9a48eb54c4bc5c1bef | <|skeleton|>
class TestMessageTypes:
def setUp(self):
"""Setup function TestTypes for class Message"""
<|body_0|>
def test_types(self):
"""Function to test data types for class Message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMessageTypes:
def setUp(self):
"""Setup function TestTypes for class Message"""
self.MessageObj = Message(input_info, n_frames)
self.input_info = self.MessageObj.input_info
self.bitstream_frames = self.MessageObj.bitstream_frames
self.number_of_frames = self.Message... | the_stack_v2_python_sparse | VLC_devel/class_structure/__auto_gen__/test_Message.py | wenh81/vlc_simulator | train | 0 | |
e673fcaa75b852f6c17b1c705d89107609c7f789 | [
"greatSum = float('-inf')\ncurSum = 0\nfor x in array:\n if curSum > 0:\n curSum += x\n else:\n curSum = x\n greatSum = max(greatSum, curSum)\nreturn greatSum",
"result = -1\nfirst = True\nfor x in array:\n if result < 0:\n result = x\n else:\n result += x\n if first:... | <|body_start_0|>
greatSum = float('-inf')
curSum = 0
for x in array:
if curSum > 0:
curSum += x
else:
curSum = x
greatSum = max(greatSum, curSum)
return greatSum
<|end_body_0|>
<|body_start_1|>
result = -1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def FindGreatestSumOfSubArray(self, array):
"""提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。"""
<|body_0|>
def FindGreatestSumOfSubArray_back(self, array):
"""提示: 同方法一,但牛客网 python2.7 不支持无穷小 float("-inf"): 从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。"""
... | stack_v2_sparse_classes_36k_train_029559 | 2,517 | permissive | [
{
"docstring": "提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。",
"name": "FindGreatestSumOfSubArray",
"signature": "def FindGreatestSumOfSubArray(self, array)"
},
{
"docstring": "提示: 同方法一,但牛客网 python2.7 不支持无穷小 float(\"-inf\"): 从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。",
"name": "FindGre... | 3 | stack_v2_sparse_classes_30k_train_010571 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def FindGreatestSumOfSubArray(self, array): 提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。
- def FindGreatestSumOfSubArray_back(self, array): 提示: 同方法一,但牛客网 python2.7 不支持无穷小 f... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def FindGreatestSumOfSubArray(self, array): 提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。
- def FindGreatestSumOfSubArray_back(self, array): 提示: 同方法一,但牛客网 python2.7 不支持无穷小 f... | 889d8fa489f1f2719c5a0dafd3ae51df7b4bf978 | <|skeleton|>
class Solution:
def FindGreatestSumOfSubArray(self, array):
"""提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。"""
<|body_0|>
def FindGreatestSumOfSubArray_back(self, array):
"""提示: 同方法一,但牛客网 python2.7 不支持无穷小 float("-inf"): 从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def FindGreatestSumOfSubArray(self, array):
"""提示: 方法一:从头到尾逐个累加数组里的数字,如果某次累加的结果为负数,则从下一个元素开始重新累加。"""
greatSum = float('-inf')
curSum = 0
for x in array:
if curSum > 0:
curSum += x
else:
curSum = x
gre... | the_stack_v2_python_sparse | 剑指offer/42-连续子数组的最大和/FindGreatestSumOfSubArray.py | jinbooooom/coding-for-algorithms | train | 14 | |
4e839ba3808743ba8c8785079521bbfa02a0e34f | [
"data = JSONParser().parse(request)['detailed_requirements']\ndetailed_requirements = DetailedRequirement.objects.filter(id__in=[d['id'] for d in data])\nserializer = DetailedRequirementSerializer(detailed_requirements, many=True)\nreturn JsonResponse({'detailed_requirements': serializer.data}, safe=False)",
"res... | <|body_start_0|>
data = JSONParser().parse(request)['detailed_requirements']
detailed_requirements = DetailedRequirement.objects.filter(id__in=[d['id'] for d in data])
serializer = DetailedRequirementSerializer(detailed_requirements, many=True)
return JsonResponse({'detailed_requirements... | 指标点view | DetailedRequirements | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetailedRequirements:
"""指标点view"""
def get(self, request):
"""查询指标点"""
<|body_0|>
def put(self, request):
"""修改指标点"""
<|body_1|>
def post(self, request):
"""增加指标点"""
<|body_2|>
def delete(self, request):
"""删除指标点"""
... | stack_v2_sparse_classes_36k_train_029560 | 15,061 | permissive | [
{
"docstring": "查询指标点",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改指标点",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加指标点",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除指标点"... | 4 | stack_v2_sparse_classes_30k_train_017816 | Implement the Python class `DetailedRequirements` described below.
Class description:
指标点view
Method signatures and docstrings:
- def get(self, request): 查询指标点
- def put(self, request): 修改指标点
- def post(self, request): 增加指标点
- def delete(self, request): 删除指标点 | Implement the Python class `DetailedRequirements` described below.
Class description:
指标点view
Method signatures and docstrings:
- def get(self, request): 查询指标点
- def put(self, request): 修改指标点
- def post(self, request): 增加指标点
- def delete(self, request): 删除指标点
<|skeleton|>
class DetailedRequirements:
"""指标点view""... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class DetailedRequirements:
"""指标点view"""
def get(self, request):
"""查询指标点"""
<|body_0|>
def put(self, request):
"""修改指标点"""
<|body_1|>
def post(self, request):
"""增加指标点"""
<|body_2|>
def delete(self, request):
"""删除指标点"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetailedRequirements:
"""指标点view"""
def get(self, request):
"""查询指标点"""
data = JSONParser().parse(request)['detailed_requirements']
detailed_requirements = DetailedRequirement.objects.filter(id__in=[d['id'] for d in data])
serializer = DetailedRequirementSerializer(detaile... | the_stack_v2_python_sparse | plan/views.py | MIXISAMA/MIS-backend | train | 0 |
bb0c5155111e0c6ad0be0dcc95af68e9fde7e24b | [
"response = self.client.get(reverse('education:demographics'))\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.context.get('json_data'), None)\nself.assertEqual(response.context.get('all_cohort'), None)\nself.assertEqual(response.context.get('all_rate'), None)\nfor demo in State.GROUP_NAMES:... | <|body_start_0|>
response = self.client.get(reverse('education:demographics'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('json_data'), None)
self.assertEqual(response.context.get('all_cohort'), None)
self.assertEqual(response.context.get('a... | EducationDemographicsViewTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationDemographicsViewTest:
def test_no_data(self):
"""Make sure demographics page renders even if there is no data in the database."""
<|body_0|>
def test_with_data(self):
"""Make sure demographics page renders if there is data in the database."""
<|body_... | stack_v2_sparse_classes_36k_train_029561 | 9,266 | no_license | [
{
"docstring": "Make sure demographics page renders even if there is no data in the database.",
"name": "test_no_data",
"signature": "def test_no_data(self)"
},
{
"docstring": "Make sure demographics page renders if there is data in the database.",
"name": "test_with_data",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_005476 | Implement the Python class `EducationDemographicsViewTest` described below.
Class description:
Implement the EducationDemographicsViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure demographics page renders even if there is no data in the database.
- def test_with_data(self): Make s... | Implement the Python class `EducationDemographicsViewTest` described below.
Class description:
Implement the EducationDemographicsViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure demographics page renders even if there is no data in the database.
- def test_with_data(self): Make s... | 2a8e2dc4e9b3cb92d4d437b37e61940a9486b81f | <|skeleton|>
class EducationDemographicsViewTest:
def test_no_data(self):
"""Make sure demographics page renders even if there is no data in the database."""
<|body_0|>
def test_with_data(self):
"""Make sure demographics page renders if there is data in the database."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationDemographicsViewTest:
def test_no_data(self):
"""Make sure demographics page renders even if there is no data in the database."""
response = self.client.get(reverse('education:demographics'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context... | the_stack_v2_python_sparse | education/tests.py | smeds1/mysite | train | 1 | |
8e4e24a1c0fc91f6121c5fd6e4dfc68fdeab120a | [
"super().__init__()\nself.convKK = nn.Conv1d(k, k * k, dim_in, groups=k)\nself.activation = nn.Softmax(dim=-1)\nself.dp = nn.Dropout()",
"N, k, _ = region_feats.size()\nconved = self.convKK(region_feats)\nmultiplier = conved.view(N, k, k)\nmultiplier = self.activation(multiplier)\ntransformed_feats = torch.matmul... | <|body_start_0|>
super().__init__()
self.convKK = nn.Conv1d(k, k * k, dim_in, groups=k)
self.activation = nn.Softmax(dim=-1)
self.dp = nn.Dropout()
<|end_body_0|>
<|body_start_1|>
N, k, _ = region_feats.size()
conved = self.convKK(region_feats)
multiplier = conve... | A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d) | Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transform:
"""A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d)"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
<|body_0|>
def forward(self, region_feats):
""":param re... | stack_v2_sparse_classes_36k_train_029562 | 15,047 | no_license | [
{
"docstring": ":param dim_in: input feature dimension :param k: k neighbors",
"name": "__init__",
"signature": "def __init__(self, dim_in, k)"
},
{
"docstring": ":param region_feats: (N, k, d) :return: (N, k, d)",
"name": "forward",
"signature": "def forward(self, region_feats)"
}
] | 2 | null | Implement the Python class `Transform` described below.
Class description:
A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d)
Method signatures and docstrings:
- def __init__(self, dim_in, k): :param dim_in: input feature dimension :param k: k neighbors
- def forward(self, reg... | Implement the Python class `Transform` described below.
Class description:
A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d)
Method signatures and docstrings:
- def __init__(self, dim_in, k): :param dim_in: input feature dimension :param k: k neighbors
- def forward(self, reg... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Transform:
"""A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d)"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
<|body_0|>
def forward(self, region_feats):
""":param re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transform:
"""A Vertex Transformation module Permutation invariant transformation: (N, k, d) -> (N, k, d)"""
def __init__(self, dim_in, k):
""":param dim_in: input feature dimension :param k: k neighbors"""
super().__init__()
self.convKK = nn.Conv1d(k, k * k, dim_in, groups=k)
... | the_stack_v2_python_sparse | generated/test_iMoonLab_DHGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
2bdef0258e9969d3383d56253811c7e8958f0dde | [
"self.name = name\nself.text = text\nself.type_name = type_name\nself.ordered = ordered\nself.expression = expression if notnull(expression) else None\nself.loop_variables = loop_variables if loop_variables else []\nself.loop_expression = loop_expression",
"attribute_metadatas: List[AttributeMetadata] = []\nfor _... | <|body_start_0|>
self.name = name
self.text = text
self.type_name = type_name
self.ordered = ordered
self.expression = expression if notnull(expression) else None
self.loop_variables = loop_variables if loop_variables else []
self.loop_expression = loop_expression... | AttributeMetadata | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeMetadata:
def __init__(self, name: str, text: str, type_name: str, ordered: bool=None, expression: str=None, loop_variables: List[str]=None, loop_expression: Optional[str]=None):
"""Create metadata for a user attribute. :param name: The name of the attribute. :param text: The te... | stack_v2_sparse_classes_36k_train_029563 | 2,842 | permissive | [
{
"docstring": "Create metadata for a user attribute. :param name: The name of the attribute. :param text: The text representation of the attribute in the survey data. :param type_name: The type of the attribute. :param ordered: Whether the values of the attribute are ordered. :param expression: Optional regula... | 2 | null | Implement the Python class `AttributeMetadata` described below.
Class description:
Implement the AttributeMetadata class.
Method signatures and docstrings:
- def __init__(self, name: str, text: str, type_name: str, ordered: bool=None, expression: str=None, loop_variables: List[str]=None, loop_expression: Optional[str... | Implement the Python class `AttributeMetadata` described below.
Class description:
Implement the AttributeMetadata class.
Method signatures and docstrings:
- def __init__(self, name: str, text: str, type_name: str, ordered: bool=None, expression: str=None, loop_variables: List[str]=None, loop_expression: Optional[str... | 1a0fcf0c22e2c7306cba0218f82d24c97d28ee1f | <|skeleton|>
class AttributeMetadata:
def __init__(self, name: str, text: str, type_name: str, ordered: bool=None, expression: str=None, loop_variables: List[str]=None, loop_expression: Optional[str]=None):
"""Create metadata for a user attribute. :param name: The name of the attribute. :param text: The te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeMetadata:
def __init__(self, name: str, text: str, type_name: str, ordered: bool=None, expression: str=None, loop_variables: List[str]=None, loop_expression: Optional[str]=None):
"""Create metadata for a user attribute. :param name: The name of the attribute. :param text: The text representat... | the_stack_v2_python_sparse | survey/surveys/metadata/attribute_metadata.py | vahndi/quant-survey | train | 2 | |
ae9c066f9dac57118147a05f618b6acbc2d519e1 | [
"user = Users.objects().get(id=get_jwt_identity())\noutput = convert_doc(user, {'name', 'email', 'phone', 'roles'})\nimg_binary = user.image.read()\nimg_b64 = base64.b64encode(img_binary)\noutput['image'] = img_b64.decode('utf-8')\nreturn jsonify(output)",
"data = request.get_json()\ntry:\n user = Users.object... | <|body_start_0|>
user = Users.objects().get(id=get_jwt_identity())
output = convert_doc(user, {'name', 'email', 'phone', 'roles'})
img_binary = user.image.read()
img_b64 = base64.b64encode(img_binary)
output['image'] = img_b64.decode('utf-8')
return jsonify(output)
<|end_... | Flask-resftul resource for returning the signed in user information. | SignedInUserApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignedInUserApi:
"""Flask-resftul resource for returning the signed in user information."""
def get(self) -> Response:
"""GET response method for getting information on currently logged in user. JSON Web Token is required. :return: JSON object"""
<|body_0|>
def put(self)... | stack_v2_sparse_classes_36k_train_029564 | 7,554 | no_license | [
{
"docstring": "GET response method for getting information on currently logged in user. JSON Web Token is required. :return: JSON object",
"name": "get",
"signature": "def get(self) -> Response"
},
{
"docstring": "PUT response method for updating information on currently logged in user. JSON We... | 2 | stack_v2_sparse_classes_30k_train_003096 | Implement the Python class `SignedInUserApi` described below.
Class description:
Flask-resftul resource for returning the signed in user information.
Method signatures and docstrings:
- def get(self) -> Response: GET response method for getting information on currently logged in user. JSON Web Token is required. :ret... | Implement the Python class `SignedInUserApi` described below.
Class description:
Flask-resftul resource for returning the signed in user information.
Method signatures and docstrings:
- def get(self) -> Response: GET response method for getting information on currently logged in user. JSON Web Token is required. :ret... | 7f44c736c95866aaf820627ea54d3f00b3ada779 | <|skeleton|>
class SignedInUserApi:
"""Flask-resftul resource for returning the signed in user information."""
def get(self) -> Response:
"""GET response method for getting information on currently logged in user. JSON Web Token is required. :return: JSON object"""
<|body_0|>
def put(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignedInUserApi:
"""Flask-resftul resource for returning the signed in user information."""
def get(self) -> Response:
"""GET response method for getting information on currently logged in user. JSON Web Token is required. :return: JSON object"""
user = Users.objects().get(id=get_jwt_iden... | the_stack_v2_python_sparse | backend/uimpactify/controller/user.py | ObaidaSaleh/E-learning-app | train | 1 |
cc22f75d4e0322cdcdb4adaabfc03fe6919c7c46 | [
"costs.sort(key=lambda x: abs(x[0] - x[1]), reverse=True)\nab_cst = [0, 0]\nab_cnt = [0, 0]\nfor i, (a, b) in enumerate(costs):\n if abs(ab_cnt[0] - ab_cnt[1]) == len(costs) - i:\n if ab_cnt[0] < ab_cnt[1]:\n ab_cnt[0] += 1\n ab_cst[0] += a\n else:\n ab_cnt[1] += 1\... | <|body_start_0|>
costs.sort(key=lambda x: abs(x[0] - x[1]), reverse=True)
ab_cst = [0, 0]
ab_cnt = [0, 0]
for i, (a, b) in enumerate(costs):
if abs(ab_cnt[0] - ab_cnt[1]) == len(costs) - i:
if ab_cnt[0] < ab_cnt[1]:
ab_cnt[0] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""Sort by gap in descending order and assign each with the largest gap first"""
<|body_0|>
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""Simply sort by cost_a - cost_b and assign ea... | stack_v2_sparse_classes_36k_train_029565 | 2,963 | no_license | [
{
"docstring": "Sort by gap in descending order and assign each with the largest gap first",
"name": "twoCitySchedCost",
"signature": "def twoCitySchedCost(self, costs: List[List[int]]) -> int"
},
{
"docstring": "Simply sort by cost_a - cost_b and assign early half to go a and the others to B",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoCitySchedCost(self, costs: List[List[int]]) -> int: Sort by gap in descending order and assign each with the largest gap first
- def twoCitySchedCost(self, costs: List[Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoCitySchedCost(self, costs: List[List[int]]) -> int: Sort by gap in descending order and assign each with the largest gap first
- def twoCitySchedCost(self, costs: List[Lis... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""Sort by gap in descending order and assign each with the largest gap first"""
<|body_0|>
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""Simply sort by cost_a - cost_b and assign ea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
"""Sort by gap in descending order and assign each with the largest gap first"""
costs.sort(key=lambda x: abs(x[0] - x[1]), reverse=True)
ab_cst = [0, 0]
ab_cnt = [0, 0]
for i, (a, b) in enumerate(cost... | the_stack_v2_python_sparse | leetcode/solved/1095_Two_City_Scheduling/solution.py | sungminoh/algorithms | train | 0 | |
4397f7965cdb08030730406eb8f71aebd4559de9 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = MacOSTCCEntry()\nevent_data.allowed = self._GetRowValue(query_hash, row, 'allowed')\nevent_data.client = self._... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = MacOSTCCEntry()
eve... | SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.apple.TCC/TCC.db | MacOSTCCPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacOSTCCPlugin:
"""SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.apple.TCC/TCC.db"""
def _GetDateTimeR... | stack_v2_sparse_classes_36k_train_029566 | 5,334 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if not available.",
"name... | 2 | stack_v2_sparse_classes_30k_train_006004 | Implement the Python class `MacOSTCCPlugin` described below.
Class description:
SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.app... | Implement the Python class `MacOSTCCPlugin` described below.
Class description:
SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.app... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class MacOSTCCPlugin:
"""SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.apple.TCC/TCC.db"""
def _GetDateTimeR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacOSTCCPlugin:
"""SQLite parser plugin for MacOS TCC database files. The MacOS Transparency, Consent, Control (TCC) database file is typically stored in: /Library/Application Support/com.apple.TCC/TCC.db /Users/<username>/Library/Application Support/com.apple.TCC/TCC.db"""
def _GetDateTimeRowValue(self,... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/macos_tcc.py | log2timeline/plaso | train | 1,506 |
a635c9433a2fc54177c8f5a94edeaef0dddf5a3a | [
"msg = request.json\nif not msg:\n logger.debug(\"/testing-farm/results: we haven't received any JSON data.\")\n return (\"We haven't received any JSON data.\", HTTPStatus.BAD_REQUEST)\ntry:\n self.validate_testing_farm_request()\nexcept ValidationFailed as exc:\n logger.info(f'/testing-farm/results {ex... | <|body_start_0|>
msg = request.json
if not msg:
logger.debug("/testing-farm/results: we haven't received any JSON data.")
return ("We haven't received any JSON data.", HTTPStatus.BAD_REQUEST)
try:
self.validate_testing_farm_request()
except ValidationF... | TestingFarmResults | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestingFarmResults:
def post(self):
"""Submit Testing Farm results"""
<|body_0|>
def validate_testing_farm_request():
"""Validate testing farm token received in request with the one in packit-service.yaml :raises ValidationFailed"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_029567 | 4,956 | permissive | [
{
"docstring": "Submit Testing Farm results",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Validate testing farm token received in request with the one in packit-service.yaml :raises ValidationFailed",
"name": "validate_testing_farm_request",
"signature": "def validat... | 2 | stack_v2_sparse_classes_30k_train_020579 | Implement the Python class `TestingFarmResults` described below.
Class description:
Implement the TestingFarmResults class.
Method signatures and docstrings:
- def post(self): Submit Testing Farm results
- def validate_testing_farm_request(): Validate testing farm token received in request with the one in packit-serv... | Implement the Python class `TestingFarmResults` described below.
Class description:
Implement the TestingFarmResults class.
Method signatures and docstrings:
- def post(self): Submit Testing Farm results
- def validate_testing_farm_request(): Validate testing farm token received in request with the one in packit-serv... | 03f840cdfbcc129582a2ec2a20f069c85fea0c56 | <|skeleton|>
class TestingFarmResults:
def post(self):
"""Submit Testing Farm results"""
<|body_0|>
def validate_testing_farm_request():
"""Validate testing farm token received in request with the one in packit-service.yaml :raises ValidationFailed"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestingFarmResults:
def post(self):
"""Submit Testing Farm results"""
msg = request.json
if not msg:
logger.debug("/testing-farm/results: we haven't received any JSON data.")
return ("We haven't received any JSON data.", HTTPStatus.BAD_REQUEST)
try:
... | the_stack_v2_python_sparse | packit_service/service/api/testing_farm.py | FalseG0d/packit-service | train | 2 | |
fa99fd971c42bdde73b6655fd9a0fbe2edc415eb | [
"ret = ''\nlength1 = len(num1)\nlength2 = len(num2)\nif length1 < length2:\n short_s = num1\n long_s = num2\n length1 = length1\n length2 = length2\nelse:\n short_s = num2\n long_s = num1\n length1 = length2\n length2 = length1\ni = 1\ncarry = 0\nwhile i <= length1 or i <= length2:\n a = ... | <|body_start_0|>
ret = ''
length1 = len(num1)
length2 = len(num2)
if length1 < length2:
short_s = num1
long_s = num2
length1 = length1
length2 = length2
else:
short_s = num2
long_s = num1
length1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addStrings1(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = ''
... | stack_v2_sparse_classes_36k_train_029568 | 1,659 | no_license | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings1",
"signature": "def addStrings1(self, num1, num2)"
},
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "addStrings",
"signature": "def addStrings(self, num1, num2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings1(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addStrings1(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def addStrings(self, num1, num2): :type num1: str :type num2: str :rtype: str
<|skeleton|>
class... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def addStrings1(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def addStrings(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addStrings1(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
ret = ''
length1 = len(num1)
length2 = len(num2)
if length1 < length2:
short_s = num1
long_s = num2
length1 = length1
length2 =... | the_stack_v2_python_sparse | python/leetcode/415_Add_Strings.py | bobcaoge/my-code | train | 0 | |
9ff101a51354921862b04fdd826669daee7a7bd1 | [
"self.cfg = AutoCFG(self.__defaults).update_fields(kwargs)\nself.secret = secret\nself.logger = new_channel('tokenazer')",
"try:\n return jschema.apply(obj=art.unmarshal(data=cfb_decrypt(self.secret, data=data['d'], iv=data['i']), mask=(bytes((mask[i] ^ self.cfg.mask_1[i % len(self.cfg.mask_1)] for i in range(... | <|body_start_0|>
self.cfg = AutoCFG(self.__defaults).update_fields(kwargs)
self.secret = secret
self.logger = new_channel('tokenazer')
<|end_body_0|>
<|body_start_1|>
try:
return jschema.apply(obj=art.unmarshal(data=cfb_decrypt(self.secret, data=data['d'], iv=data['i']), mas... | This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 ) | Tokenazer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto k... | stack_v2_sparse_classes_36k_train_029569 | 5,190 | permissive | [
{
"docstring": "secret - secret key for crypto kwargs: mask_0 - bytes - extra secret (default: None) mask_1 - bytes - extra secret (default: None)",
"name": "__init__",
"signature": "def __init__(self, secret: bytes, **kwargs) -> None"
},
{
"docstring": ":rtype dict: decoded cookie as dict or No... | 4 | stack_v2_sparse_classes_30k_train_006350 | Implement the Python class `Tokenazer` described below.
Class description:
This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )
Method signatures and docstrings:
- def __init__(self, secret: b... | Implement the Python class `Tokenazer` described below.
Class description:
This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )
Method signatures and docstrings:
- def __init__(self, secret: b... | f8ca3a40c4bcb6c8d75d6e8a3ef796295b734be7 | <|skeleton|>
class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto kwargs: mask_0... | the_stack_v2_python_sparse | k2/tokenazer/tokenazer.py | moff4/k2 | train | 2 |
4161be37879990afbde90764f69d9ed3a2e2ee31 | [
"if cable not in ['straight', 'loopback']:\n raise ValueError(\"Cable can only be 'straight', or 'loopback'.\")\nsuper().__init__(mb_info, index, direction)\nself.cable = cable",
"if cable not in ['straight', 'loopback']:\n raise ValueError(\"Cable can only be 'straight', or 'loopback'.\")\nself.cable = cab... | <|body_start_0|>
if cable not in ['straight', 'loopback']:
raise ValueError("Cable can only be 'straight', or 'loopback'.")
super().__init__(mb_info, index, direction)
self.cable = cable
<|end_body_0|>
<|body_start_1|>
if cable not in ['straight', 'loopback']:
ra... | This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable. The default is a straight cable (no internal wire twisting). For pin mapping... | Pmod_Cable | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pmod_Cable:
"""This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable. The default is a straight cable (no in... | stack_v2_sparse_classes_36k_train_029570 | 3,844 | permissive | [
{
"docstring": "Return a new instance of a Cable object. Only the cable type is checked during initialization, since all the other parameters are checked by Pmod IO class. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. index: int The ind... | 3 | stack_v2_sparse_classes_30k_train_016838 | Implement the Python class `Pmod_Cable` described below.
Class description:
This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable.... | Implement the Python class `Pmod_Cable` described below.
Class description:
This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable.... | de6b6fc3a803945d59f8f06523addfe0d9b60a1c | <|skeleton|>
class Pmod_Cable:
"""This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable. The default is a straight cable (no in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pmod_Cable:
"""This class can be used for a cable connecting Pmod interfaces. This class inherits from the Pmod IO class. Note ---- When 2 Pmods are connected using a cable, the parameter 'cable' decides whether the cable is a 'loopback' or 'straight' cable. The default is a straight cable (no internal wire t... | the_stack_v2_python_sparse | pynq/lib/pmod/pmod_cable.py | schelleg/PYNQ | train | 1 |
b88304857ccb73407964fc8cad51c4417319b0dd | [
"logger.info('Combining sky')\nout = None\nfor f in in_filenames:\n try:\n small = DESDataImage.load(f)\n except (ValueError, IOError):\n logger.warning('SkyCombine could not load minisky ' + f)\n continue\n if small['DETPOS'].strip() in invalid:\n continue\n blocksize = smal... | <|body_start_0|>
logger.info('Combining sky')
out = None
for f in in_filenames:
try:
small = DESDataImage.load(f)
except (ValueError, IOError):
logger.warning('SkyCombine could not load minisky ' + f)
continue
if... | SkyCombine | [
"NCSA"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkyCombine:
def __call__(cls, in_filenames, out_filename, mask_value, invalid):
"""Produce compressed image of sky background for entire exposure by combining minisky FITS images for single CCDs. Missing input minisky will only generate a warning. :Parameters: - `in_filenames`: list of f... | stack_v2_sparse_classes_36k_train_029571 | 5,705 | permissive | [
{
"docstring": "Produce compressed image of sky background for entire exposure by combining minisky FITS images for single CCDs. Missing input minisky will only generate a warning. :Parameters: - `in_filenames`: list of filenames of single-chip sky images - `out_filename`: filename for the output combined sky i... | 3 | stack_v2_sparse_classes_30k_train_002517 | Implement the Python class `SkyCombine` described below.
Class description:
Implement the SkyCombine class.
Method signatures and docstrings:
- def __call__(cls, in_filenames, out_filename, mask_value, invalid): Produce compressed image of sky background for entire exposure by combining minisky FITS images for single... | Implement the Python class `SkyCombine` described below.
Class description:
Implement the SkyCombine class.
Method signatures and docstrings:
- def __call__(cls, in_filenames, out_filename, mask_value, invalid): Produce compressed image of sky background for entire exposure by combining minisky FITS images for single... | 8a299e9368d01cac51f53af6e4937e797f378d7a | <|skeleton|>
class SkyCombine:
def __call__(cls, in_filenames, out_filename, mask_value, invalid):
"""Produce compressed image of sky background for entire exposure by combining minisky FITS images for single CCDs. Missing input minisky will only generate a warning. :Parameters: - `in_filenames`: list of f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkyCombine:
def __call__(cls, in_filenames, out_filename, mask_value, invalid):
"""Produce compressed image of sky background for entire exposure by combining minisky FITS images for single CCDs. Missing input minisky will only generate a warning. :Parameters: - `in_filenames`: list of filenames of si... | the_stack_v2_python_sparse | python/pixcorrect/sky_combine.py | DarkEnergySurvey/pixcorrect | train | 1 | |
ba1f51320df86513a9be38a5284552e64010beff | [
"if not head or not head.next:\n return head\nlast_node = self.get_last_node(head)\nl1 = self.sort_list(head)\nl2 = self.sort_list(last_node)\nreturn self.merge(l1, l2)",
"fast = node\nslow = node\nbreak_node = node\nwhile fast and fast.next:\n fast = fast.next.next\n break_node = slow\n slow = slow.n... | <|body_start_0|>
if not head or not head.next:
return head
last_node = self.get_last_node(head)
l1 = self.sort_list(head)
l2 = self.sort_list(last_node)
return self.merge(l1, l2)
<|end_body_0|>
<|body_start_1|>
fast = node
slow = node
break_no... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
<|body_0|>
def get_last_node(self, node: ListNode) -> ListNode:
"""获取后部分节点 Args: node: node节点 Returns: 最后部分节点"""
<|body_1|>
def merge(self, l1: ListNode, ... | stack_v2_sparse_classes_36k_train_029572 | 2,630 | permissive | [
{
"docstring": "对链表进行排序 Args: head: 节点 Returns: 链表",
"name": "sort_list",
"signature": "def sort_list(self, head: ListNode) -> ListNode"
},
{
"docstring": "获取后部分节点 Args: node: node节点 Returns: 最后部分节点",
"name": "get_last_node",
"signature": "def get_last_node(self, node: ListNode) -> ListN... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort_list(self, head: ListNode) -> ListNode: 对链表进行排序 Args: head: 节点 Returns: 链表
- def get_last_node(self, node: ListNode) -> ListNode: 获取后部分节点 Args: node: node节点 Returns: 最后部... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort_list(self, head: ListNode) -> ListNode: 对链表进行排序 Args: head: 节点 Returns: 链表
- def get_last_node(self, node: ListNode) -> ListNode: 获取后部分节点 Args: node: node节点 Returns: 最后部... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
<|body_0|>
def get_last_node(self, node: ListNode) -> ListNode:
"""获取后部分节点 Args: node: node节点 Returns: 最后部分节点"""
<|body_1|>
def merge(self, l1: ListNode, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
if not head or not head.next:
return head
last_node = self.get_last_node(head)
l1 = self.sort_list(head)
l2 = self.sort_list(last_node)
return self.me... | the_stack_v2_python_sparse | src/leetcodepython/list/sort_list_148.py | zhangyu345293721/leetcode | train | 101 | |
2c7a2f6fce2db7430199f7c1f2fc22443153c657 | [
"threading.Thread.__init__(self)\nself.ip = ip\nself.port = port\nself.backlog = backlog\nself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n self.socket.bind((ip, port))\n self.socket.listen(self.backlog)\n print('open port', ip, port)\nexcept Exception as e:\n print('bind register|... | <|body_start_0|>
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.bind((ip, port))
self.socket.listen(self.backlog)
pri... | RegisterSocket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterSocket:
def __init__(self, ip, port, backlog, dbManager):
"""initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param model_id: str"""
<|body_0|>
def run(self):
"""listen to the port and receive the ... | stack_v2_sparse_classes_36k_train_029573 | 13,824 | no_license | [
{
"docstring": "initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param model_id: str",
"name": "__init__",
"signature": "def __init__(self, ip, port, backlog, dbManager)"
},
{
"docstring": "listen to the port and receive the data. The... | 2 | stack_v2_sparse_classes_30k_train_017354 | Implement the Python class `RegisterSocket` described below.
Class description:
Implement the RegisterSocket class.
Method signatures and docstrings:
- def __init__(self, ip, port, backlog, dbManager): initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param... | Implement the Python class `RegisterSocket` described below.
Class description:
Implement the RegisterSocket class.
Method signatures and docstrings:
- def __init__(self, ip, port, backlog, dbManager): initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param... | 9076a813c803bc9c47054fff7bae2824304da282 | <|skeleton|>
class RegisterSocket:
def __init__(self, ip, port, backlog, dbManager):
"""initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param model_id: str"""
<|body_0|>
def run(self):
"""listen to the port and receive the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterSocket:
def __init__(self, ip, port, backlog, dbManager):
"""initialize ModelSocket :param load_balancer: LoadBalancer :param ip: str :param port: int :param backlog: str :param model_id: str"""
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.... | the_stack_v2_python_sparse | old_code/entity.py | JaneWuNEU/hitdl_server | train | 0 | |
c3bb589e12f953acab1c2883791d9cce7d2703f6 | [
"self._domain = domain\nself._path = path or RequestBuilder.DEFAULT_PATH\nself._scheme = scheme or RequestBuilder.DEFAULT_SCHEME\nself._params = params or {}",
"params_string = RequestBuilder.QUERY_DELIM if self._params else ''\nparams_string += RequestBuilder.QUERY_KEY_VALUE_DELIM.join([RequestBuilder.QUERY_KEY_... | <|body_start_0|>
self._domain = domain
self._path = path or RequestBuilder.DEFAULT_PATH
self._scheme = scheme or RequestBuilder.DEFAULT_SCHEME
self._params = params or {}
<|end_body_0|>
<|body_start_1|>
params_string = RequestBuilder.QUERY_DELIM if self._params else ''
p... | Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component of the request (default: 'https'). :type _scheme: str :attr _params: The paramet... | RequestBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestBuilder:
"""Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component of the request (default: 'https'). :ty... | stack_v2_sparse_classes_36k_train_029574 | 1,956 | permissive | [
{
"docstring": "Initializes the `RequestBuilder` object. :param domain: The domain component of the request. :type domain: str :param path: The path component of the request (default: None). :type path: str :param scheme: The scheme component of the request (default: None). :type scheme: str :param params: The ... | 2 | stack_v2_sparse_classes_30k_train_009557 | Implement the Python class `RequestBuilder` described below.
Class description:
Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component... | Implement the Python class `RequestBuilder` described below.
Class description:
Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component... | 03c1acb2561cb85e62e791a81ecd624b6297c1c0 | <|skeleton|>
class RequestBuilder:
"""Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component of the request (default: 'https'). :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestBuilder:
"""Encapsulates Functionality for Building Web Requests. :attr _domain: The domain component of the request. :type _domain: str :attr _path: The path component of the request (default: ''). :type _path: str :attr _scheme: The scheme component of the request (default: 'https'). :type _scheme: s... | the_stack_v2_python_sparse | code_complete/code_snippet_providers/utils/request_builder.py | berjc/code-complete | train | 1 |
041d858ee08c418eb48215abc95cf8e83e8c30cb | [
"try:\n log.info('%s %r' % (request.remote_addr, request))\n response = []\n if len(request.args) > 0:\n persons = ModelOperations.person_filter(request)\n else:\n persons = ModelOperations.person_list()\n if not persons:\n return jsonify(persons=response)\n response =... | <|body_start_0|>
try:
log.info('%s %r' % (request.remote_addr, request))
response = []
if len(request.args) > 0:
persons = ModelOperations.person_filter(request)
else:
persons = ModelOperations.person_list()
if not p... | Gets lists of persons. | PersonList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonList:
"""Gets lists of persons."""
def get(self):
""":return:"""
<|body_0|>
def post(self):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
log.info('%s %r' % (request.remote_addr, request))
respons... | stack_v2_sparse_classes_36k_train_029575 | 23,973 | permissive | [
{
"docstring": ":return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": ":return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009498 | Implement the Python class `PersonList` described below.
Class description:
Gets lists of persons.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): :return: | Implement the Python class `PersonList` described below.
Class description:
Gets lists of persons.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): :return:
<|skeleton|>
class PersonList:
"""Gets lists of persons."""
def get(self):
""":return:"""
<|body_0|>
... | c27812e6b846eb1e28ec0c6e8508e18886e37617 | <|skeleton|>
class PersonList:
"""Gets lists of persons."""
def get(self):
""":return:"""
<|body_0|>
def post(self):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonList:
"""Gets lists of persons."""
def get(self):
""":return:"""
try:
log.info('%s %r' % (request.remote_addr, request))
response = []
if len(request.args) > 0:
persons = ModelOperations.person_filter(request)
else:
... | the_stack_v2_python_sparse | api/version1_0/application/api_main.py | gogasca/news_ml | train | 4 |
a85ab38296b6a13eb9a8a1e01035c714b002fb7a | [
"for attribut in self.composant.items():\n fonction = _attribut_vevent.get(str(attribut[0]), None)\n if fonction is not None:\n fonction(self, attribut)\n else:\n self.informations[str(attribut[0])] = self.composant.decoded(str(attribut[0]))",
"creneau = self.agenda.ajouterCreneau(self.anne... | <|body_start_0|>
for attribut in self.composant.items():
fonction = _attribut_vevent.get(str(attribut[0]), None)
if fonction is not None:
fonction(self, attribut)
else:
self.informations[str(attribut[0])] = self.composant.decoded(str(attribut[0... | La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de debut lue @ivar fin: l'heure de fin lue @ivar agenda: l'agenda cible @ivar com... | VeventParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VeventParser:
"""La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de debut lue @ivar fin: l'heure de fin lu... | stack_v2_sparse_classes_36k_train_029576 | 5,156 | no_license | [
{
"docstring": "Lance la lecture du composant, et remplis les champs. @param self: L'argument implicite.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Crée le creneau et le rempli correctement. @param self: L'argument implicite. @raise ValueError: en cas d'une insertion qu... | 3 | stack_v2_sparse_classes_30k_train_001596 | Implement the Python class `VeventParser` described below.
Class description:
La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de... | Implement the Python class `VeventParser` described below.
Class description:
La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de... | cfb10131abde3ec8f51e9dcd84003c3230516e18 | <|skeleton|>
class VeventParser:
"""La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de debut lue @ivar fin: l'heure de fin lu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VeventParser:
"""La classe conteneur chargée de récupérer les informations d'un Vevent dans le but de créer et remplir un Creneau par la suite. @ivar annee: l'annee lue @ivar mois: le mois lu @ivar jour: le jour lu @ivar uid: l'uid lu @ivar debut: l'heure de debut lue @ivar fin: l'heure de fin lue @ivar agend... | the_stack_v2_python_sparse | organizer/src/modele/agenda/importations/_veventIcs.py | Lbardoux/TER_2016_organizer | train | 1 |
471e6f631a8bedd641e85606480434d03b76f321 | [
"n_row = len(matrix)\nn_col = len(matrix[0])\nmat = []\nfor i in range(n_row):\n r = []\n for j in range(n_col):\n r.append(int(matrix[i][j]))\n mat.append(r)\nheights = mat[0]\nres = self.largestRectangleArea(heights)\nfor i in range(1, n_row):\n new_height = mat[i]\n heights = [heights[j] + ... | <|body_start_0|>
n_row = len(matrix)
n_col = len(matrix[0])
mat = []
for i in range(n_row):
r = []
for j in range(n_col):
r.append(int(matrix[i][j]))
mat.append(r)
heights = mat[0]
res = self.largestRectangleArea(heights... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n_row = len(mat... | stack_v2_sparse_classes_36k_train_029577 | 1,336 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
class ... | ca8b2662330776d14962532ed8994dfeedadef70 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
n_row = len(matrix)
n_col = len(matrix[0])
mat = []
for i in range(n_row):
r = []
for j in range(n_col):
r.append(int(matrix[i][j]))
... | the_stack_v2_python_sparse | Algo/Leetcode/085MaxRectangle.py | lawy623/Algorithm_Interview_Prep | train | 2 | |
46e1b6040e5c41d9cd5760ec9902fce4a5acda80 | [
"if not self.username:\n raise RuntimeError('Please supply a valid user name.')\nif self.use_tsk:\n self.path_type = rdfvalue.PathSpec.PathType.TSK\nelse:\n self.path_type = rdfvalue.PathSpec.PathType.OS\nclient = aff4.FACTORY.Open(self.client_id, token=self.token)\nself.user_pb = flow_utils.GetUserInfo(cl... | <|body_start_0|>
if not self.username:
raise RuntimeError('Please supply a valid user name.')
if self.use_tsk:
self.path_type = rdfvalue.PathSpec.PathType.TSK
else:
self.path_type = rdfvalue.PathSpec.PathType.OS
client = aff4.FACTORY.Open(self.client_i... | Do the initial work for a user investigation. | WinUserActivityInvestigation | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each flow finishing."""
... | stack_v2_sparse_classes_36k_train_029578 | 10,734 | permissive | [
{
"docstring": "Validate parameters and do the actual work.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Complete anything we need to do for each flow finishing.",
"name": "FinishFlow",
"signature": "def FinishFlow(self, responses)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020848 | Implement the Python class `WinUserActivityInvestigation` described below.
Class description:
Do the initial work for a user investigation.
Method signatures and docstrings:
- def Start(self): Validate parameters and do the actual work.
- def FinishFlow(self, responses): Complete anything we need to do for each flow ... | Implement the Python class `WinUserActivityInvestigation` described below.
Class description:
Do the initial work for a user investigation.
Method signatures and docstrings:
- def Start(self): Validate parameters and do the actual work.
- def FinishFlow(self, responses): Complete anything we need to do for each flow ... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each flow finishing."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WinUserActivityInvestigation:
"""Do the initial work for a user investigation."""
def Start(self):
"""Validate parameters and do the actual work."""
if not self.username:
raise RuntimeError('Please supply a valid user name.')
if self.use_tsk:
self.path_type... | the_stack_v2_python_sparse | lib/flows/general/automation.py | defaultnamehere/grr | train | 3 |
fd07364b1590a2ca32e76c5871c8f70410c7c633 | [
"self.total = 0\nself.size = size\nself.queue = []",
"if len(self.queue) >= self.size:\n out = self.queue.pop(0)\n self.total -= out\nself.queue.append(val)\nself.total += val\nreturn self.total / len(self.queue)"
] | <|body_start_0|>
self.total = 0
self.size = size
self.queue = []
<|end_body_0|>
<|body_start_1|>
if len(self.queue) >= self.size:
out = self.queue.pop(0)
self.total -= out
self.queue.append(val)
self.total += val
return self.total / len(se... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
<|body_0|>
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到tot... | stack_v2_sparse_classes_36k_train_029579 | 1,545 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self, size: int)"
},
{
"docstring": "如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到total, 除以当前size即使平均数",
"nam... | 2 | stack_v2_sparse_classes_30k_train_013746 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Initialize your data structure here.
- def next(self, val: int) -> float: 如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大... | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Initialize your data structure here.
- def next(self, val: int) -> float: 如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大... | 034efcefe9940267abcf4c9cab655b2344e3e901 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
<|body_0|>
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的数字,此操作为O(1) 再把当前数字val 放到queue里,并且加入到tot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size: int):
"""Initialize your data structure here."""
self.total = 0
self.size = size
self.queue = []
def next(self, val: int) -> float:
"""如果当前的size超过了初始size, 即弹出第一个数字 queue.pop(0), 这样queue总保持初始size-1的大小。 保持一个窗口里,因此total要减去pop出来的... | the_stack_v2_python_sparse | 346_moving_average_from_data_stream.py | HongsenHe/algo2018 | train | 0 | |
97ff6f91fd2202e87bbf9d0d1f08b340b27f2fa8 | [
"_params = dict()\nmsg = dict(type='Subnets', request='AllZones', version=5, params=_params)\nreply = await self.rpc(msg)\nreturn reply",
"if space_tag is not None and (not isinstance(space_tag, (bytes, str))):\n raise Exception('Expected space_tag to be a str, received: {}'.format(type(space_tag)))\nif zone i... | <|body_start_0|>
_params = dict()
msg = dict(type='Subnets', request='AllZones', version=5, params=_params)
reply = await self.rpc(msg)
return reply
<|end_body_0|>
<|body_start_1|>
if space_tag is not None and (not isinstance(space_tag, (bytes, str))):
raise Exceptio... | SubnetsFacade | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubnetsFacade:
async def AllZones(self):
"""AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults"""
<|body_0|>
async def ListSubnets(self, space_tag=None, zone=None)... | stack_v2_sparse_classes_36k_train_029580 | 41,639 | permissive | [
{
"docstring": "AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults",
"name": "AllZones",
"signature": "async def AllZones(self)"
},
{
"docstring": "ListSubnets returns the matching sub... | 3 | stack_v2_sparse_classes_30k_train_011834 | Implement the Python class `SubnetsFacade` described below.
Class description:
Implement the SubnetsFacade class.
Method signatures and docstrings:
- async def AllZones(self): AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Re... | Implement the Python class `SubnetsFacade` described below.
Class description:
Implement the SubnetsFacade class.
Method signatures and docstrings:
- async def AllZones(self): AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Re... | f21bc426952579efb980439f6a07d59bcb4cce0b | <|skeleton|>
class SubnetsFacade:
async def AllZones(self):
"""AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults"""
<|body_0|>
async def ListSubnets(self, space_tag=None, zone=None)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubnetsFacade:
async def AllZones(self):
"""AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults"""
_params = dict()
msg = dict(type='Subnets', request='AllZones', version=5, p... | the_stack_v2_python_sparse | juju/client/_client5.py | juju/python-libjuju | train | 63 | |
0cf1cb9a338cd5383b6517e138ec2ae033a02419 | [
"cubelist, self.cycletime = set_up_masked_cubes()\nmerger = MergeCubesForWeightedBlending('model_id', weighting_coord='forecast_period', model_id_attr='mosg__model_configuration')\nself.cube = merger.process(cubelist)\nself.plugin = WeightAndBlend('model_id', 'dict', weighting_coord='forecast_period', wts_dict=MODE... | <|body_start_0|>
cubelist, self.cycletime = set_up_masked_cubes()
merger = MergeCubesForWeightedBlending('model_id', weighting_coord='forecast_period', model_id_attr='mosg__model_configuration')
self.cube = merger.process(cubelist)
self.plugin = WeightAndBlend('model_id', 'dict', weighti... | Test the _update_spatial_weights method | Test__update_spatial_weights | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__update_spatial_weights:
"""Test the _update_spatial_weights method"""
def setUp(self):
"""Set up cube and plugin"""
<|body_0|>
def test_basic(self):
"""Test function returns a cube of the expected shape"""
<|body_1|>
def test_values(self):
... | stack_v2_sparse_classes_36k_train_029581 | 30,096 | permissive | [
{
"docstring": "Set up cube and plugin",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test function returns a cube of the expected shape",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test weights are fuzzified as expected",
... | 3 | null | Implement the Python class `Test__update_spatial_weights` described below.
Class description:
Test the _update_spatial_weights method
Method signatures and docstrings:
- def setUp(self): Set up cube and plugin
- def test_basic(self): Test function returns a cube of the expected shape
- def test_values(self): Test wei... | Implement the Python class `Test__update_spatial_weights` described below.
Class description:
Test the _update_spatial_weights method
Method signatures and docstrings:
- def setUp(self): Set up cube and plugin
- def test_basic(self): Test function returns a cube of the expected shape
- def test_values(self): Test wei... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__update_spatial_weights:
"""Test the _update_spatial_weights method"""
def setUp(self):
"""Set up cube and plugin"""
<|body_0|>
def test_basic(self):
"""Test function returns a cube of the expected shape"""
<|body_1|>
def test_values(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__update_spatial_weights:
"""Test the _update_spatial_weights method"""
def setUp(self):
"""Set up cube and plugin"""
cubelist, self.cycletime = set_up_masked_cubes()
merger = MergeCubesForWeightedBlending('model_id', weighting_coord='forecast_period', model_id_attr='mosg__mod... | the_stack_v2_python_sparse | improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py | metoppv/improver | train | 101 |
cd158c50b42891ccd3e00f861ee1759408e151e5 | [
"self.cumul_area = [0]\nself.x_dimensions = [0]\nself.rects = rects\nfor x1, y1, x2, y2 in rects:\n x_dim, y_dim = (x2 - x1 + 1, y2 - y1 + 1)\n self.x_dimensions.append(x_dim)\n self.cumul_area.append(self.cumul_area[-1] + x_dim * y_dim)",
"n = random.randint(1, self.cumul_area[-1])\ni = bisect.bisect_le... | <|body_start_0|>
self.cumul_area = [0]
self.x_dimensions = [0]
self.rects = rects
for x1, y1, x2, y2 in rects:
x_dim, y_dim = (x2 - x1 + 1, y2 - y1 + 1)
self.x_dimensions.append(x_dim)
self.cumul_area.append(self.cumul_area[-1] + x_dim * y_dim)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cumul_area = [0]
self.x_dimensions = [0]
self.rects = rects
... | stack_v2_sparse_classes_36k_train_029582 | 2,027 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001733 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.cumul_area = [0]
self.x_dimensions = [0]
self.rects = rects
for x1, y1, x2, y2 in rects:
x_dim, y_dim = (x2 - x1 + 1, y2 - y1 + 1)
self.x_dimensions.append(x_dim)
... | the_stack_v2_python_sparse | python_1_to_1000/497_Random_Point_in_Non-overlapping_Rectangles.py | jakehoare/leetcode | train | 58 | |
2d3d5876c555493ea999e2cd9f2caf2c9fa7fc9c | [
"a = 100\nb = 96\nstrand = '+'\nassert talon.compute_delta(a, b, strand) == -4",
"a = 96\nb = 100\nstrand = '+'\nassert talon.compute_delta(a, b, strand) == 4",
"a = 96\nb = 100\nstrand = '-'\nassert talon.compute_delta(a, b, strand) == -4",
"a = 100\nb = 96\nstrand = '-'\nassert talon.compute_delta(a, b, str... | <|body_start_0|>
a = 100
b = 96
strand = '+'
assert talon.compute_delta(a, b, strand) == -4
<|end_body_0|>
<|body_start_1|>
a = 96
b = 100
strand = '+'
assert talon.compute_delta(a, b, strand) == 4
<|end_body_1|>
<|body_start_2|>
a = 96
b... | TestComputeDelta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestComputeDelta:
def test_1(self):
"""Plus-strand upstream"""
<|body_0|>
def test_2(self):
"""Plus-strand downstream"""
<|body_1|>
def test_3(self):
"""Minus-strand upstream"""
<|body_2|>
def test_4(self):
"""Minus-strand do... | stack_v2_sparse_classes_36k_train_029583 | 794 | permissive | [
{
"docstring": "Plus-strand upstream",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "Plus-strand downstream",
"name": "test_2",
"signature": "def test_2(self)"
},
{
"docstring": "Minus-strand upstream",
"name": "test_3",
"signature": "def test_3(sel... | 4 | stack_v2_sparse_classes_30k_train_005351 | Implement the Python class `TestComputeDelta` described below.
Class description:
Implement the TestComputeDelta class.
Method signatures and docstrings:
- def test_1(self): Plus-strand upstream
- def test_2(self): Plus-strand downstream
- def test_3(self): Minus-strand upstream
- def test_4(self): Minus-strand downs... | Implement the Python class `TestComputeDelta` described below.
Class description:
Implement the TestComputeDelta class.
Method signatures and docstrings:
- def test_1(self): Plus-strand upstream
- def test_2(self): Plus-strand downstream
- def test_3(self): Minus-strand upstream
- def test_4(self): Minus-strand downs... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestComputeDelta:
def test_1(self):
"""Plus-strand upstream"""
<|body_0|>
def test_2(self):
"""Plus-strand downstream"""
<|body_1|>
def test_3(self):
"""Minus-strand upstream"""
<|body_2|>
def test_4(self):
"""Minus-strand do... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestComputeDelta:
def test_1(self):
"""Plus-strand upstream"""
a = 100
b = 96
strand = '+'
assert talon.compute_delta(a, b, strand) == -4
def test_2(self):
"""Plus-strand downstream"""
a = 96
b = 100
strand = '+'
assert talon... | the_stack_v2_python_sparse | testing_suite/test_compute_delta.py | kopardev/TALON | train | 0 | |
b72592d05f7acb19c1a272189dd6789d3f4d890a | [
"try:\n with open(yaml_file_path, 'r') as f:\n self.doc = yaml.load(f)\nexcept Exception as ex:\n message = 'Exception: An exception occured: {}'.format(ex)\n raise Exception(message)",
"param_value = self.doc[appliance][param]\nif param_value == '':\n message = 'Value is not updated for the pa... | <|body_start_0|>
try:
with open(yaml_file_path, 'r') as f:
self.doc = yaml.load(f)
except Exception as ex:
message = 'Exception: An exception occured: {}'.format(ex)
raise Exception(message)
<|end_body_0|>
<|body_start_1|>
param_value = self.d... | GetYamlValue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetYamlValue:
def __init__(self, yaml_file_path=yaml_path):
""":param yaml_file_path: Path of yaml file, Default will the config.yaml file"""
<|body_0|>
def get_config(self, appliance, param):
"""This function gives the yaml value corresponding to the parameter sampl... | stack_v2_sparse_classes_36k_train_029584 | 1,425 | no_license | [
{
"docstring": ":param yaml_file_path: Path of yaml file, Default will the config.yaml file",
"name": "__init__",
"signature": "def __init__(self, yaml_file_path=yaml_path)"
},
{
"docstring": "This function gives the yaml value corresponding to the parameter sample Yaml file xstream_details: xtm... | 2 | stack_v2_sparse_classes_30k_train_011710 | Implement the Python class `GetYamlValue` described below.
Class description:
Implement the GetYamlValue class.
Method signatures and docstrings:
- def __init__(self, yaml_file_path=yaml_path): :param yaml_file_path: Path of yaml file, Default will the config.yaml file
- def get_config(self, appliance, param): This f... | Implement the Python class `GetYamlValue` described below.
Class description:
Implement the GetYamlValue class.
Method signatures and docstrings:
- def __init__(self, yaml_file_path=yaml_path): :param yaml_file_path: Path of yaml file, Default will the config.yaml file
- def get_config(self, appliance, param): This f... | 93dd6d14ae4b0856aa7c6f059904cc1f13800e5f | <|skeleton|>
class GetYamlValue:
def __init__(self, yaml_file_path=yaml_path):
""":param yaml_file_path: Path of yaml file, Default will the config.yaml file"""
<|body_0|>
def get_config(self, appliance, param):
"""This function gives the yaml value corresponding to the parameter sampl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetYamlValue:
def __init__(self, yaml_file_path=yaml_path):
""":param yaml_file_path: Path of yaml file, Default will the config.yaml file"""
try:
with open(yaml_file_path, 'r') as f:
self.doc = yaml.load(f)
except Exception as ex:
message = 'Exc... | the_stack_v2_python_sparse | automation_framework/utils/GetYamlValue.py | vijaymaddukuri/python_repo | train | 0 | |
473ef5e38ce09f0898baf040f4761e2d402662b4 | [
"urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\ndownload_file_name.parent.mkdir(parents=True, exist_ok=True)\nresponse = requests.get(file_url, verify=verify, timeout=settings.REQUESTS_DEFAULT_TIMOUT)\nif response.status_code == 200:\n file_contents = response.content\nelse:\n raise Exce... | <|body_start_0|>
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
download_file_name.parent.mkdir(parents=True, exist_ok=True)
response = requests.get(file_url, verify=verify, timeout=settings.REQUESTS_DEFAULT_TIMOUT)
if response.status_code == 200:
file_co... | A simple class to encapsulate the download capabilities of the application | Downloader | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Downloader:
"""A simple class to encapsulate the download capabilities of the application"""
def download_file_from_url(cls, file_url: str, download_file_name: Path, verify: bool=True) -> str:
"""Downloads a file from a remote URL location and returns the file location. Args: file_ur... | stack_v2_sparse_classes_36k_train_029585 | 3,010 | permissive | [
{
"docstring": "Downloads a file from a remote URL location and returns the file location. Args: file_url (str): URL where the zip file is located download_file_name (pathlib.Path): file path where the file will be downloaded (called downloaded.zip by default) verify (bool): A flag to check if the certificate i... | 2 | stack_v2_sparse_classes_30k_train_004439 | Implement the Python class `Downloader` described below.
Class description:
A simple class to encapsulate the download capabilities of the application
Method signatures and docstrings:
- def download_file_from_url(cls, file_url: str, download_file_name: Path, verify: bool=True) -> str: Downloads a file from a remote ... | Implement the Python class `Downloader` described below.
Class description:
A simple class to encapsulate the download capabilities of the application
Method signatures and docstrings:
- def download_file_from_url(cls, file_url: str, download_file_name: Path, verify: bool=True) -> str: Downloads a file from a remote ... | 980ed8f04a83b683bf146dfdb1ca8e5906c2f55d | <|skeleton|>
class Downloader:
"""A simple class to encapsulate the download capabilities of the application"""
def download_file_from_url(cls, file_url: str, download_file_name: Path, verify: bool=True) -> str:
"""Downloads a file from a remote URL location and returns the file location. Args: file_ur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Downloader:
"""A simple class to encapsulate the download capabilities of the application"""
def download_file_from_url(cls, file_url: str, download_file_name: Path, verify: bool=True) -> str:
"""Downloads a file from a remote URL location and returns the file location. Args: file_url (str): URL ... | the_stack_v2_python_sparse | data/data-pipeline/data_pipeline/etl/downloader.py | GeoPlatform/justice40-tool | train | 0 |
f1085f89e86d6e5416562b00883d826215a27b5d | [
"try:\n payment = Payments()\n payment.find(filters)\n app.logger.info(f'Se encontro el complemento {str(payment._id)}')\n return payment\nexcept Exception as e:\n print('ERROR in repo', e)\n app.logger.error(e)\n return None",
"try:\n payments = Payments.find_all(filters)\n app.logger.... | <|body_start_0|>
try:
payment = Payments()
payment.find(filters)
app.logger.info(f'Se encontro el complemento {str(payment._id)}')
return payment
except Exception as e:
print('ERROR in repo', e)
app.logger.error(e)
retur... | PaymentsMongoRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentsMongoRepository:
def get_one(self, filters: dict) -> dict:
"""Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de busqueda :return: diccionario con el documento encontrado."""
<|body_0|>
def get_all(self, filters:... | stack_v2_sparse_classes_36k_train_029586 | 1,702 | no_license | [
{
"docstring": "Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de busqueda :return: diccionario con el documento encontrado.",
"name": "get_one",
"signature": "def get_one(self, filters: dict) -> dict"
},
{
"docstring": "Busca los complemen... | 3 | stack_v2_sparse_classes_30k_val_001028 | Implement the Python class `PaymentsMongoRepository` described below.
Class description:
Implement the PaymentsMongoRepository class.
Method signatures and docstrings:
- def get_one(self, filters: dict) -> dict: Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de ... | Implement the Python class `PaymentsMongoRepository` described below.
Class description:
Implement the PaymentsMongoRepository class.
Method signatures and docstrings:
- def get_one(self, filters: dict) -> dict: Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de ... | 071ca3bdddafe591e4edef11bd52172cf62f3339 | <|skeleton|>
class PaymentsMongoRepository:
def get_one(self, filters: dict) -> dict:
"""Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de busqueda :return: diccionario con el documento encontrado."""
<|body_0|>
def get_all(self, filters:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaymentsMongoRepository:
def get_one(self, filters: dict) -> dict:
"""Busca el datos del complemento de pago en la base de datos :param filters: diccionario con los filtros de busqueda :return: diccionario con el documento encontrado."""
try:
payment = Payments()
paymen... | the_stack_v2_python_sparse | app/repository/payments_repository.py | trevino-676/catalog-service | train | 0 | |
5bc84827bca4bd76e35b97303e9d5506edc8d614 | [
"QGraphicsRectItem.__init__(self)\nself.parentWidget = parent\nif sys.version_info > (3,):\n if isinstance(name, bytes):\n name = str(name, 'utf8', errors='ignore')\nself.label = QGraphicsTextItem(name, self)\nself.setColor(blockColor='#FFFFFF')\nself.changeSize(width, height)",
"color = QColor(0, 0, 0)... | <|body_start_0|>
QGraphicsRectItem.__init__(self)
self.parentWidget = parent
if sys.version_info > (3,):
if isinstance(name, bytes):
name = str(name, 'utf8', errors='ignore')
self.label = QGraphicsTextItem(name, self)
self.setColor(blockColor='#FFFFFF'... | Represents a block in the diagram | TimestampItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimestampItem:
"""Represents a block in the diagram"""
def __init__(self, parent, name='Untitled', width=180, height=40):
"""Constructor"""
<|body_0|>
def setColor(self, blockColor):
"""Set color"""
<|body_1|>
def changeSize(self, w, h):
"""R... | stack_v2_sparse_classes_36k_train_029587 | 9,630 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent, name='Untitled', width=180, height=40)"
},
{
"docstring": "Set color",
"name": "setColor",
"signature": "def setColor(self, blockColor)"
},
{
"docstring": "Resize block function",
"name... | 3 | null | Implement the Python class `TimestampItem` described below.
Class description:
Represents a block in the diagram
Method signatures and docstrings:
- def __init__(self, parent, name='Untitled', width=180, height=40): Constructor
- def setColor(self, blockColor): Set color
- def changeSize(self, w, h): Resize block fun... | Implement the Python class `TimestampItem` described below.
Class description:
Represents a block in the diagram
Method signatures and docstrings:
- def __init__(self, parent, name='Untitled', width=180, height=40): Constructor
- def setColor(self, blockColor): Set color
- def changeSize(self, w, h): Resize block fun... | 66f65dd6e4a48909120f63239f630147c733df3f | <|skeleton|>
class TimestampItem:
"""Represents a block in the diagram"""
def __init__(self, parent, name='Untitled', width=180, height=40):
"""Constructor"""
<|body_0|>
def setColor(self, blockColor):
"""Set color"""
<|body_1|>
def changeSize(self, w, h):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimestampItem:
"""Represents a block in the diagram"""
def __init__(self, parent, name='Untitled', width=180, height=40):
"""Constructor"""
QGraphicsRectItem.__init__(self)
self.parentWidget = parent
if sys.version_info > (3,):
if isinstance(name, bytes):
... | the_stack_v2_python_sparse | TestResults/GraphView.py | ExtensiveAutomation/extensiveautomation-appclient | train | 2 |
4f4f530cda1eff18842990d24468d879711a7aa1 | [
"self.input_type = input_type\nif input_type == 'file':\n self.cap = cv2.VideoCapture(file_path)\nelse:\n self.cap = cv2.VideoCapture(0)\n ret, frame = self.cap.read()\ncascPath = configuration.MODEL_PATH + 'haarcascade_frontalface_alt.xml'\nself.faceCascade = cv2.CascadeClassifier(cascPath)\nself.file_nam... | <|body_start_0|>
self.input_type = input_type
if input_type == 'file':
self.cap = cv2.VideoCapture(file_path)
else:
self.cap = cv2.VideoCapture(0)
ret, frame = self.cap.read()
cascPath = configuration.MODEL_PATH + 'haarcascade_frontalface_alt.xml'
... | This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the faces for predicting the emotion, we used... | FaceReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the fac... | stack_v2_sparse_classes_36k_train_029588 | 16,328 | permissive | [
{
"docstring": "Arguments: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the defalt camera.",
"name": "__init__",
"signature": "def __init__(self, input_type, file_path=None)"
},
{
"docstring": "delete files for releasing the resourse.",
"name... | 5 | stack_v2_sparse_classes_30k_train_015107 | Implement the Python class `FaceReader` described below.
Class description:
This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save ... | Implement the Python class `FaceReader` described below.
Class description:
This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save ... | 531f646dcb493dce2575af3b9d77403ebc1f4a35 | <|skeleton|>
class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the fac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the faces for predic... | the_stack_v2_python_sparse | MindLink-Eumpy/real_time_detection/GUI/MLE_tool/tool.py | wozu-dichter/MindLink-Explorer | train | 0 |
3d443c5e9282820a05a1b4e7f121362d843983e1 | [
"test = '4 4 0\\n2 1 2'\nd = Spheres(test)\nself.assertEqual(d.numa, [4, 4, 0])\nself.assertEqual(d.numb, [2, 1, 2])\nself.assertEqual(d.delta, [2, 3, -2])\nself.assertEqual(Spheres(test).calculate(), 'Yes')\ntest = '5 6 1\\n2 7 2'\nself.assertEqual(Spheres(test).calculate(), 'No')\ntest = '3 3 3\\n2 2 2'\nself.ass... | <|body_start_0|>
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEqual(d.numa, [4, 4, 0])
self.assertEqual(d.numb, [2, 1, 2])
self.assertEqual(d.delta, [2, 3, -2])
self.assertEqual(Spheres(test).calculate(), 'Yes')
test = '5 6 1\n2 7 2'
self.assertEqual... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Spheres class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEq... | stack_v2_sparse_classes_36k_train_029589 | 3,011 | permissive | [
{
"docstring": "Spheres class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010475 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Spheres class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Spheres class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Spheres class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Spheres class testing"""
test = '4 4 0\n2 1 2'
d = Spheres(test)
self.assertEqual(d.numa, [4, 4, 0])
self.assertEqual(d.numb, [2, 1, 2])
self.assertEqual(d.delta, [2, 3, -2])
self.assertEqual(Spheres(test).calcul... | the_stack_v2_python_sparse | codeforces/606A_spheres.py | snsokolov/contests | train | 1 | |
f95a8f37625b9e45cdc81de925493852f2715915 | [
"if base_path == '/v1/reflect/me':\n return self._reflect_request(base_path, url_args, body_args)\nmatch = self.SRV_QUERY_REGEXP.search(base_path)\nif match:\n return self.__srv_permissions_request_handler(match.group(1))\nraise EndpointException(code=500, content='Path `{}` is not supported yet'.format(base_... | <|body_start_0|>
if base_path == '/v1/reflect/me':
return self._reflect_request(base_path, url_args, body_args)
match = self.SRV_QUERY_REGEXP.search(base_path)
if match:
return self.__srv_permissions_request_handler(match.group(1))
raise EndpointException(code=500... | Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services. | MesosDnsHTTPRequestHandler | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-oracle-bcl-javase-javafx-2012",
"ErlPL-1.1",
"MPL-2.0",
"ISC",
"BSL-1.0",
"Python-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for gi... | stack_v2_sparse_classes_36k_train_029590 | 5,228 | permissive | [
{
"docstring": "Reply with the currently set mock-reply for given SRV record query. Please refer to the description of the BaseHTTPRequestHandler class for details on the arguments and return value of this method. Raises: EndpointException: request URL path is unsupported",
"name": "_calculate_response",
... | 2 | stack_v2_sparse_classes_30k_train_004788 | Implement the Python class `MesosDnsHTTPRequestHandler` described below.
Class description:
Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services.
Method signatures and docstrings:
- def _calculate_response(self, base_path, url_args, body_a... | Implement the Python class `MesosDnsHTTPRequestHandler` described below.
Class description:
Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services.
Method signatures and docstrings:
- def _calculate_response(self, base_path, url_args, body_a... | 79b9a39b4e639dc2c9435a869918399b50bfaf24 | <|skeleton|>
class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for gi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MesosDnsHTTPRequestHandler:
"""Request handler that mimics MesosDNS Depending on how it was set up, it will respond with different SRV entries for preset services."""
def _calculate_response(self, base_path, url_args, body_args=None):
"""Reply with the currently set mock-reply for given SRV recor... | the_stack_v2_python_sparse | packages/adminrouter/extra/src/test-harness/modules/mocker/endpoints/mesos_dns.py | dcos/dcos | train | 2,613 |
49f4eec9640e646abebd770fe5edc1a18592bdb0 | [
"extension = os.path.splitext(data_file)[-1]\nif extension == '.json':\n self.vocab_set = set(json.load(open(data_file)))\nelif extension == '.csv':\n self.vocab_df = pd.read_csv(data_file).set_index('WORD')\n self.vocab_set = set(self.vocab_df.index)\nelse:\n print('Only Json/CSV file extension support... | <|body_start_0|>
extension = os.path.splitext(data_file)[-1]
if extension == '.json':
self.vocab_set = set(json.load(open(data_file)))
elif extension == '.csv':
self.vocab_df = pd.read_csv(data_file).set_index('WORD')
self.vocab_set = set(self.vocab_df.index)
... | Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc | VocabSanitizer | [
"CC-BY-4.0",
"CC-BY-SA-3.0",
"CC-BY-SA-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VocabSanitizer:
"""Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc"""
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
<|body_0|>
def remove_astray(self, word_list):
"""Remove words tha... | stack_v2_sparse_classes_36k_train_029591 | 23,078 | permissive | [
{
"docstring": "data_file: path to file conatining vocabulary list",
"name": "__init__",
"signature": "def __init__(self, data_file)"
},
{
"docstring": "Remove words that are not present in vocabulary",
"name": "remove_astray",
"signature": "def remove_astray(self, word_list)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_001917 | Implement the Python class `VocabSanitizer` described below.
Class description:
Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc
Method signatures and docstrings:
- def __init__(self, data_file): data_file: path to file conatining vocabulary list
- def remove_astray(self, word_li... | Implement the Python class `VocabSanitizer` described below.
Class description:
Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc
Method signatures and docstrings:
- def __init__(self, data_file): data_file: path to file conatining vocabulary list
- def remove_astray(self, word_li... | 0e0dd8139c75477346c985201b51315b3a4e4f48 | <|skeleton|>
class VocabSanitizer:
"""Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc"""
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
<|body_0|>
def remove_astray(self, word_list):
"""Remove words tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VocabSanitizer:
"""Sanitize topK vocab prediction using ancillary vocab list by reranking or removing etc"""
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
extension = os.path.splitext(data_file)[-1]
if extension == '.json':
sel... | the_stack_v2_python_sparse | utilities/lang_data_utils.py | JosephGeoBenjamin/IndianNLP-Transliteration | train | 2 |
552a13a1ce1e7cd938b45c94e91ae7585f5443eb | [
"if name and (not namespace) and (not identifier):\n x = gmod_mappings[name]['xrefs'][0]\n namespace, identifier, name = (x.namespace, x.identifier, x.name)\nsuper().__init__(name=name, namespace=namespace, identifier=identifier, xrefs=xrefs)",
"if use_identifiers and self.entity.identifier and self.entity.... | <|body_start_0|>
if name and (not namespace) and (not identifier):
x = gmod_mappings[name]['xrefs'][0]
namespace, identifier, name = (x.namespace, x.identifier, x.name)
super().__init__(name=name, namespace=namespace, identifier=identifier, xrefs=xrefs)
<|end_body_0|>
<|body_sta... | Build a gene modification variant dictionary. | GeneModification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneModification:
"""Build a gene modification variant dictionary."""
def __init__(self, name: str, namespace: Optional[str]=None, identifier: Optional[str]=None, xrefs: Optional[List[Entity]]=None) -> None:
"""Build a protein modification variant data dictionary. :param name: The na... | stack_v2_sparse_classes_36k_train_029592 | 34,684 | permissive | [
{
"docstring": "Build a protein modification variant data dictionary. :param name: The name of the modification :param namespace: The namespace to which the name of this modification belongs :param identifier: The identifier of the name of the modification :param xrefs: Alternative database xrefs Either the nam... | 2 | null | Implement the Python class `GeneModification` described below.
Class description:
Build a gene modification variant dictionary.
Method signatures and docstrings:
- def __init__(self, name: str, namespace: Optional[str]=None, identifier: Optional[str]=None, xrefs: Optional[List[Entity]]=None) -> None: Build a protein ... | Implement the Python class `GeneModification` described below.
Class description:
Build a gene modification variant dictionary.
Method signatures and docstrings:
- def __init__(self, name: str, namespace: Optional[str]=None, identifier: Optional[str]=None, xrefs: Optional[List[Entity]]=None) -> None: Build a protein ... | ed66f013a77f9cbc513892b0dad1025b8f68bb46 | <|skeleton|>
class GeneModification:
"""Build a gene modification variant dictionary."""
def __init__(self, name: str, namespace: Optional[str]=None, identifier: Optional[str]=None, xrefs: Optional[List[Entity]]=None) -> None:
"""Build a protein modification variant data dictionary. :param name: The na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneModification:
"""Build a gene modification variant dictionary."""
def __init__(self, name: str, namespace: Optional[str]=None, identifier: Optional[str]=None, xrefs: Optional[List[Entity]]=None) -> None:
"""Build a protein modification variant data dictionary. :param name: The name of the mod... | the_stack_v2_python_sparse | src/pybel/dsl/node_classes.py | pybel/pybel | train | 133 |
5cdc5cf3541f726e10066d8ddf161639dfb2d726 | [
"ttk.Frame.__init__(self, master)\nself.conflict = conflict\nself.cframe = ttk.Frame(self)\nself.columnconfigure(0, weight=1)\nself.cframe.columnconfigure(0, weight=1)\nself.dmSelIdx = None\nself.dm = None\nself.clearBtn = ttk.Button(self, text='Clear Selection', command=self.clearSel)\nself.clearBtn.grid(row=1, co... | <|body_start_0|>
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.cframe = ttk.Frame(self)
self.columnconfigure(0, weight=1)
self.cframe.columnconfigure(0, weight=1)
self.dmSelIdx = None
self.dm = None
self.clearBtn = ttk.Button(self, text='C... | Displays a PreferenceRanking widget for each DM. | PreferenceRankingMaster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
<|body_0|>
def chgDM(self, event):
"""Change the selected DM."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_029593 | 12,627 | no_license | [
{
"docstring": "Initialize a master widget for PreferenceRankings.",
"name": "__init__",
"signature": "def __init__(self, master, conflict)"
},
{
"docstring": "Change the selected DM.",
"name": "chgDM",
"signature": "def chgDM(self, event)"
},
{
"docstring": "Refresh the widget c... | 6 | stack_v2_sparse_classes_30k_train_005336 | Implement the Python class `PreferenceRankingMaster` described below.
Class description:
Displays a PreferenceRanking widget for each DM.
Method signatures and docstrings:
- def __init__(self, master, conflict): Initialize a master widget for PreferenceRankings.
- def chgDM(self, event): Change the selected DM.
- def... | Implement the Python class `PreferenceRankingMaster` described below.
Class description:
Displays a PreferenceRanking widget for each DM.
Method signatures and docstrings:
- def __init__(self, master, conflict): Initialize a master widget for PreferenceRankings.
- def chgDM(self, event): Change the selected DM.
- def... | 502a12c9100962aaa0551763b74d303864967b80 | <|skeleton|>
class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
<|body_0|>
def chgDM(self, event):
"""Change the selected DM."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.cframe = ttk.Frame(self)
se... | the_stack_v2_python_sparse | widgets_f04_02_prefElements.py | ryosakagami/gmcr-py | train | 0 |
3a37a9f0e75faaf3573016a784f5b381e5a57dff | [
"if isinstance(form, KYCForm):\n data = form.cleaned_data\n user = PolarisUser.objects.filter(email=data.get('email')).first()\n if not user:\n user = PolarisUser.objects.create(first_name=data.get('first_name'), last_name=data.get('last_name'), email=data.get('email'))\n account = PolarisStellar... | <|body_start_0|>
if isinstance(form, KYCForm):
data = form.cleaned_data
user = PolarisUser.objects.filter(email=data.get('email')).first()
if not user:
user = PolarisUser.objects.create(first_name=data.get('first_name'), last_name=data.get('last_name'), email=... | SEP24KYC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEP24KYC:
def track_user_activity(form: forms.Form, transaction: Transaction):
"""Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarAccount and potentially a new PolarisUser. This function ensures an accurate record of a particula... | stack_v2_sparse_classes_36k_train_029594 | 5,811 | permissive | [
{
"docstring": "Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarAccount and potentially a new PolarisUser. This function ensures an accurate record of a particular person's activity.",
"name": "track_user_activity",
"signature": "def track_user... | 2 | null | Implement the Python class `SEP24KYC` described below.
Class description:
Implement the SEP24KYC class.
Method signatures and docstrings:
- def track_user_activity(form: forms.Form, transaction: Transaction): Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarA... | Implement the Python class `SEP24KYC` described below.
Class description:
Implement the SEP24KYC class.
Method signatures and docstrings:
- def track_user_activity(form: forms.Form, transaction: Transaction): Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarA... | fb2af83fa50c4c04801e3a68d8c09459e14d8c37 | <|skeleton|>
class SEP24KYC:
def track_user_activity(form: forms.Form, transaction: Transaction):
"""Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarAccount and potentially a new PolarisUser. This function ensures an accurate record of a particula... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEP24KYC:
def track_user_activity(form: forms.Form, transaction: Transaction):
"""Creates a PolarisUserTransaction object, and depending on the form passed, also creates a new PolarisStellarAccount and potentially a new PolarisUser. This function ensures an accurate record of a particular person's act... | the_stack_v2_python_sparse | server/integrations/sep24_kyc.py | stellar/django-polaris | train | 97 | |
f09cdc9acbc757bf0314e1c5b66e67f8c30b63ee | [
"LOG.info('[virtual event]: video edit state at {}'.format(self))\nself._icon_image = utils.get_image(VirtualEventIconographicPngs.FINISH.value)\nself._icon_image = cv2.cvtColor(self._icon_image, cv2.COLOR_RGBA2BGRA)\nself._sectors = [SECTOR_X_FORMAT.format(idx + 1) for idx in range(total_sectors)]",
"event, info... | <|body_start_0|>
LOG.info('[virtual event]: video edit state at {}'.format(self))
self._icon_image = utils.get_image(VirtualEventIconographicPngs.FINISH.value)
self._icon_image = cv2.cvtColor(self._icon_image, cv2.COLOR_RGBA2BGRA)
self._sectors = [SECTOR_X_FORMAT.format(idx + 1) for idx ... | Virtual Event Finish state In Finish state, display check flag for several seconds | VirtualEventFinishState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualEventFinishState:
"""Virtual Event Finish state In Finish state, display check flag for several seconds"""
def __init__(self, total_sectors):
"""initialize Finish state with a finish time for how long to display check flag Args: total_sectors (int): total number of sectors"""
... | stack_v2_sparse_classes_36k_train_029595 | 5,512 | permissive | [
{
"docstring": "initialize Finish state with a finish time for how long to display check flag Args: total_sectors (int): total number of sectors",
"name": "__init__",
"signature": "def __init__(self, total_sectors)"
},
{
"docstring": "Virtual Event state machine on event call Args: input_val (di... | 2 | null | Implement the Python class `VirtualEventFinishState` described below.
Class description:
Virtual Event Finish state In Finish state, display check flag for several seconds
Method signatures and docstrings:
- def __init__(self, total_sectors): initialize Finish state with a finish time for how long to display check fl... | Implement the Python class `VirtualEventFinishState` described below.
Class description:
Virtual Event Finish state In Finish state, display check flag for several seconds
Method signatures and docstrings:
- def __init__(self, total_sectors): initialize Finish state with a finish time for how long to display check fl... | 2ce50508dd4100eaef7f8729436549a801505705 | <|skeleton|>
class VirtualEventFinishState:
"""Virtual Event Finish state In Finish state, display check flag for several seconds"""
def __init__(self, total_sectors):
"""initialize Finish state with a finish time for how long to display check flag Args: total_sectors (int): total number of sectors"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualEventFinishState:
"""Virtual Event Finish state In Finish state, display check flag for several seconds"""
def __init__(self, total_sectors):
"""initialize Finish state with a finish time for how long to display check flag Args: total_sectors (int): total number of sectors"""
LOG.i... | the_stack_v2_python_sparse | bundle/src/deepracer_simulation_environment/scripts/mp4_saving/states/virtual_event_finish_state.py | aws-deepracer-community/deepracer-simapp | train | 83 |
91c999d23c956d727251bf14e2dcd48a6137d532 | [
"self.xk_hat = x0\nself.Pk = Pk0\nself.Gk = np.array([0])\nself.Q = Q\nself.R = R\nself.A = np.eye(self.xk_hat.shape[0])\nself.B = np.zeros(self.xk_hat.shape[0])\nself.C = np.eye(self.xk_hat.shape[0])",
"self.xk_hat = self.A @ self.xk_hat + self.B @ np.array(uk)\nself.Pk = self.A @ self.Pk @ self.A.T + self.Q\nse... | <|body_start_0|>
self.xk_hat = x0
self.Pk = Pk0
self.Gk = np.array([0])
self.Q = Q
self.R = R
self.A = np.eye(self.xk_hat.shape[0])
self.B = np.zeros(self.xk_hat.shape[0])
self.C = np.eye(self.xk_hat.shape[0])
<|end_body_0|>
<|body_start_1|>
self.... | KalmanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
def __init__(self, x0=np.array([0]), Pk0=np.array([0]), Q=np.array([0.01]), R=np.array([0.01])):
"""Initializes Kalman Filter. :param x0: (float vector) initial state estimate :param Pk0: (float 2d array) initial filter gain :param Q: (float 2d array) process noise :param R... | stack_v2_sparse_classes_36k_train_029596 | 1,311 | no_license | [
{
"docstring": "Initializes Kalman Filter. :param x0: (float vector) initial state estimate :param Pk0: (float 2d array) initial filter gain :param Q: (float 2d array) process noise :param R: (float 2d array) sensor uncertainties",
"name": "__init__",
"signature": "def __init__(self, x0=np.array([0]), P... | 2 | stack_v2_sparse_classes_30k_train_000574 | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, x0=np.array([0]), Pk0=np.array([0]), Q=np.array([0.01]), R=np.array([0.01])): Initializes Kalman Filter. :param x0: (float vector) initial state estima... | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, x0=np.array([0]), Pk0=np.array([0]), Q=np.array([0.01]), R=np.array([0.01])): Initializes Kalman Filter. :param x0: (float vector) initial state estima... | e6c9686c440486831ce5ea246ab05af5b4f6ea01 | <|skeleton|>
class KalmanFilter:
def __init__(self, x0=np.array([0]), Pk0=np.array([0]), Q=np.array([0.01]), R=np.array([0.01])):
"""Initializes Kalman Filter. :param x0: (float vector) initial state estimate :param Pk0: (float 2d array) initial filter gain :param Q: (float 2d array) process noise :param R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KalmanFilter:
def __init__(self, x0=np.array([0]), Pk0=np.array([0]), Q=np.array([0.01]), R=np.array([0.01])):
"""Initializes Kalman Filter. :param x0: (float vector) initial state estimate :param Pk0: (float 2d array) initial filter gain :param Q: (float 2d array) process noise :param R: (float 2d ar... | the_stack_v2_python_sparse | IMU/KalmanFilter.py | augustusellis/balance_bot | train | 1 | |
813b08dd264623f5b15c6d7fcca619d03cc3832e | [
"template = orm.ContentTemplate.objects.create(key='uncover_personality', category=1)\ncontent = '\\n <p>Your Vinely Wine Personality is determined by the flavor preferences that characterize your taste in wine. </p>\\n\\n <p>You can uncover yours at a Vinely Taste Party, where you’ll sip, savor, and ... | <|body_start_0|>
template = orm.ContentTemplate.objects.create(key='uncover_personality', category=1)
content = '\n <p>Your Vinely Wine Personality is determined by the flavor preferences that characterize your taste in wine. </p>\n\n <p>You can uncover yours at a Vinely Taste Party, where... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
template = orm.ContentTemplate.objects.create(key=... | stack_v2_sparse_classes_36k_train_029597 | 3,261 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
template = orm.ContentTemplate.objects.create(key='uncover_personality', category=1)
content = '\n <p>Your Vinely Wine Personality is determined by the flavor preferences that characterize your taste in ... | the_stack_v2_python_sparse | cms/migrations/0007_add_uncover_personality_page.py | RSV3/nuvine | train | 0 | |
9b5bfc372cf82cce726526a537fa9a7ff5a08556 | [
"if fan is None or star is None:\n return False\nif not (isinstance(fan, User) and isinstance(star, User)):\n return False\nrelation = Follow.objects.filter(star=star).filter(fan=fan)\nif len(relation) > 0:\n return False\nelse:\n Follow.objects.create(star=star, fan=fan)\n return True",
"if fan is... | <|body_start_0|>
if fan is None or star is None:
return False
if not (isinstance(fan, User) and isinstance(star, User)):
return False
relation = Follow.objects.filter(star=star).filter(fan=fan)
if len(relation) > 0:
return False
else:
... | FollowService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowService:
def add_fan_star(cls, fan, star):
"""Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the result whether the relation is created"""
<|body_0|>
def remove_fan_star(cls, fan, star):
... | stack_v2_sparse_classes_36k_train_029598 | 8,220 | no_license | [
{
"docstring": "Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the result whether the relation is created",
"name": "add_fan_star",
"signature": "def add_fan_star(cls, fan, star)"
},
{
"docstring": "Remove a fan from a... | 5 | stack_v2_sparse_classes_30k_test_001123 | Implement the Python class `FollowService` described below.
Class description:
Implement the FollowService class.
Method signatures and docstrings:
- def add_fan_star(cls, fan, star): Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the resul... | Implement the Python class `FollowService` described below.
Class description:
Implement the FollowService class.
Method signatures and docstrings:
- def add_fan_star(cls, fan, star): Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the resul... | 8565018a30a81fc32d904e57b2347f2e24a726c0 | <|skeleton|>
class FollowService:
def add_fan_star(cls, fan, star):
"""Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the result whether the relation is created"""
<|body_0|>
def remove_fan_star(cls, fan, star):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowService:
def add_fan_star(cls, fan, star):
"""Add a fan to a star :param fan: type: User, the fan user :param star: type: User, the star user :return: result: type: Bool, the result whether the relation is created"""
if fan is None or star is None:
return False
if not... | the_stack_v2_python_sparse | accounts/service.py | KomeijiSatori/mysite | train | 5 | |
d45debe8a56d3dc2a51a91d08b4fde7ff48817ea | [
"for paper_id in fragment.split():\n try:\n paper_id, dummy, categories = self._parse_entry(paper_id)\n except AssertionError:\n warnings.warn(f'Failed parsing new (new style): {paper_id}')\n continue\n for category in categories:\n try:\n yield (Identifier(paper_id),... | <|body_start_0|>
for paper_id in fragment.split():
try:
paper_id, dummy, categories = self._parse_entry(paper_id)
except AssertionError:
warnings.warn(f'Failed parsing new (new style): {paper_id}')
continue
for category in categ... | Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are preserved, but within each section are entries for e-prints from all archives. | NewStyleLineParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewStyleLineParser:
"""Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are preserved, but within each section are entr... | stack_v2_sparse_classes_36k_train_029599 | 23,697 | permissive | [
{
"docstring": "Parse entries for new e-prints. Parameters ---------- archive : str Literally just ``\"arxiv\"``; this is a dummy place-holder, since new-style lines contain entries for all archives for which announcements occurred on a particular day. fragment : str Section of the line containing new e-print e... | 4 | stack_v2_sparse_classes_30k_train_016794 | Implement the Python class `NewStyleLineParser` described below.
Class description:
Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are pres... | Implement the Python class `NewStyleLineParser` described below.
Class description:
Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are pres... | 407cb0b2cef83c7f653dabdf998e797b18475b13 | <|skeleton|>
class NewStyleLineParser:
"""Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are preserved, but within each section are entr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewStyleLineParser:
"""Parses new-style daily log lines. Starting after 2007-04-02 (:const:`NEW_STYLE_CUTOVER_AFTER`), the format changed to put all announcement-related events on a given day on the same line. The three original sections of the line are preserved, but within each section are entries for e-pri... | the_stack_v2_python_sparse | arxiv/canonical/classic/daily.py | arXiv/arxiv-canonical | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.