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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"self.num_events = num_events\nself.num_periods = num_periods\nself.dtypes = OrderedDict([('event_id', 'i'), ('period_no', 'i'), ('occ_date_id', 'i')])\nself.date_algorithm = 1\nself.start_stats = [{'desc': 'Date algorithm', 'value': self.date_algorithm, 'dtype': 'i'}, {'desc': 'Number of periods', 'value': self.nu... | <|body_start_0|>
self.num_events = num_events
self.num_periods = num_periods
self.dtypes = OrderedDict([('event_id', 'i'), ('period_no', 'i'), ('occ_date_id', 'i')])
self.date_algorithm = 1
self.start_stats = [{'desc': 'Date algorithm', 'value': self.date_algorithm, 'dtype': 'i'}... | Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_from_truncated_normal_cdf: Get number of periods from truncated normal cumulative... | OccurrenceFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OccurrenceFile:
"""Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_from_truncated_normal_cdf: Get number o... | stack_v2_sparse_classes_36k_train_019300 | 39,722 | permissive | [
{
"docstring": "Initialise Occurrence file class. Args: num_events (int): number of events. num_periods (int): total number of periods. random_seed (float): random seed for random number generator. directory (str): dummy model file destination. mean (float): mean of truncated normal distribution sampled to dete... | 5 | null | Implement the Python class `OccurrenceFile` described below.
Class description:
Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_... | Implement the Python class `OccurrenceFile` described below.
Class description:
Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class OccurrenceFile:
"""Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_from_truncated_normal_cdf: Get number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OccurrenceFile:
"""Generate data for Occurrence dummy model file. This file maps events to periods, which can represent any length of time. Attributes: get_num_periods_from_truncated_normal_cdf: Get number of periods on event-by-event basis. get_num_periods_from_truncated_normal_cdf: Get number of periods fro... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
a94defafafac0185705096d8ca5fee70ecb04e9f | [
"self.capacity = capacity\nself.time = 0\nself.map = {}\nself.freq_time = {}\nself.priority_queue = []\nself.update = set()",
"self.time += 1\nif key in self.map:\n freq, _ = self.freq_time[key]\n self.freq_time[key] = (freq + 1, self.time)\n self.update.add(key)\n return self.map[key]\nreturn -1",
... | <|body_start_0|>
self.capacity = capacity
self.time = 0
self.map = {}
self.freq_time = {}
self.priority_queue = []
self.update = set()
<|end_body_0|>
<|body_start_1|>
self.time += 1
if key in self.map:
freq, _ = self.freq_time[key]
... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_019301 | 3,017 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_005001 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.time = 0
self.map = {}
self.freq_time = {}
self.priority_queue = []
self.update = set()
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | python_1_to_1000/460_LFU_Cache.py | jakehoare/leetcode | train | 58 | |
b1c12a6d34432884c067651cde8072fd67424aa5 | [
"pending_info = {'user': user, 'category': ActionCategory.CONFIRM_EMAIL, 'token': get_uuid(cls.DEFAULT_TOKEN_LENGHT)}\nif new_email:\n serializer = EmailSerializer(data={'email': new_email})\n serializer.is_valid(raise_exception=True)\n pending_info['extra'] = serializer.validated_data\npending_action, _ =... | <|body_start_0|>
pending_info = {'user': user, 'category': ActionCategory.CONFIRM_EMAIL, 'token': get_uuid(cls.DEFAULT_TOKEN_LENGHT)}
if new_email:
serializer = EmailSerializer(data={'email': new_email})
serializer.is_valid(raise_exception=True)
pending_info['extra'] ... | Contains all utility methods to help auth precesses. | AuthService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthService:
"""Contains all utility methods to help auth precesses."""
def send_confirmation_email(cls, user, new_email=None):
"""Process the email confirmation sending."""
<|body_0|>
def confirm_email(cls, pending_action):
"""Process the email confirmation."""
... | stack_v2_sparse_classes_36k_train_019302 | 1,752 | permissive | [
{
"docstring": "Process the email confirmation sending.",
"name": "send_confirmation_email",
"signature": "def send_confirmation_email(cls, user, new_email=None)"
},
{
"docstring": "Process the email confirmation.",
"name": "confirm_email",
"signature": "def confirm_email(cls, pending_ac... | 2 | null | Implement the Python class `AuthService` described below.
Class description:
Contains all utility methods to help auth precesses.
Method signatures and docstrings:
- def send_confirmation_email(cls, user, new_email=None): Process the email confirmation sending.
- def confirm_email(cls, pending_action): Process the em... | Implement the Python class `AuthService` described below.
Class description:
Contains all utility methods to help auth precesses.
Method signatures and docstrings:
- def send_confirmation_email(cls, user, new_email=None): Process the email confirmation sending.
- def confirm_email(cls, pending_action): Process the em... | 3fdc01eabdff459b31e016f9f6d1cafc19c5a292 | <|skeleton|>
class AuthService:
"""Contains all utility methods to help auth precesses."""
def send_confirmation_email(cls, user, new_email=None):
"""Process the email confirmation sending."""
<|body_0|>
def confirm_email(cls, pending_action):
"""Process the email confirmation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthService:
"""Contains all utility methods to help auth precesses."""
def send_confirmation_email(cls, user, new_email=None):
"""Process the email confirmation sending."""
pending_info = {'user': user, 'category': ActionCategory.CONFIRM_EMAIL, 'token': get_uuid(cls.DEFAULT_TOKEN_LENGHT)... | the_stack_v2_python_sparse | apps/accounts/services/auth_service.py | jimialex/django-wise | train | 0 |
22194b07d19eb1b7b8848e24d3f1436ed8d15636 | [
"chart_options = document.chart_options\nplot = cls._create_plot(chart_options=chart_options)\ncls._add_title(plot, chart_options.title)\nreturn plot",
"x = chart_options.x_axis\nx_data_type = x.data_type\nplot = figure(height=chart_options.height, width=chart_options.width, x_axis_type=x_data_type)\nplot.xaxis.a... | <|body_start_0|>
chart_options = document.chart_options
plot = cls._create_plot(chart_options=chart_options)
cls._add_title(plot, chart_options.title)
return plot
<|end_body_0|>
<|body_start_1|>
x = chart_options.x_axis
x_data_type = x.data_type
plot = figure(hei... | Recipe for creating a plot to display to the user. | ChartRecipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChartRecipe:
"""Recipe for creating a plot to display to the user."""
def create(cls, document: Chart) -> figure:
"""Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredients for bokeh figure creation. :return: plot(bokeh.plotti... | stack_v2_sparse_classes_36k_train_019303 | 9,655 | no_license | [
{
"docstring": "Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredients for bokeh figure creation. :return: plot(bokeh.plotting.figure) - bokeh figure object to display to the user.",
"name": "create",
"signature": "def create(cls, document: Char... | 3 | stack_v2_sparse_classes_30k_train_007176 | Implement the Python class `ChartRecipe` described below.
Class description:
Recipe for creating a plot to display to the user.
Method signatures and docstrings:
- def create(cls, document: Chart) -> figure: Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredie... | Implement the Python class `ChartRecipe` described below.
Class description:
Recipe for creating a plot to display to the user.
Method signatures and docstrings:
- def create(cls, document: Chart) -> figure: Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredie... | eae965a1eb6f53ec5bd5ab961ec0383737165ce4 | <|skeleton|>
class ChartRecipe:
"""Recipe for creating a plot to display to the user."""
def create(cls, document: Chart) -> figure:
"""Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredients for bokeh figure creation. :return: plot(bokeh.plotti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChartRecipe:
"""Recipe for creating a plot to display to the user."""
def create(cls, document: Chart) -> figure:
"""Create bokeh figure to display to the user. :param document: (Chart) chart document object containing ingredients for bokeh figure creation. :return: plot(bokeh.plotting.figure) - ... | the_stack_v2_python_sparse | Visualiser/modules/charts/creators.py | RadoslawPotyka/DataVisualiser | train | 0 |
b4b000182b765577a6d2c7877a957308a03ab302 | [
"self.init_lr = init_lr\nself.gamma = gamma\nself.iter_steps = iter_steps",
"lr = self.init_lr\nfor iter_step in self.iter_steps:\n if iter >= iter_step:\n lr *= self.gamma\nreturn lr"
] | <|body_start_0|>
self.init_lr = init_lr
self.gamma = gamma
self.iter_steps = iter_steps
<|end_body_0|>
<|body_start_1|>
lr = self.init_lr
for iter_step in self.iter_steps:
if iter >= iter_step:
lr *= self.gamma
return lr
<|end_body_1|>
| StepScheduler Step decay | StepScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepScheduler:
"""StepScheduler Step decay"""
def __init__(self, init_lr, gamma, iter_steps):
"""Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is multiplied. Example: StepScheduler(0.1, 0.1, [150000, 300000... | stack_v2_sparse_classes_36k_train_019304 | 5,375 | permissive | [
{
"docstring": "Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is multiplied. Example: StepScheduler(0.1, 0.1, [150000, 300000, 400000])",
"name": "__init__",
"signature": "def __init__(self, init_lr, gamma, iter_steps)"
},
... | 2 | null | Implement the Python class `StepScheduler` described below.
Class description:
StepScheduler Step decay
Method signatures and docstrings:
- def __init__(self, init_lr, gamma, iter_steps): Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is mul... | Implement the Python class `StepScheduler` described below.
Class description:
StepScheduler Step decay
Method signatures and docstrings:
- def __init__(self, init_lr, gamma, iter_steps): Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is mul... | 93211d0f322d76efc48cfcf27decae7bd818f923 | <|skeleton|>
class StepScheduler:
"""StepScheduler Step decay"""
def __init__(self, init_lr, gamma, iter_steps):
"""Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is multiplied. Example: StepScheduler(0.1, 0.1, [150000, 300000... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StepScheduler:
"""StepScheduler Step decay"""
def __init__(self, init_lr, gamma, iter_steps):
"""Args: init_lr (float): Initial learning rate. gamma (float): Multiplier. iter_steps (list of int): Iteration at which gamma is multiplied. Example: StepScheduler(0.1, 0.1, [150000, 300000, 400000])"""... | the_stack_v2_python_sparse | python/src/nnabla/utils/learning_rate_scheduler.py | Pandinosaurus/nnabla | train | 1 |
b8b8d26452f9f38788afc4efd8417f42c360cfa4 | [
"self.block_data = self.server_behaviors.create_block_device_mapping_v2(boot_index=0, uuid=self.image_ref, volume_size=self.volume_size, source_type='image', destination_type='volume', delete_on_termination='invalid')\nwith self.assertRaises(BadRequest):\n self.boot_from_volume_client.create_server(block_device_... | <|body_start_0|>
self.block_data = self.server_behaviors.create_block_device_mapping_v2(boot_index=0, uuid=self.image_ref, volume_size=self.volume_size, source_type='image', destination_type='volume', delete_on_termination='invalid')
with self.assertRaises(BadRequest):
self.boot_from_volume_... | CreateVolumeServerNegativeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateVolumeServerNegativeTest:
def test_delete_on_terminate_invalid(self):
"""Verify delete on termination set to invalid throws bad request"""
<|body_0|>
def test_source_type_invalid(self):
"""Verify source type set to invalid throws bad request"""
<|body_1... | stack_v2_sparse_classes_36k_train_019305 | 4,997 | permissive | [
{
"docstring": "Verify delete on termination set to invalid throws bad request",
"name": "test_delete_on_terminate_invalid",
"signature": "def test_delete_on_terminate_invalid(self)"
},
{
"docstring": "Verify source type set to invalid throws bad request",
"name": "test_source_type_invalid",... | 5 | null | Implement the Python class `CreateVolumeServerNegativeTest` described below.
Class description:
Implement the CreateVolumeServerNegativeTest class.
Method signatures and docstrings:
- def test_delete_on_terminate_invalid(self): Verify delete on termination set to invalid throws bad request
- def test_source_type_inva... | Implement the Python class `CreateVolumeServerNegativeTest` described below.
Class description:
Implement the CreateVolumeServerNegativeTest class.
Method signatures and docstrings:
- def test_delete_on_terminate_invalid(self): Verify delete on termination set to invalid throws bad request
- def test_source_type_inva... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class CreateVolumeServerNegativeTest:
def test_delete_on_terminate_invalid(self):
"""Verify delete on termination set to invalid throws bad request"""
<|body_0|>
def test_source_type_invalid(self):
"""Verify source type set to invalid throws bad request"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateVolumeServerNegativeTest:
def test_delete_on_terminate_invalid(self):
"""Verify delete on termination set to invalid throws bad request"""
self.block_data = self.server_behaviors.create_block_device_mapping_v2(boot_index=0, uuid=self.image_ref, volume_size=self.volume_size, source_type='... | the_stack_v2_python_sparse | cloudroast/compute/integration/volumes/boot_from_volume/v2/test_volume_server_negative.py | RULCSoft/cloudroast | train | 1 | |
0c6e5fd1d8be662993d75f79742ceebeff9d4487 | [
"primes = list()\nfactors = list()\nfor i in range(2, n + 1):\n is_prime = True\n for p in primes:\n if i % p == 0:\n is_prime = False\n break\n if is_prime:\n primes.append(i)\n if n % i == 0:\n print(f'[DEBUG] found {i} (n = {n})')\n factor... | <|body_start_0|>
primes = list()
factors = list()
for i in range(2, n + 1):
is_prime = True
for p in primes:
if i % p == 0:
is_prime = False
break
if is_prime:
primes.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def method_v1(self, n: int) -> int:
"""Brute force. It doesn't work well on large numbers."""
<|body_0|>
def method_v2(self, n: int) -> int:
"""Try to be a little bit smarter. Here we first try to find the next prime, and then check if it is a factor. Every... | stack_v2_sparse_classes_36k_train_019306 | 3,762 | no_license | [
{
"docstring": "Brute force. It doesn't work well on large numbers.",
"name": "method_v1",
"signature": "def method_v1(self, n: int) -> int"
},
{
"docstring": "Try to be a little bit smarter. Here we first try to find the next prime, and then check if it is a factor. Every time we find a factor ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def method_v1(self, n: int) -> int: Brute force. It doesn't work well on large numbers.
- def method_v2(self, n: int) -> int: Try to be a little bit smarter. Here we first try to... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def method_v1(self, n: int) -> int: Brute force. It doesn't work well on large numbers.
- def method_v2(self, n: int) -> int: Try to be a little bit smarter. Here we first try to... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def method_v1(self, n: int) -> int:
"""Brute force. It doesn't work well on large numbers."""
<|body_0|>
def method_v2(self, n: int) -> int:
"""Try to be a little bit smarter. Here we first try to find the next prime, and then check if it is a factor. Every... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def method_v1(self, n: int) -> int:
"""Brute force. It doesn't work well on large numbers."""
primes = list()
factors = list()
for i in range(2, n + 1):
is_prime = True
for p in primes:
if i % p == 0:
is_prim... | the_stack_v2_python_sparse | python3/euler/3.largest_prime_factor.py | victorchu/algorithms | train | 0 | |
aaed73b38dff73deb389604f5657d88b77c2d6c1 | [
"self.lines = open(filen, 'r').readlines()\ntimeBlocks = self.getTimeBlocks()\nself.timeParams = {}\nvolForEachTime = self.returnVolumeHybro(timeBlocks)\nself.timeParams.update(volForEachTime)",
"lineNum = []\ntimeBlock = {}\nfor lineNumber, line in enumerate(self.lines):\n if line.strip().startswith('1*'):\n ... | <|body_start_0|>
self.lines = open(filen, 'r').readlines()
timeBlocks = self.getTimeBlocks()
self.timeParams = {}
volForEachTime = self.returnVolumeHybro(timeBlocks)
self.timeParams.update(volForEachTime)
<|end_body_0|>
<|body_start_1|>
lineNum = []
timeBlock = {... | class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output | MELCORdata | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MELCORdata:
"""class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output"""
def __init__(self, filen):
"""Constructor @ In, filen, FileObject, the file to parse @ O... | stack_v2_sparse_classes_36k_train_019307 | 4,020 | permissive | [
{
"docstring": "Constructor @ In, filen, FileObject, the file to parse @ Out, None",
"name": "__init__",
"signature": "def __init__(self, filen)"
},
{
"docstring": "This method returns a dictionary of lists of type {\"time\":[lines Of Output for that time]} @ In, None @ Out, timeBlock, dict, {\"... | 4 | null | Implement the Python class `MELCORdata` described below.
Class description:
class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output
Method signatures and docstrings:
- def __init__(self, filen): C... | Implement the Python class `MELCORdata` described below.
Class description:
class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output
Method signatures and docstrings:
- def __init__(self, filen): C... | fbee9e3def3c1ee576d1af85f3258cc816ceaaaf | <|skeleton|>
class MELCORdata:
"""class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output"""
def __init__(self, filen):
"""Constructor @ In, filen, FileObject, the file to parse @ O... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MELCORdata:
"""class that parses output of MELCOR 2.1 output file and reads in trip, minor block and write a csv file For now, Only the data associated to control volumes are parsed and output"""
def __init__(self, filen):
"""Constructor @ In, filen, FileObject, the file to parse @ Out, None"""
... | the_stack_v2_python_sparse | framework/CodeInterfaces/MELCOR/MELCORdata.py | jbae11/raven | train | 0 |
621bd3cbf3005f12cb4eb9824a90f385fb9cf1da | [
"a = ['H']\nif self.VN:\n a.append('VN:Z:2.0')\nfor fn in self.tagnames:\n if fn != 'VN':\n a.append(self.field_to_s(fn, tag=True))\nreturn a",
"a = ['H']\nif self.VN:\n a.append('VN:Z:1.0')\nfor fn in self.tagnames:\n if fn != 'VN':\n a.append(self.field_to_s(fn, tag=True))\nreturn a"
] | <|body_start_0|>
a = ['H']
if self.VN:
a.append('VN:Z:2.0')
for fn in self.tagnames:
if fn != 'VN':
a.append(self.field_to_s(fn, tag=True))
return a
<|end_body_0|>
<|body_start_1|>
a = ['H']
if self.VN:
a.append('VN:Z:1... | VersionConversion | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionConversion:
def _to_gfa2_a(self):
"""Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Array of strings representing the tags."""
<|body_0|>
def _to_gfa1_a(self):
"""Return the... | stack_v2_sparse_classes_36k_train_019308 | 847 | permissive | [
{
"docstring": "Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Array of strings representing the tags.",
"name": "_to_gfa2_a",
"signature": "def _to_gfa2_a(self)"
},
{
"docstring": "Return the string represent... | 2 | null | Implement the Python class `VersionConversion` described below.
Class description:
Implement the VersionConversion class.
Method signatures and docstrings:
- def _to_gfa2_a(self): Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Arra... | Implement the Python class `VersionConversion` described below.
Class description:
Implement the VersionConversion class.
Method signatures and docstrings:
- def _to_gfa2_a(self): Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Arra... | 12b31daac26ab137b6ee4a29b4f14554ba962dcb | <|skeleton|>
class VersionConversion:
def _to_gfa2_a(self):
"""Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Array of strings representing the tags."""
<|body_0|>
def _to_gfa1_a(self):
"""Return the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionConversion:
def _to_gfa2_a(self):
"""Return the string representation of the tags, changing the value of the VN tag to 2.0, if this is present Returns ------- list of str Array of strings representing the tags."""
a = ['H']
if self.VN:
a.append('VN:Z:2.0')
fo... | the_stack_v2_python_sparse | gfapy/line/header/version_conversion.py | ggonnella/gfapy | train | 63 | |
0edc280dbaa13aa4fb9b831887766535612992e7 | [
"self.project = project\nself.tmp_path = tmp_path\nself.pvc_dict = get_pvc_dict()\nself.pvc_dict['metadata']['name'] = 'logwriter-cephfs-many'\nself.pvc_dict['spec']['accessModes'] = [constants.ACCESS_MODE_RWX]\nif storagecluster_independent_check() and (not is_managed_service_cluster()):\n sc_name = constants.D... | <|body_start_0|>
self.project = project
self.tmp_path = tmp_path
self.pvc_dict = get_pvc_dict()
self.pvc_dict['metadata']['name'] = 'logwriter-cephfs-many'
self.pvc_dict['spec']['accessModes'] = [constants.ACCESS_MODE_RWX]
if storagecluster_independent_check() and (not is... | Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https://github.com/red-hat-storage/ocs-ci/issues/5724 will be completed. | LogReaderWriterParallel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogReaderWriterParallel:
"""Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https://github.com/red-hat-storage/ocs-ci/iss... | stack_v2_sparse_classes_36k_train_019309 | 9,222 | permissive | [
{
"docstring": "Init of the LogReaderWriterParallel object Args: project (pytest fixture): The project fixture. tmp_path (pytest fixture): The tmp_path fixture. storage_size (str): The size of the storage in GB. The default value is 2 GB.",
"name": "__init__",
"signature": "def __init__(self, project, t... | 3 | null | Implement the Python class `LogReaderWriterParallel` described below.
Class description:
Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https:... | Implement the Python class `LogReaderWriterParallel` described below.
Class description:
Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https:... | 5e9e504957403148e413326f65c3769bf9d8eb39 | <|skeleton|>
class LogReaderWriterParallel:
"""Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https://github.com/red-hat-storage/ocs-ci/iss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogReaderWriterParallel:
"""Write and read logfile stored on cephfs volume, from all worker nodes of a cluster via k8s Deployment, while fetching content of the stored data via oc rsync to check the data locally. TO DO: Update the test after the issue https://github.com/red-hat-storage/ocs-ci/issues/5724 will... | the_stack_v2_python_sparse | ocs_ci/ocs/cephfs_workload.py | red-hat-storage/ocs-ci | train | 146 |
4c231424109f9ebd43336ce8213490328a2f8caa | [
"self.done = False\nself.th_lim = pyrado.inf\nself.sign = 1 if positive else -1\nself.u_max = 0.9\nself.cnt = 0\nself.cnt_done = cnt_done",
"meas = meas.to(dtype=to.get_default_dtype())\nth = meas[0].item()\nif abs(th - self.th_lim) > 1e-06:\n self.cnt = 0\n self.th_lim = th\nelse:\n self.cnt += 1\nself.... | <|body_start_0|>
self.done = False
self.th_lim = pyrado.inf
self.sign = 1 if positive else -1
self.u_max = 0.9
self.cnt = 0
self.cnt_done = cnt_done
<|end_body_0|>
<|body_start_1|>
meas = meas.to(dtype=to.get_default_dtype())
th = meas[0].item()
i... | Controller for going to one of the joint limits (part of the calibration routine) | QQubeGoToLimCtrl | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QQubeGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, positive: bool=True, cnt_done: int=250):
"""Constructor :param positive: direction switch"""
<|body_0|>
def __call__(self, meas: to.Tensor) -> to.... | stack_v2_sparse_classes_36k_train_019310 | 32,197 | permissive | [
{
"docstring": "Constructor :param positive: direction switch",
"name": "__init__",
"signature": "def __init__(self, positive: bool=True, cnt_done: int=250)"
},
{
"docstring": "Go to joint limits by applying `u_max` and save limit value in `th_lim`. :param meas: sensor measurement :return: actio... | 2 | null | Implement the Python class `QQubeGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, positive: bool=True, cnt_done: int=250): Constructor :param positive: direction switch
- def __call... | Implement the Python class `QQubeGoToLimCtrl` described below.
Class description:
Controller for going to one of the joint limits (part of the calibration routine)
Method signatures and docstrings:
- def __init__(self, positive: bool=True, cnt_done: int=250): Constructor :param positive: direction switch
- def __call... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class QQubeGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, positive: bool=True, cnt_done: int=250):
"""Constructor :param positive: direction switch"""
<|body_0|>
def __call__(self, meas: to.Tensor) -> to.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QQubeGoToLimCtrl:
"""Controller for going to one of the joint limits (part of the calibration routine)"""
def __init__(self, positive: bool=True, cnt_done: int=250):
"""Constructor :param positive: direction switch"""
self.done = False
self.th_lim = pyrado.inf
self.sign = ... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/special/environment_specific.py | 1abner1/SimuRLacra | train | 0 |
74bce0dbec2c1a92c40a962f3a099097be735c96 | [
"super().__init__()\nself.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.dropout = nn.Dropout(dropout)\nself.linear1 = nn.Linear(d_model, dim_feedforward)\nself.linear2 = nn.Linear(dim_feedforward, d_model)\nself... | <|body_start_0|>
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
s... | A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhi... | TransformerDecoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones... | stack_v2_sparse_classes_36k_train_019311 | 20,460 | permissive | [
{
"docstring": "Initialize a TransformerDecoder. Parameters ---------- d_model : int The number of expected features in the input. n_head : int The number of heads in the multiheadattention models. dim_feedforward : int, optional The dimension of the feedforward network (default=2048). dropout : float, optional... | 2 | stack_v2_sparse_classes_30k_train_001851 | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Ni... | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Ni... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDecoderLayer:
"""A TransformerDecoderLayer. A TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gom... | the_stack_v2_python_sparse | flambe/nn/transformer.py | cle-ros/flambe | train | 1 |
0661b411ccaecc369180ac74db245b0bd74ebc29 | [
"self.task = task\nself.connected = False\nself.error = ''\nself.immsock = None",
"log.debug('WhiskerImmSocket: connect')\nproto = socket.getprotobyname('tcp')\ntry:\n self.immsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)\n self.immsock.connect((server, port))\n self.connected = True\ne... | <|body_start_0|>
self.task = task
self.connected = False
self.error = ''
self.immsock = None
<|end_body_0|>
<|body_start_1|>
log.debug('WhiskerImmSocket: connect')
proto = socket.getprotobyname('tcp')
try:
self.immsock = socket.socket(socket.AF_INET, ... | Whisker Twisted immediate socket handler. Uses raw sockets. | WhiskerImmSocket | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
<|body_0|>
def connect(self, server: str, port: int) -> None:
"""Co... | stack_v2_sparse_classes_36k_train_019312 | 17,022 | permissive | [
{
"docstring": "Args: task: instance of :class:`WhiskerTwistedTask`",
"name": "__init__",
"signature": "def __init__(self, task: WhiskerTwistedTask) -> None"
},
{
"docstring": "Connects the Whisker immediate socket. Args: server: server hostname/IP address port: immediate port number",
"name... | 4 | stack_v2_sparse_classes_30k_train_007840 | Implement the Python class `WhiskerImmSocket` described below.
Class description:
Whisker Twisted immediate socket handler. Uses raw sockets.
Method signatures and docstrings:
- def __init__(self, task: WhiskerTwistedTask) -> None: Args: task: instance of :class:`WhiskerTwistedTask`
- def connect(self, server: str, p... | Implement the Python class `WhiskerImmSocket` described below.
Class description:
Whisker Twisted immediate socket handler. Uses raw sockets.
Method signatures and docstrings:
- def __init__(self, task: WhiskerTwistedTask) -> None: Args: task: instance of :class:`WhiskerTwistedTask`
- def connect(self, server: str, p... | 938e4dad4aa0789101421462d1a0b7ff1833d2bb | <|skeleton|>
class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
<|body_0|>
def connect(self, server: str, port: int) -> None:
"""Co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhiskerImmSocket:
"""Whisker Twisted immediate socket handler. Uses raw sockets."""
def __init__(self, task: WhiskerTwistedTask) -> None:
"""Args: task: instance of :class:`WhiskerTwistedTask`"""
self.task = task
self.connected = False
self.error = ''
self.immsock ... | the_stack_v2_python_sparse | whisker/twistedclient.py | RudolfCardinal/whisker-python-client | train | 0 |
26af818019ff22cb49061189c0e08b4fdc34af2f | [
"self.capacity = capacity\nself.size = 1\nself.head = LinkedList(0, -1)\nself.tail = self.head\nself.hash_table = {-1: self.head}",
"if key in self.hash_table:\n if self.hash_table[key] is not self.tail:\n new_tail = LinkedList(self.hash_table[key].val, key)\n self.tail.next = new_tail\n s... | <|body_start_0|>
self.capacity = capacity
self.size = 1
self.head = LinkedList(0, -1)
self.tail = self.head
self.hash_table = {-1: self.head}
<|end_body_0|>
<|body_start_1|>
if key in self.hash_table:
if self.hash_table[key] is not self.tail:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_019313 | 2,028 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_007451 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | d09f56d4fef859ca4749dc753d869828f5de901f | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.size = 1
self.head = LinkedList(0, -1)
self.tail = self.head
self.hash_table = {-1: self.head}
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | 146/LRU Cache.py | ArrayZoneYour/LeetCode | train | 0 | |
48495827d4f139c6463ed0a004e9465dab3f2da0 | [
"employee_schema = EmployeeSchema()\nemployee_data = request.get_json()\nvalidated_employee_data, errors = employee_schema.load(employee_data)\nif errors:\n return (dict(status='fail', message=errors), 400)\nemployee = Employee(**validated_employee_data)\nsaved_employee = employee.save()\nif not saved_employee:\... | <|body_start_0|>
employee_schema = EmployeeSchema()
employee_data = request.get_json()
validated_employee_data, errors = employee_schema.load(employee_data)
if errors:
return (dict(status='fail', message=errors), 400)
employee = Employee(**validated_employee_data)
... | EmployeeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeView:
def post(self):
"""Creating an Employee ad"""
<|body_0|>
def get(self):
"""Getting All employees"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
employee_schema = EmployeeSchema()
employee_data = request.get_json()
vali... | stack_v2_sparse_classes_36k_train_019314 | 3,201 | no_license | [
{
"docstring": "Creating an Employee ad",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Getting All employees",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008544 | Implement the Python class `EmployeeView` described below.
Class description:
Implement the EmployeeView class.
Method signatures and docstrings:
- def post(self): Creating an Employee ad
- def get(self): Getting All employees | Implement the Python class `EmployeeView` described below.
Class description:
Implement the EmployeeView class.
Method signatures and docstrings:
- def post(self): Creating an Employee ad
- def get(self): Getting All employees
<|skeleton|>
class EmployeeView:
def post(self):
"""Creating an Employee ad""... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class EmployeeView:
def post(self):
"""Creating an Employee ad"""
<|body_0|>
def get(self):
"""Getting All employees"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeView:
def post(self):
"""Creating an Employee ad"""
employee_schema = EmployeeSchema()
employee_data = request.get_json()
validated_employee_data, errors = employee_schema.load(employee_data)
if errors:
return (dict(status='fail', message=errors), 40... | the_stack_v2_python_sparse | app/controllers/employee.py | MutegekiHenry/project-cohort-backend | train | 0 | |
d0bb6e04c26c9871dcd8321e411fe4c5707cbc6d | [
"pytest.assume(1 == 2)\npytest.assume(2 == 3)\npytest.assume(2 == 2)",
"assert 1 == 2\nassert 2 == 3\nassert 2 == 2"
] | <|body_start_0|>
pytest.assume(1 == 2)
pytest.assume(2 == 3)
pytest.assume(2 == 2)
<|end_body_0|>
<|body_start_1|>
assert 1 == 2
assert 2 == 3
assert 2 == 2
<|end_body_1|>
| TestPytestAssume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPytestAssume:
def test_001(self):
"""pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:"""
<|body_0|>
def test_002(self):
"""assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pytest.assume(1 == 2)
p... | stack_v2_sparse_classes_36k_train_019315 | 792 | no_license | [
{
"docstring": "pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:",
"name": "test_001",
"signature": "def test_001(self)"
},
{
"docstring": "assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return:",
"name": "test_002",
"signature": "def test_002(self)"
}
] | 2 | null | Implement the Python class `TestPytestAssume` described below.
Class description:
Implement the TestPytestAssume class.
Method signatures and docstrings:
- def test_001(self): pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:
- def test_002(self): assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return: | Implement the Python class `TestPytestAssume` described below.
Class description:
Implement the TestPytestAssume class.
Method signatures and docstrings:
- def test_001(self): pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:
- def test_002(self): assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return:
<|skeleton|>
class TestPyte... | df9d96009cbdf84176efbf4b02f43cb1d5208524 | <|skeleton|>
class TestPytestAssume:
def test_001(self):
"""pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:"""
<|body_0|>
def test_002(self):
"""assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPytestAssume:
def test_001(self):
"""pytest.assume:有多条断言时,当断言失败时,其他断言依旧会校验 :return:"""
pytest.assume(1 == 2)
pytest.assume(2 == 3)
pytest.assume(2 == 2)
def test_002(self):
"""assert:有多条断言时,当断言失败时,失败断言之后的断言不会再校验 :return:"""
assert 1 == 2
assert ... | the_stack_v2_python_sparse | pytest_study/test_fixture/test_pytest_assume.py | 606keng/weeds_study | train | 1 | |
15f785e873763bd0b559e7bd0053c42524230ffe | [
"super(SetUp, self).__init__(*args, **kwargs)\nself.arguments = arguments\nself._lexicographer = None\nself._builder = None\nreturn",
"if self._lexicographer is None:\n glob = self.arguments.glob\n message = 'Building Lexicographer with glob ({0})'.format(glob)\n self.logger.debug(message)\n self._lex... | <|body_start_0|>
super(SetUp, self).__init__(*args, **kwargs)
self.arguments = arguments
self._lexicographer = None
self._builder = None
return
<|end_body_0|>
<|body_start_1|>
if self._lexicographer is None:
glob = self.arguments.glob
message = 'B... | The SetUp sets up the infrastructure | SetUp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetUp:
"""The SetUp sets up the infrastructure"""
def __init__(self, arguments, *args, **kwargs):
""":param: - `arguments`: An ArgumentParser Namespace"""
<|body_0|>
def lexicographer(self):
""":return: Lexicographer that maps config-files"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_019316 | 1,568 | permissive | [
{
"docstring": ":param: - `arguments`: An ArgumentParser Namespace",
"name": "__init__",
"signature": "def __init__(self, arguments, *args, **kwargs)"
},
{
"docstring": ":return: Lexicographer that maps config-files",
"name": "lexicographer",
"signature": "def lexicographer(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_005212 | Implement the Python class `SetUp` described below.
Class description:
The SetUp sets up the infrastructure
Method signatures and docstrings:
- def __init__(self, arguments, *args, **kwargs): :param: - `arguments`: An ArgumentParser Namespace
- def lexicographer(self): :return: Lexicographer that maps config-files
- ... | Implement the Python class `SetUp` described below.
Class description:
The SetUp sets up the infrastructure
Method signatures and docstrings:
- def __init__(self, arguments, *args, **kwargs): :param: - `arguments`: An ArgumentParser Namespace
- def lexicographer(self): :return: Lexicographer that maps config-files
- ... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class SetUp:
"""The SetUp sets up the infrastructure"""
def __init__(self, arguments, *args, **kwargs):
""":param: - `arguments`: An ArgumentParser Namespace"""
<|body_0|>
def lexicographer(self):
""":return: Lexicographer that maps config-files"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetUp:
"""The SetUp sets up the infrastructure"""
def __init__(self, arguments, *args, **kwargs):
""":param: - `arguments`: An ArgumentParser Namespace"""
super(SetUp, self).__init__(*args, **kwargs)
self.arguments = arguments
self._lexicographer = None
self._build... | the_stack_v2_python_sparse | apetools/proletarians/setuprun.py | russell-n/oldape | train | 0 |
874fce545e36c50d2bc10a65aec91c74793b0f8a | [
"log.info('Starting video stream...')\nvideo_stream = VideoStream(src=0).start()\ntime.sleep(2)\ntimeout_time = time.time() + 10\nvalid_code = False\nwhile True:\n extracted_frame = video_stream.read()\n extracted_frame = imutils.resize(extracted_frame, width=400)\n found_barcodes = pyzbar.decode(extracted... | <|body_start_0|>
log.info('Starting video stream...')
video_stream = VideoStream(src=0).start()
time.sleep(2)
timeout_time = time.time() + 10
valid_code = False
while True:
extracted_frame = video_stream.read()
extracted_frame = imutils.resize(extr... | The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found. | QRReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRReader:
"""The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found."""
def read_qr_code(self):
"""This functions initialises the camera and then searches for QR ... | stack_v2_sparse_classes_36k_train_019317 | 5,578 | no_license | [
{
"docstring": "This functions initialises the camera and then searches for QR codes. Any codes that are found are incrementally passed to :func:`validate_qr_code` which returns the code to be returned to the calling function, or False if the code is invalid.",
"name": "read_qr_code",
"signature": "def ... | 2 | null | Implement the Python class `QRReader` described below.
Class description:
The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found.
Method signatures and docstrings:
- def read_qr_code(self): This f... | Implement the Python class `QRReader` described below.
Class description:
The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found.
Method signatures and docstrings:
- def read_qr_code(self): This f... | 8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf | <|skeleton|>
class QRReader:
"""The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found."""
def read_qr_code(self):
"""This functions initialises the camera and then searches for QR ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QRReader:
"""The QRReader class consists of two functions, :func:`read_qr_code` which is publicly callable, and :func:`validate_qr_code` which is called to validate any codes that are found."""
def read_qr_code(self):
"""This functions initialises the camera and then searches for QR codes. Any co... | the_stack_v2_python_sparse | AgentPi/qrreader.py | JiewenGuan/Iot-Carshare | train | 0 |
006f8088a3c2309deb57ba249ae1c42861322f12 | [
"m = re.search(cls.direction_symbol_regex, s)\nif m:\n symbol = m.group(0)\n if symbol[0] == '<' and symbol[-1] == '>':\n return True\n return False\nelse:\n raise MalformattedReactionDirectionSymbolException('Check the directional symbol')",
"m = re.match(cls.symbol_regex, symbol)\nif m is Non... | <|body_start_0|>
m = re.search(cls.direction_symbol_regex, s)
if m:
symbol = m.group(0)
if symbol[0] == '<' and symbol[-1] == '>':
return True
return False
else:
raise MalformattedReactionDirectionSymbolException('Check the directio... | An implementation of ExpressionParser for reading strings and forming | StringExpressionParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringExpressionParser:
"""An implementation of ExpressionParser for reading strings and forming"""
def _is_bidirectional(cls, s):
"""Determines if a reaction is bi-directional based on the symbol between the reactants and products. :param s: a string which is formatted according to ... | stack_v2_sparse_classes_36k_train_019318 | 8,250 | no_license | [
{
"docstring": "Determines if a reaction is bi-directional based on the symbol between the reactants and products. :param s: a string which is formatted according to our conventions :return: True or False",
"name": "_is_bidirectional",
"signature": "def _is_bidirectional(cls, s)"
},
{
"docstring... | 5 | stack_v2_sparse_classes_30k_train_006791 | Implement the Python class `StringExpressionParser` described below.
Class description:
An implementation of ExpressionParser for reading strings and forming
Method signatures and docstrings:
- def _is_bidirectional(cls, s): Determines if a reaction is bi-directional based on the symbol between the reactants and prod... | Implement the Python class `StringExpressionParser` described below.
Class description:
An implementation of ExpressionParser for reading strings and forming
Method signatures and docstrings:
- def _is_bidirectional(cls, s): Determines if a reaction is bi-directional based on the symbol between the reactants and prod... | 4a625b0b00040a06f2b52ac74d60c636012f1dd4 | <|skeleton|>
class StringExpressionParser:
"""An implementation of ExpressionParser for reading strings and forming"""
def _is_bidirectional(cls, s):
"""Determines if a reaction is bi-directional based on the symbol between the reactants and products. :param s: a string which is formatted according to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringExpressionParser:
"""An implementation of ExpressionParser for reading strings and forming"""
def _is_bidirectional(cls, s):
"""Determines if a reaction is bi-directional based on the symbol between the reactants and products. :param s: a string which is formatted according to our conventio... | the_stack_v2_python_sparse | src/parsers.py | blawney/mycalc | train | 0 |
7bdc64a53691f704603177e663af144b6d360444 | [
"network_1 = Conv1DNetwork()\nself.assertEqual(len(network_1.layers), 4)\nself.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))\nfor layer in network_1.layers[0].layers:\n self.assertTrue(isinstance(layer, tx.core.SequentialLayer))\ninputs_1 = tf.ones([64, 16, 300], tf.float32)\... | <|body_start_0|>
network_1 = Conv1DNetwork()
self.assertEqual(len(network_1.layers), 4)
self.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx.core.MergeLayer))
for layer in network_1.layers[0].layers:
self.assertTrue(isinstance(layer, tx.core.SequentialLayer))... | Tests :class:`~texar.tf.modules.Conv1DNetwork` class. | Conv1DNetworkTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
... | stack_v2_sparse_classes_36k_train_019319 | 4,238 | permissive | [
{
"docstring": "Tests feed forward.",
"name": "test_feedforward",
"signature": "def test_feedforward(self)"
},
{
"docstring": "Tests use of pooling layer when the seq_length dimension of inputs is `None`.",
"name": "test_unknown_seq_length",
"signature": "def test_unknown_seq_length(self... | 3 | stack_v2_sparse_classes_30k_train_002931 | Implement the Python class `Conv1DNetworkTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DNetwork` class.
Method signatures and docstrings:
- def test_feedforward(self): Tests feed forward.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of ... | Implement the Python class `Conv1DNetworkTest` described below.
Class description:
Tests :class:`~texar.tf.modules.Conv1DNetwork` class.
Method signatures and docstrings:
- def test_feedforward(self): Tests feed forward.
- def test_unknown_seq_length(self): Tests use of pooling layer when the seq_length dimension of ... | 0704b3d4c93915b9a6f96b725e49ae20bf5d1e90 | <|skeleton|>
class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
<|body_0|>
def test_unknown_seq_length(self):
"""Tests use of pooling layer when the seq_length dimension of inputs is `None`."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv1DNetworkTest:
"""Tests :class:`~texar.tf.modules.Conv1DNetwork` class."""
def test_feedforward(self):
"""Tests feed forward."""
network_1 = Conv1DNetwork()
self.assertEqual(len(network_1.layers), 4)
self.assertTrue(isinstance(network_1.layer_by_name('conv_pool_1'), tx... | the_stack_v2_python_sparse | texar/tf/modules/networks/conv_networks_test.py | arita37/texar | train | 2 |
34eb3eabde4d8665502d141338d7b82776449095 | [
"if len(s) == 0:\n return ''\nvowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']\ntemp = []\nans = []\nvowels = []\nfor i in xrange(len(s)):\n if s[i] in vowelsTable:\n x = '~'\n vowels.append(s[i])\n else:\n x = s[i]\n temp.append(x)\nfor i in temp:\n if i == '~':\... | <|body_start_0|>
if len(s) == 0:
return ''
vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']
temp = []
ans = []
vowels = []
for i in xrange(len(s)):
if s[i] in vowelsTable:
x = '~'
vowels.append(s[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def reverseVowels_2_ptr(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_019320 | 2,402 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels2",
"signature": "def reverseVowels2(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name... | 3 | stack_v2_sparse_classes_30k_train_017960 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
- def reverseVowels_2_ptr(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
- def reverseVowels_2_ptr(self, s): :type s: str :rtype: str
<|skele... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def reverseVowels_2_ptr(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
if len(s) == 0:
return ''
vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']
temp = []
ans = []
vowels = []
for i in xrange(len(s)):
if s[i] in vow... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00345.Reverse_Vowels_of_a_String.py | roger6blog/LeetCode | train | 0 | |
5336b321557adf947b01d78ed7ff16ac6d32c140 | [
"if not head:\n return\ncurrNode, nodeList = (head, [])\nwhile currNode:\n nodeList.append(currNode)\n currNode = currNode.next\nleft, right = (0, len(nodeList) - 1)\nwhile left < right:\n nodeList[left].next = nodeList[right]\n if left + 1 >= right:\n nodeList[right].next = None\n else:\n ... | <|body_start_0|>
if not head:
return
currNode, nodeList = (head, [])
while currNode:
nodeList.append(currNode)
currNode = currNode.next
left, right = (0, len(nodeList) - 1)
while left < right:
nodeList[left].next = nodeList[right]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reorderList(self, head: ListNode) -> None:
"""通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)"""
<|body_0|>
def reorderList2(self, head: ListNode) -> None:
"""优化解法,时间复杂度O(n)空间复杂度O(1) 1.使用快慢指针寻找链表中点;2将尾部链表翻转;3将两个链表合并"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_019321 | 1,464 | no_license | [
{
"docstring": "通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)",
"name": "reorderList",
"signature": "def reorderList(self, head: ListNode) -> None"
},
{
"docstring": "优化解法,时间复杂度O(n)空间复杂度O(1) 1.使用快慢指针寻找链表中点;2将尾部链表翻转;3将两个链表合并",
"name": "reorderList2",
"signature": "def reorderList2(self, head: ListN... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head: ListNode) -> None: 通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)
- def reorderList2(self, head: ListNode) -> None: 优化解法,时间复杂度O(n)空间复杂度O(1) 1.使用快慢指针寻找链表中点;2将尾部链表... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head: ListNode) -> None: 通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)
- def reorderList2(self, head: ListNode) -> None: 优化解法,时间复杂度O(n)空间复杂度O(1) 1.使用快慢指针寻找链表中点;2将尾部链表... | d265eb981a7586d46d0ced3accc2ea186dc7691c | <|skeleton|>
class Solution:
def reorderList(self, head: ListNode) -> None:
"""通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)"""
<|body_0|>
def reorderList2(self, head: ListNode) -> None:
"""优化解法,时间复杂度O(n)空间复杂度O(1) 1.使用快慢指针寻找链表中点;2将尾部链表翻转;3将两个链表合并"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reorderList(self, head: ListNode) -> None:
"""通过遍历head链表所有节点重构,时间复杂度O(n)空间复杂度O(n)"""
if not head:
return
currNode, nodeList = (head, [])
while currNode:
nodeList.append(currNode)
currNode = currNode.next
left, right = (0... | the_stack_v2_python_sparse | pythonCode/No101-150/no143重排链表.py | odinfor/leetcode | train | 0 | |
a13b26b43ecf2b5712c5e0e98a895fd6bbeb8e88 | [
"if not table:\n return {}\nrecord_values = {}\nfor record in table.records:\n if parser_mediator.abort:\n break\n if record.get_number_of_values() != 2:\n continue\n identification = self._GetRecordValue(record, 0)\n filename = self._GetRecordValue(record, 1)\n if not identification... | <|body_start_0|>
if not table:
return {}
record_values = {}
for record in table.records:
if parser_mediator.abort:
break
if record.get_number_of_values() != 2:
continue
identification = self._GetRecordValue(record, 0... | Parses a File History ESE database file. | FileHistoryESEDBPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHistoryESEDBPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, parser_mediator, table):
"""Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other componen... | stack_v2_sparse_classes_36k_train_019322 | 4,191 | permissive | [
{
"docstring": "Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. table (pyesedb.table): strings table. Returns: dict[str,object]: values per column name.",
"name": "_GetDictFro... | 2 | null | Implement the Python class `FileHistoryESEDBPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, parser_mediator, table): Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator):... | Implement the Python class `FileHistoryESEDBPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, parser_mediator, table): Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator):... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class FileHistoryESEDBPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, parser_mediator, table):
"""Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other componen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileHistoryESEDBPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, parser_mediator, table):
"""Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s... | the_stack_v2_python_sparse | plaso/parsers/esedb_plugins/file_history.py | log2timeline/plaso | train | 1,506 |
2cb80e1bcc8046168061edb78acc8389fb88c62e | [
"super(JSTwoGaussian, self).__init__()\nassert isinstance(input_shape, tuple) and len(input_shape) == 1, '\"input_shape\" should be a tuple.'\nassert isinstance(output_shape, tuple) and len(output_shape) == 1, '\"output_shape\" should be a tuple.'\nassert output_shape[0] * 2 == input_shape[0], '\"output_shape\" is ... | <|body_start_0|>
super(JSTwoGaussian, self).__init__()
assert isinstance(input_shape, tuple) and len(input_shape) == 1, '"input_shape" should be a tuple.'
assert isinstance(output_shape, tuple) and len(output_shape) == 1, '"output_shape" should be a tuple.'
assert output_shape[0] * 2 == ... | JSTwoGaussian | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSTwoGaussian:
def __init__(self, input_shape, output_shape):
"""This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a tuple of three values, i.e., (input channel, input width, input height). output_shape: tuple a tuple ... | stack_v2_sparse_classes_36k_train_019323 | 19,014 | permissive | [
{
"docstring": "This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a tuple of three values, i.e., (input channel, input width, input height). output_shape: tuple a tuple of single value, i.e., (input channel,) or (input dim,).",
"name": "_... | 2 | null | Implement the Python class `JSTwoGaussian` described below.
Class description:
Implement the JSTwoGaussian class.
Method signatures and docstrings:
- def __init__(self, input_shape, output_shape): This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a... | Implement the Python class `JSTwoGaussian` described below.
Class description:
Implement the JSTwoGaussian class.
Method signatures and docstrings:
- def __init__(self, input_shape, output_shape): This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a... | 7585261dd1b1c6c99dada5d2d1aabf482e89e880 | <|skeleton|>
class JSTwoGaussian:
def __init__(self, input_shape, output_shape):
"""This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a tuple of three values, i.e., (input channel, input width, input height). output_shape: tuple a tuple ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSTwoGaussian:
def __init__(self, input_shape, output_shape):
"""This function initializes the class. The shape of two tensor should be double. Parameters ---------- input_shape: tuple a tuple of three values, i.e., (input channel, input width, input height). output_shape: tuple a tuple of single valu... | the_stack_v2_python_sparse | lemontree/objectives.py | khshim/lemontree | train | 3 | |
0c8e418d0dcbcd8a68827bfc0b7ed2dedd385c47 | [
"super(KFSmoothbatch, self).__init__(self.calc, multiproc=False)\nself.half_life = half_life\nself.batch_time = batch_time\nself.rho = np.exp(np.log(0.5) / (self.half_life / batch_time))",
"print('calculating new SB parameters')\nC_old = decoder.kf.C\nQ_old = decoder.kf.Q\ndrives_neurons = decoder.drives_neurons\... | <|body_start_0|>
super(KFSmoothbatch, self).__init__(self.calc, multiproc=False)
self.half_life = half_life
self.batch_time = batch_time
self.rho = np.exp(np.log(0.5) / (self.half_life / batch_time))
<|end_body_0|>
<|body_start_1|>
print('calculating new SB parameters')
... | Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details | KFSmoothbatch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KFSmoothbatch:
"""Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details"""
def __init__(self, batch_time, half_life... | stack_v2_sparse_classes_36k_train_019324 | 43,699 | permissive | [
{
"docstring": "Constructor for KFSmoothbatch Parameters ---------- batch_time : float Time over which to collect sample data half_life : float Time over which parameters are half-overwritten Return ------ KFSmoothbatch instance",
"name": "__init__",
"signature": "def __init__(self, batch_time, half_lif... | 2 | null | Implement the Python class `KFSmoothbatch` described below.
Class description:
Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details
Method s... | Implement the Python class `KFSmoothbatch` described below.
Class description:
Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details
Method s... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class KFSmoothbatch:
"""Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details"""
def __init__(self, batch_time, half_life... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KFSmoothbatch:
"""Deprecation Warning: This update method has not been used for quite long. See KFRML for an enhanced but similar method Calculate KF Parameter updates using the SmoothBatch method. See [Orsborn et al, 2012] for mathematical details"""
def __init__(self, batch_time, half_life):
""... | the_stack_v2_python_sparse | riglib/bmi/clda.py | carmenalab/brain-python-interface | train | 9 |
b361b6c9b6aaaff111500ef745926090450371d7 | [
"session = requests.Session()\nif path:\n with open(path, mode='rb') as f:\n request = requests.Request(method, url, headers=headers, data=f)\n prepped = request.prepare()\n response = session.send(prepped, timeout=SOCKET_TIMEOUT)\nelse:\n request = requests.Request(method, url, headers=h... | <|body_start_0|>
session = requests.Session()
if path:
with open(path, mode='rb') as f:
request = requests.Request(method, url, headers=headers, data=f)
prepped = request.prepare()
response = session.send(prepped, timeout=SOCKET_TIMEOUT)
... | HttpProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpProvider:
def send(self, method, headers, url, data=None, content=None, path=None):
"""Send the built request using all the specified parameters. Args: method (str): The HTTP method to use (ex. GET) headers (dict of (str, str)): A dictionary of name-value pairs for headers in the req... | stack_v2_sparse_classes_36k_train_019325 | 4,433 | permissive | [
{
"docstring": "Send the built request using all the specified parameters. Args: method (str): The HTTP method to use (ex. GET) headers (dict of (str, str)): A dictionary of name-value pairs for headers in the request url (str): The URL for the request to be sent to data (str): Defaults to None, data to include... | 2 | null | Implement the Python class `HttpProvider` described below.
Class description:
Implement the HttpProvider class.
Method signatures and docstrings:
- def send(self, method, headers, url, data=None, content=None, path=None): Send the built request using all the specified parameters. Args: method (str): The HTTP method t... | Implement the Python class `HttpProvider` described below.
Class description:
Implement the HttpProvider class.
Method signatures and docstrings:
- def send(self, method, headers, url, data=None, content=None, path=None): Send the built request using all the specified parameters. Args: method (str): The HTTP method t... | a5151a43c44acf61c513efdf286d40234c0795f0 | <|skeleton|>
class HttpProvider:
def send(self, method, headers, url, data=None, content=None, path=None):
"""Send the built request using all the specified parameters. Args: method (str): The HTTP method to use (ex. GET) headers (dict of (str, str)): A dictionary of name-value pairs for headers in the req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpProvider:
def send(self, method, headers, url, data=None, content=None, path=None):
"""Send the built request using all the specified parameters. Args: method (str): The HTTP method to use (ex. GET) headers (dict of (str, str)): A dictionary of name-value pairs for headers in the request url (str)... | the_stack_v2_python_sparse | src/onedrivesdk_fork/http_provider.py | AtakamaLLC/onedrive-sdk-python | train | 20 | |
c51d341dc6b272ad040958710304662e846cc107 | [
"self.namespace = '{http://www.opengis.net/wms}'\nif caps.getroot().find('Service') is not None:\n self.use_ns = False\nelif caps.getroot().find(self.namespace + 'Service') is not None:\n self.use_ns = True\nelse:\n raise etree.ParseError(_('Unable to parse capabilities file.\\n ... | <|body_start_0|>
self.namespace = '{http://www.opengis.net/wms}'
if caps.getroot().find('Service') is not None:
self.use_ns = False
elif caps.getroot().find(self.namespace + 'Service') is not None:
self.use_ns = True
else:
raise etree.ParseError(_('Una... | WMSXMLNsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WMSXMLNsHandler:
def __init__(self, caps):
"""!Handle XML namespaces according to WMS version of capabilities."""
<|body_0|>
def Ns(self, tag_name):
"""!Add namespace to tag_name according to version"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_019326 | 22,644 | no_license | [
{
"docstring": "!Handle XML namespaces according to WMS version of capabilities.",
"name": "__init__",
"signature": "def __init__(self, caps)"
},
{
"docstring": "!Add namespace to tag_name according to version",
"name": "Ns",
"signature": "def Ns(self, tag_name)"
}
] | 2 | null | Implement the Python class `WMSXMLNsHandler` described below.
Class description:
Implement the WMSXMLNsHandler class.
Method signatures and docstrings:
- def __init__(self, caps): !Handle XML namespaces according to WMS version of capabilities.
- def Ns(self, tag_name): !Add namespace to tag_name according to version | Implement the Python class `WMSXMLNsHandler` described below.
Class description:
Implement the WMSXMLNsHandler class.
Method signatures and docstrings:
- def __init__(self, caps): !Handle XML namespaces according to WMS version of capabilities.
- def Ns(self, tag_name): !Add namespace to tag_name according to version... | 8f56d3ab47c5e845812231d20234b30c0230c8a2 | <|skeleton|>
class WMSXMLNsHandler:
def __init__(self, caps):
"""!Handle XML namespaces according to WMS version of capabilities."""
<|body_0|>
def Ns(self, tag_name):
"""!Add namespace to tag_name according to version"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WMSXMLNsHandler:
def __init__(self, caps):
"""!Handle XML namespaces according to WMS version of capabilities."""
self.namespace = '{http://www.opengis.net/wms}'
if caps.getroot().find('Service') is not None:
self.use_ns = False
elif caps.getroot().find(self.namespa... | the_stack_v2_python_sparse | grass6/raster/r.in.wms2/wms_cap_parsers.py | Tekpre012/grass-addons | train | 1 | |
5214ef7af28235be78ecae59458aded32c00b3ee | [
"super().__init__()\nself.keys = []\nself.freq = {}",
"if key is not None and item is not None:\n if len(self.keys) >= BaseCaching.MAX_ITEMS and key not in self.keys:\n lfu = self.keys.pop(self.keys.index(self.find_lessFreq()))\n del self.freq[lfu]\n del self.cache_data[lfu]\n print... | <|body_start_0|>
super().__init__()
self.keys = []
self.freq = {}
<|end_body_0|>
<|body_start_1|>
if key is not None and item is not None:
if len(self.keys) >= BaseCaching.MAX_ITEMS and key not in self.keys:
lfu = self.keys.pop(self.keys.index(self.find_lessF... | manage the cache | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
<|body_0|>
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
<|body_1|>
def get(self, key):
"""Get an item by key using LFU"""
... | stack_v2_sparse_classes_36k_train_019327 | 1,623 | no_license | [
{
"docstring": "auto call function",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "add an item in the cache using Least-frequently used",
"name": "put",
"signature": "def put(self, key, item)"
},
{
"docstring": "Get an item by key using LFU",
"name"... | 4 | stack_v2_sparse_classes_30k_train_013125 | Implement the Python class `LFUCache` described below.
Class description:
manage the cache
Method signatures and docstrings:
- def __init__(self): auto call function
- def put(self, key, item): add an item in the cache using Least-frequently used
- def get(self, key): Get an item by key using LFU
- def find_lessFreq(... | Implement the Python class `LFUCache` described below.
Class description:
manage the cache
Method signatures and docstrings:
- def __init__(self): auto call function
- def put(self, key, item): add an item in the cache using Least-frequently used
- def get(self, key): Get an item by key using LFU
- def find_lessFreq(... | 251d28c9b555096c61a7112ada43dc65576d03c5 | <|skeleton|>
class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
<|body_0|>
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
<|body_1|>
def get(self, key):
"""Get an item by key using LFU"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
super().__init__()
self.keys = []
self.freq = {}
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
if key is not None and item is not None:... | the_stack_v2_python_sparse | 0x03-caching/100-lfu_cache.py | dgquintero/holbertonschool-web_back_end | train | 0 |
e624f11ba7bd9bd048404b9e738168366c2c85d3 | [
"super().__init__(*args, **kwargs)\nself.fields['first_name'].required = False\nself.fields['last_name'].required = False\nself.fields['institution'].required = False\nself.fields['institution_logo'].required = False\nself.fields['allow_notifications'].required = False",
"cleaned_data = super().clean()\ncleaned_d... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.fields['first_name'].required = False
self.fields['last_name'].required = False
self.fields['institution'].required = False
self.fields['institution_logo'].required = False
self.fields['allow_notifications'].required... | Profile form used to update users | ProfileForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileForm:
"""Profile form used to update users"""
def __init__(self, *args, **kwargs):
"""Sets the fields as not required"""
<|body_0|>
def clean(self):
"""Returns cleaned data only if is not none"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019328 | 5,975 | no_license | [
{
"docstring": "Sets the fields as not required",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Returns cleaned data only if is not none",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016136 | Implement the Python class `ProfileForm` described below.
Class description:
Profile form used to update users
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Sets the fields as not required
- def clean(self): Returns cleaned data only if is not none | Implement the Python class `ProfileForm` described below.
Class description:
Profile form used to update users
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Sets the fields as not required
- def clean(self): Returns cleaned data only if is not none
<|skeleton|>
class ProfileForm:
"""Pr... | 8ff935383fa9355d4f47c358a9971cff8ab8a92c | <|skeleton|>
class ProfileForm:
"""Profile form used to update users"""
def __init__(self, *args, **kwargs):
"""Sets the fields as not required"""
<|body_0|>
def clean(self):
"""Returns cleaned data only if is not none"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileForm:
"""Profile form used to update users"""
def __init__(self, *args, **kwargs):
"""Sets the fields as not required"""
super().__init__(*args, **kwargs)
self.fields['first_name'].required = False
self.fields['last_name'].required = False
self.fields['insti... | the_stack_v2_python_sparse | accounts/forms.py | cesardlinx/asistentecatedra | train | 1 |
58d3221be982627f8f28b3f01ecd59f961cf2b64 | [
"i = 0\nwhile i != row:\n if borad[i][col] == 'Q':\n return False\n i += 1\ni, j = (row - 1, col - 1)\nwhile i >= 0 and j >= 0:\n if borad[i][j] == 'Q':\n return False\n i -= 1\n j -= 1\ni, j = (row - 1, col + 1)\nwhile i >= 0 and j < n:\n if borad[i][j] == 'Q':\n return False... | <|body_start_0|>
i = 0
while i != row:
if borad[i][col] == 'Q':
return False
i += 1
i, j = (row - 1, col - 1)
while i >= 0 and j >= 0:
if borad[i][j] == 'Q':
return False
i -= 1
j -= 1
i, ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkvalid(self, borad, row, col, n):
"""set board[row][col]=='Q' check whether it's valid result"""
<|body_0|>
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
... | stack_v2_sparse_classes_36k_train_019329 | 1,288 | permissive | [
{
"docstring": "set board[row][col]=='Q' check whether it's valid result",
"name": "checkvalid",
"signature": "def checkvalid(self, borad, row, col, n)"
},
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002279 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkvalid(self, borad, row, col, n): set board[row][col]=='Q' check whether it's valid result
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkvalid(self, borad, row, col, n): set board[row][col]=='Q' check whether it's valid result
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
<|skeleton|>... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def checkvalid(self, borad, row, col, n):
"""set board[row][col]=='Q' check whether it's valid result"""
<|body_0|>
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkvalid(self, borad, row, col, n):
"""set board[row][col]=='Q' check whether it's valid result"""
i = 0
while i != row:
if borad[i][col] == 'Q':
return False
i += 1
i, j = (row - 1, col - 1)
while i >= 0 and j >= ... | the_stack_v2_python_sparse | 51-N-Queens/solution.py | Tanych/CodeTracking | train | 0 | |
6b00a9bf98504e604ea482a9cddc3674ce47d7cf | [
"hex_addr = _HexAddressRegexpFor(android_abi)\nself._re_map_section = re.compile('\\\\s*(?P<addr_start>' + hex_addr + ')-(?P<addr_end>' + hex_addr + ')' + '\\\\s+' + '(?P<perm>...)\\\\s+' + '(?P<file_offset>[0-9a-f]+)\\\\s+' + '(?P<file_size>[0-9a-f]+)\\\\s*' + '(?P<file_path>[^ \\\\t]+)?')\nself._addr_map = []\nse... | <|body_start_0|>
hex_addr = _HexAddressRegexpFor(android_abi)
self._re_map_section = re.compile('\\s*(?P<addr_start>' + hex_addr + ')-(?P<addr_end>' + hex_addr + ')' + '\\s+' + '(?P<perm>...)\\s+' + '(?P<file_offset>[0-9a-f]+)\\s+' + '(?P<file_size>[0-9a-f]+)\\s*' + '(?P<file_path>[^ \\t]+)?')
s... | Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole memory map input with ParseLines(), then call FindSectionForAddress() repeated... | MemoryMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoryMap:
"""Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole memory map input with ParseLines(), then ... | stack_v2_sparse_classes_36k_train_019330 | 28,535 | permissive | [
{
"docstring": "Initializes instance. Args: android_abi: Android CPU ABI name (e.g. 'armeabi-v7a')",
"name": "__init__",
"signature": "def __init__(self, android_abi)"
},
{
"docstring": "Try to translate a memory map input line, if detected. This only takes care of converting mapped APK file pat... | 6 | null | Implement the Python class `MemoryMap` described below.
Class description:
Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole me... | Implement the Python class `MemoryMap` described below.
Class description:
Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole me... | acefdaaadd3ef46f10f63d1acae2259e4024d383 | <|skeleton|>
class MemoryMap:
"""Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole memory map input with ParseLines(), then ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemoryMap:
"""Models the memory map of a given process. Usage is: 1) Create new instance, passing the Android ABI. 2) Call TranslateLine() whenever you want to detect and translate any memory map input line. 3) Otherwise, it is possible to parse the whole memory map input with ParseLines(), then call FindSect... | the_stack_v2_python_sparse | build/android/pylib/symbols/symbol_utils.py | youtube/cobalt | train | 169 |
46b2f7ce35f6a03d6687632196fe2f09abcacd2c | [
"event_list_container = response.css('dl.simcal-events-list-container')\nfor event_date, event_details in zip(event_list_container.css('dt.simcal-day-label'), event_list_container.css('dd.simcal-day')):\n date = event_date.css('.simcal-date-format::text').get()\n for event_detail in event_details.css('li.simc... | <|body_start_0|>
event_list_container = response.css('dl.simcal-events-list-container')
for event_date, event_details in zip(event_list_container.css('dt.simcal-day-label'), event_list_container.css('dd.simcal-day')):
date = event_date.css('.simcal-date-format::text').get()
for e... | Spider to crawl Heritage's website. | HeritageSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
<|body_0|>
def format_datetime(self, date_string, time_string):
"""Given a time and date in ... | stack_v2_sparse_classes_36k_train_019331 | 2,595 | no_license | [
{
"docstring": "Parse the html for performance information and yield PerformanceItem instances.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Given a time and date in string form, format the date so that it is in the format month/day/year hour:minute.",
"name... | 2 | stack_v2_sparse_classes_30k_train_013521 | Implement the Python class `HeritageSpider` described below.
Class description:
Spider to crawl Heritage's website.
Method signatures and docstrings:
- def parse(self, response): Parse the html for performance information and yield PerformanceItem instances.
- def format_datetime(self, date_string, time_string): Give... | Implement the Python class `HeritageSpider` described below.
Class description:
Spider to crawl Heritage's website.
Method signatures and docstrings:
- def parse(self, response): Parse the html for performance information and yield PerformanceItem instances.
- def format_datetime(self, date_string, time_string): Give... | d5ae552d383f5f971e29a38055c518fc68172f32 | <|skeleton|>
class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
<|body_0|>
def format_datetime(self, date_string, time_string):
"""Given a time and date in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeritageSpider:
"""Spider to crawl Heritage's website."""
def parse(self, response):
"""Parse the html for performance information and yield PerformanceItem instances."""
event_list_container = response.css('dl.simcal-events-list-container')
for event_date, event_details in zip(ev... | the_stack_v2_python_sparse | server/app/performance_scraper/performance_scraper/spiders/heritage_spider.py | EricMontague/MailChimp-Newsletter-Project | train | 0 |
1df6800ea70dd88fd38a98221015040fd29c3c01 | [
"self.createform = forms.QuotationForm(request.POST)\nif self.createform.is_valid():\n req = {'name': self.createform.cleaned_data['name'], 'email': self.createform.cleaned_data['email'], 'phone': self.createform.cleaned_data['phone'], 'vehiculeModel': self.createform.cleaned_data['vehiculeModel'], 'vehiculeYear... | <|body_start_0|>
self.createform = forms.QuotationForm(request.POST)
if self.createform.is_valid():
req = {'name': self.createform.cleaned_data['name'], 'email': self.createform.cleaned_data['email'], 'phone': self.createform.cleaned_data['phone'], 'vehiculeModel': self.createform.cleaned_da... | Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view | QuotationCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuotationCreateView:
"""Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view"""
def post(self, request):
"""Validate and send a post request to the API"""
<|body_0|>
def get(self, request):
"""Initialize the form fo... | stack_v2_sparse_classes_36k_train_019332 | 4,483 | no_license | [
{
"docstring": "Validate and send a post request to the API",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Initialize the form for `:model:`Quotation creation via API",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019643 | Implement the Python class `QuotationCreateView` described below.
Class description:
Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view
Method signatures and docstrings:
- def post(self, request): Validate and send a post request to the API
- def get(self, request): I... | Implement the Python class `QuotationCreateView` described below.
Class description:
Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view
Method signatures and docstrings:
- def post(self, request): Validate and send a post request to the API
- def get(self, request): I... | f7ad1ece8ff4788f99f9cf6a0538c0aaa3653554 | <|skeleton|>
class QuotationCreateView:
"""Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view"""
def post(self, request):
"""Validate and send a post request to the API"""
<|body_0|>
def get(self, request):
"""Initialize the form fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuotationCreateView:
"""Form for :model:`Quotation creation` Automtically generate the email TODO do this in the detail view"""
def post(self, request):
"""Validate and send a post request to the API"""
self.createform = forms.QuotationForm(request.POST)
if self.createform.is_vali... | the_stack_v2_python_sparse | quotations/views.py | GuillaumeGSO/MotorQuotationLab | train | 0 |
ff4986d247f8aee25bf3bbade1aa513a48303284 | [
"init_weights = 'glorot_uniform'\nsuper(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(output_dim=embedding, input_dim=vocab)\nself.gru = tf.keras.layers.GRU(units=units, recurrent_initializer=init_weights, return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(units=voc... | <|body_start_0|>
init_weights = 'glorot_uniform'
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(output_dim=embedding, input_dim=vocab)
self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer=init_weights, return_sequences=True, return_state=True)
... | class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description] | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description]"""
def __init__(self, vocab, embedding, units, batch):
"""[Class constructor] Args: vocab ([int]): [size of the input vocabulary] embedding ([int]):... | stack_v2_sparse_classes_36k_train_019333 | 2,937 | no_license | [
{
"docstring": "[Class constructor] Args: vocab ([int]): [size of the input vocabulary] embedding ([int]): [dimensionality of the embedding vector] units ([int]): [number of hidden units in the RNN cell] batch ([int]): [batch size instance attributes] Attributes: batch Batch size units Number of hidden units in... | 2 | stack_v2_sparse_classes_30k_train_011080 | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): [Class constructor] Args: vocab (... | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): [Class constructor] Args: vocab (... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class RNNDecoder:
"""class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description]"""
def __init__(self, vocab, embedding, units, batch):
"""[Class constructor] Args: vocab ([int]): [size of the input vocabulary] embedding ([int]):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""class RNNEncoder Inherits from tensorflow.keras.layers.Layer to encode 4 ML translation Args: tf ([type]): [description]"""
def __init__(self, vocab, embedding, units, batch):
"""[Class constructor] Args: vocab ([int]): [size of the input vocabulary] embedding ([int]): [dimensional... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
eb4ed989f04dcdce30a03f0b2cce08868ac1a1de | [
"super(Inception4e, self).__init__()\nself.branch1 = paddle.nn.Sequential(ConvBNLayer(num_channels=num_channels, num_filters=ch3x3reduced, filter_size=1, stride=1, padding=0), ConvBNLayer(num_channels=ch3x3reduced, num_filters=ch3x3, filter_size=3, stride=2, padding=1))\nself.branch2 = paddle.nn.Sequential(ConvBNLa... | <|body_start_0|>
super(Inception4e, self).__init__()
self.branch1 = paddle.nn.Sequential(ConvBNLayer(num_channels=num_channels, num_filters=ch3x3reduced, filter_size=1, stride=1, padding=0), ConvBNLayer(num_channels=ch3x3reduced, num_filters=ch3x3, filter_size=3, stride=2, padding=1))
self.branc... | Inception4e | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inception4e:
def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception4e` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of... | stack_v2_sparse_classes_36k_train_019334 | 23,805 | permissive | [
{
"docstring": "@Brief `Inception4e` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv before 3x3 conv ch3x3 : output channel numbers of 3x3 conv doublech3x3reduced : channel numbers of 1x1 conv before the double 3x3 ... | 2 | null | Implement the Python class `Inception4e` described below.
Class description:
Implement the Inception4e class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception4e` @Parameters num_channels : channel ... | Implement the Python class `Inception4e` described below.
Class description:
Implement the Inception4e class.
Method signatures and docstrings:
- def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj): @Brief `Inception4e` @Parameters num_channels : channel ... | 78ff3c3ab3906012a0f4a612251347632aa493a7 | <|skeleton|>
class Inception4e:
def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception4e` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inception4e:
def __init__(self, num_channels, ch3x3reduced, ch3x3, doublech3x3reduced, doublech3x3_1, doublech3x3_2, pool_proj):
"""@Brief `Inception4e` @Parameters num_channels : channel numbers of input tensor ch1x1 : output channel numbers of 1x1 conv ch3x3reduced : channel numbers of 1x1 conv befo... | the_stack_v2_python_sparse | ECO/paddle2.0/model/ECO.py | thinkall/Contrib | train | 1 | |
6f8a9c66498766945e42cd2777b8ccc31a59754e | [
"self.bandwidth_bytes_per_second = bandwidth_bytes_per_second\nself.cassandra_recover_job_params = cassandra_recover_job_params\nself.concurrency = concurrency\nself.couchbase_recover_job_params = couchbase_recover_job_params\nself.hbase_recover_job_params = hbase_recover_job_params\nself.hdfs_recover_job_params = ... | <|body_start_0|>
self.bandwidth_bytes_per_second = bandwidth_bytes_per_second
self.cassandra_recover_job_params = cassandra_recover_job_params
self.concurrency = concurrency
self.couchbase_recover_job_params = couchbase_recover_job_params
self.hbase_recover_job_params = hbase_rec... | Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params specific to cassandra recover job. concurrency (int): Max number of mappers couchbase_recov... | NoSqlRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoSqlRecoverJobParams:
"""Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params specific to cassandra recover job. concurr... | stack_v2_sparse_classes_36k_train_019335 | 6,314 | permissive | [
{
"docstring": "Constructor for the NoSqlRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, bandwidth_bytes_per_second=None, cassandra_recover_job_params=None, concurrency=None, couchbase_recover_job_params=None, hbase_recover_job_params=None, hdfs_recover_job_params=None, hiv... | 2 | null | Implement the Python class `NoSqlRecoverJobParams` described below.
Class description:
Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params spe... | Implement the Python class `NoSqlRecoverJobParams` described below.
Class description:
Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params spe... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NoSqlRecoverJobParams:
"""Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params specific to cassandra recover job. concurr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoSqlRecoverJobParams:
"""Implementation of the 'NoSqlRecoverJobParams' model. TODO: type description here. Attributes: bandwidth_bytes_per_second (long|int): Net bandwidth bytes per second cassandra_recover_job_params (CassandraRecoverJobParams): Params specific to cassandra recover job. concurrency (int): M... | the_stack_v2_python_sparse | cohesity_management_sdk/models/no_sql_recover_job_params.py | cohesity/management-sdk-python | train | 24 |
3d3d8bab58ae8312b8f256cdb1fc23b1b535385f | [
"self.capacity = capacity\nself.cache = {}\nself.count_to_node = collections.defaultdict(collections.OrderedDict)\nself.min_count = 0",
"if key not in self.cache:\n return -1\nnode = self.cache[key]\ndel self.count_to_node[node.count][key]\nnode.count += 1\nself.count_to_node[node.count][key] = node\nif not se... | <|body_start_0|>
self.capacity = capacity
self.cache = {}
self.count_to_node = collections.defaultdict(collections.OrderedDict)
self.min_count = 0
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
node = self.cache[key]
del self.coun... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_019336 | 3,450 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 54ff328131bf2ef387292f31a0e2a2c2cf612cdd | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = {}
self.count_to_node = collections.defaultdict(collections.OrderedDict)
self.min_count = 0
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | hashtable/460.lfu-cache.py | hjlarry/leetcode | train | 0 | |
e06fb8c1064aa1dcfcf8cef4a7d54ac17f5c084e | [
"self.capacity = capacity\nself.size = 0\nself.cache = dict()\nself.cachelist = DoubleList()",
"if key not in self.cache:\n return -1\nnode = self.cache[key]\nself.cachelist.delete(node)\nself.cachelist.append(node)\nreturn node.val",
"if key in self.cache:\n node = self.cache[key]\n node.val = value\n... | <|body_start_0|>
self.capacity = capacity
self.size = 0
self.cache = dict()
self.cachelist = DoubleList()
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
node = self.cache[key]
self.cachelist.delete(node)
self.cachelist.app... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_019337 | 2,925 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_007700 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.size = 0
self.cache = dict()
self.cachelist = DoubleList()
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
ret... | the_stack_v2_python_sparse | Tencent/midum/LRU缓存.py | 2226171237/Algorithmpractice | train | 0 | |
8f364b2151b821d8ce85ebe1ce3a3d4ffed67940 | [
"n = len(arr)\nleft = [float('inf') for _ in range(n)]\nright = [float('inf') for _ in range(n)]\npresum = {0: -1}\ncurr = 0\nfor i in range(n):\n curr += arr[i]\n if i > 0:\n left[i] = left[i - 1]\n if curr - target in presum:\n left[i] = min(left[i], i - presum[curr - target])\n presum[c... | <|body_start_0|>
n = len(arr)
left = [float('inf') for _ in range(n)]
right = [float('inf') for _ in range(n)]
presum = {0: -1}
curr = 0
for i in range(n):
curr += arr[i]
if i > 0:
left[i] = left[i - 1]
if curr - target ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
"""left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(left[i] + right[i + 1] for i: 0 to n - 2)"""
<|body_0|>
def minSumOfLengths(self, arr: ... | stack_v2_sparse_classes_36k_train_019338 | 3,270 | no_license | [
{
"docstring": "left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(left[i] + right[i + 1] for i: 0 to n - 2)",
"name": "minSumOfLengths",
"signature": "def minSumOfLengths(self, arr: List[int], target: int) -> int"
},
{
"docstring": "d... | 2 | stack_v2_sparse_classes_30k_train_005353 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSumOfLengths(self, arr: List[int], target: int) -> int: left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(lef... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSumOfLengths(self, arr: List[int], target: int) -> int: left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(lef... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
"""left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(left[i] + right[i + 1] for i: 0 to n - 2)"""
<|body_0|>
def minSumOfLengths(self, arr: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
"""left: left[i] is min subarr len to the left of i right: right[i] is min subarr len to the right of i return min(left[i] + right[i + 1] for i: 0 to n - 2)"""
n = len(arr)
left = [float('inf') for _ in range(n)]
... | the_stack_v2_python_sparse | Leetcode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum.py | Chaoran-sjsu/leetcode | train | 0 | |
0a57c5a3170437619a128837257a2b49a44eddab | [
"super(PingCommand, self).__init__()\nself.target = target\nself.connection = connection\nself.operating_system = operating_system\nself._arguments = None\nself._expression = None\nreturn",
"if self._arguments is None:\n try:\n self._arguments = PingArguments.arguments[self.operating_system] + self.targ... | <|body_start_0|>
super(PingCommand, self).__init__()
self.target = target
self.connection = connection
self.operating_system = operating_system
self._arguments = None
self._expression = None
return
<|end_body_0|>
<|body_start_1|>
if self._arguments is Non... | A ping is a simple ping-command. | PingCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PingCommand:
"""A ping is a simple ping-command."""
def __init__(self, target=None, connection=None, operating_system=None):
"""PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to the device - `operating_system`: The operating system of ... | stack_v2_sparse_classes_36k_train_019339 | 4,487 | permissive | [
{
"docstring": "PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to the device - `operating_system`: The operating system of the device",
"name": "__init__",
"signature": "def __init__(self, target=None, connection=None, operating_system=None)"
},
{
... | 5 | null | Implement the Python class `PingCommand` described below.
Class description:
A ping is a simple ping-command.
Method signatures and docstrings:
- def __init__(self, target=None, connection=None, operating_system=None): PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to ... | Implement the Python class `PingCommand` described below.
Class description:
A ping is a simple ping-command.
Method signatures and docstrings:
- def __init__(self, target=None, connection=None, operating_system=None): PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to ... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class PingCommand:
"""A ping is a simple ping-command."""
def __init__(self, target=None, connection=None, operating_system=None):
"""PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to the device - `operating_system`: The operating system of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PingCommand:
"""A ping is a simple ping-command."""
def __init__(self, target=None, connection=None, operating_system=None):
"""PingCommand constructor :param: - `target`: An IP Address to ping. - `connection`: A Connection to the device - `operating_system`: The operating system of the device"""... | the_stack_v2_python_sparse | apetools/commands/ping.py | russell-n/oldape | train | 0 |
faa1d067a94a8260c9c89bc63aff5b7717e431d5 | [
"super().__init__()\nself.nmeas_respmat = 10\nself.nmeas_beta = 10\nself.filename = 'variation'",
"dtmp = '{0:26s} = {1:9d} {2:s}\\n'.format\nstg = dtmp('nmeas_beta', self.nmeas_beta, '')\nstg += dtmp('nmeas_respmat', self.nmeas_respmat, '')\nstg += f\"filename = '{self.filename:s}'\\n\"\nreturn stg"
] | <|body_start_0|>
super().__init__()
self.nmeas_respmat = 10
self.nmeas_beta = 10
self.filename = 'variation'
<|end_body_0|>
<|body_start_1|>
dtmp = '{0:26s} = {1:9d} {2:s}\n'.format
stg = dtmp('nmeas_beta', self.nmeas_beta, '')
stg += dtmp('nmeas_respmat', self.... | . | RespMatBetaParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RespMatBetaParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.nmeas_respmat = 10
self.nmeas_beta = 10
self.filename = 'va... | stack_v2_sparse_classes_36k_train_019340 | 3,801 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003350 | Implement the Python class `RespMatBetaParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `RespMatBetaParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class RespMatBetaParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class RespMatBetaParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RespMatBetaParams:
"""."""
def __init__(self):
"""."""
super().__init__()
self.nmeas_respmat = 10
self.nmeas_beta = 10
self.filename = 'variation'
def __str__(self):
"""."""
dtmp = '{0:26s} = {1:9d} {2:s}\n'.format
stg = dtmp('nmeas_be... | the_stack_v2_python_sparse | apsuite/commisslib/measure_respm_beta.py | lnls-fac/apsuite | train | 1 |
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59 | [
"user = request.user\ncheck_user_status(user)\nuser_id = user.id\nrestaurant = PendingRestaurant.get_by_owner(user_id)\nform = RestaurantMediaForm(request.data, request.FILES)\nif not form.is_valid():\n raise ValidationError(message=form.errors, code='invalid_input')\nrestaurant = PendingRestaurant.upload_media(... | <|body_start_0|>
user = request.user
check_user_status(user)
user_id = user.id
restaurant = PendingRestaurant.get_by_owner(user_id)
form = RestaurantMediaForm(request.data, request.FILES)
if not form.is_valid():
raise ValidationError(message=form.errors, code=... | Restaurant media (image/video) view | RestaurantMediaView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestaurantMediaView:
"""Restaurant media (image/video) view"""
def put(self, request):
"""For inserting or updating restaurant media"""
<|body_0|>
def delete(self, request):
"""For removing image(s) from the restaurant_image_url field and Google Cloud bucket"""
... | stack_v2_sparse_classes_36k_train_019341 | 19,356 | no_license | [
{
"docstring": "For inserting or updating restaurant media",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "For removing image(s) from the restaurant_image_url field and Google Cloud bucket",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004966 | Implement the Python class `RestaurantMediaView` described below.
Class description:
Restaurant media (image/video) view
Method signatures and docstrings:
- def put(self, request): For inserting or updating restaurant media
- def delete(self, request): For removing image(s) from the restaurant_image_url field and Goo... | Implement the Python class `RestaurantMediaView` described below.
Class description:
Restaurant media (image/video) view
Method signatures and docstrings:
- def put(self, request): For inserting or updating restaurant media
- def delete(self, request): For removing image(s) from the restaurant_image_url field and Goo... | 2707062c9a9a8bb4baca955e8a60ba08cc9f8953 | <|skeleton|>
class RestaurantMediaView:
"""Restaurant media (image/video) view"""
def put(self, request):
"""For inserting or updating restaurant media"""
<|body_0|>
def delete(self, request):
"""For removing image(s) from the restaurant_image_url field and Google Cloud bucket"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestaurantMediaView:
"""Restaurant media (image/video) view"""
def put(self, request):
"""For inserting or updating restaurant media"""
user = request.user
check_user_status(user)
user_id = user.id
restaurant = PendingRestaurant.get_by_owner(user_id)
form =... | the_stack_v2_python_sparse | backend/restaurant/views.py | MochiTarts/Find-Dining-The-Bridge | train | 1 |
602861e02c85ec6f0bda94c74be302830841db2e | [
"logger.info('Overriding class: Space -> HyperComplexSpace.')\nlower_bound = np.zeros(n_variables)\nupper_bound = np.ones(n_variables)\nsuper(HyperComplexSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)\nself.build()\nlogger.info('Class overrided.')",
"for agent in sel... | <|body_start_0|>
logger.info('Overriding class: Space -> HyperComplexSpace.')
lower_bound = np.zeros(n_variables)
upper_bound = np.ones(n_variables)
super(HyperComplexSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)
self.build()
... | An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space. | HyperComplexSpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args... | stack_v2_sparse_classes_36k_train_019342 | 1,466 | permissive | [
{
"docstring": "Initialization method. Args: n_agents: Number of agents. n_variables: Number of decision variables. n_dimensions: Number of search space dimensions. mapping: String-based identifiers for mapping variables' names.",
"name": "__init__",
"signature": "def __init__(self, n_agents: int, n_var... | 2 | stack_v2_sparse_classes_30k_train_004584 | Implement the Python class `HyperComplexSpace` described below.
Class description:
An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optio... | Implement the Python class `HyperComplexSpace` described below.
Class description:
An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optio... | 7326a887ed8e3858bc99c8815048d56d02edf88c | <|skeleton|>
class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args: n_agents: N... | the_stack_v2_python_sparse | opytimizer/spaces/hyper_complex.py | gugarosa/opytimizer | train | 602 |
35f38c64fa2560d5152ce761dddaf6573982eb53 | [
"count = 0\ncnt_words = {}\nfor word in words:\n cnt_words[word] = cnt_words.get(word, 0) + 1\nfor word in cnt_words.keys():\n if self.isSubsequence(word, S):\n count += cnt_words[word]\nreturn count",
"idx = 0\nfor c in s:\n idx = t.find(c, idx)\n if idx == -1:\n return False\n idx +... | <|body_start_0|>
count = 0
cnt_words = {}
for word in words:
cnt_words[word] = cnt_words.get(word, 0) + 1
for word in cnt_words.keys():
if self.isSubsequence(word, S):
count += cnt_words[word]
return count
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
... | stack_v2_sparse_classes_36k_train_019343 | 3,821 | permissive | [
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseq",
"signature": "def numMatchingSubseq(self, S, words)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002224 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class... | 34d34280170c991ea7a28d74a3f2338753844917 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
count = 0
cnt_words = {}
for word in words:
cnt_words[word] = cnt_words.get(word, 0) + 1
for word in cnt_words.keys():
if self.isSubsequence(wo... | the_stack_v2_python_sparse | number_of_matching_subsequences_792.py | danielsunzhongyuan/my_leetcode_in_python | train | 0 | |
65210560a0a1e25f94576bc2336c13b7e5bee31a | [
"self.parent = parent\nself.power = power\nself.isPhysical = isPhysical\nself.pierce = pierce",
"damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)\nif target.dodge == self.pierce:\n return 2 * damage\nelse:\n return damage"
] | <|body_start_0|>
self.parent = parent
self.power = power
self.isPhysical = isPhysical
self.pierce = pierce
<|end_body_0|>
<|body_start_1|>
damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)
if target.dodge == self.pierce:
return 2 * damage
... | Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner | PierceDodge2XDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_36k_train_019344 | 842 | no_license | [
{
"docstring": "Build the Damage Delegate with the dodge it pierces",
"name": "__init__",
"signature": "def __init__(self, parent, power, isPhysical, pierce)"
},
{
"docstring": "Doubles the damage when the opponent is dodging in the manner that is pierced",
"name": "coreDamage",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_002093 | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
self.parent = parent
self.power = po... | the_stack_v2_python_sparse | src/Battle/Attack/DamageDelegates/piercedodge_2Xdelegate.py | sgtnourry/Pokemon-Project | train | 0 |
46b21183496bd8992f6f7a2298eee49189ccd0c1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | PredictServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictServicer:
def Infer(self, request, context):
"""Inference"""
<|body_0|>
def StreamInfer(self, request_iterator, context):
"""Stream Interface"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | stack_v2_sparse_classes_36k_train_019345 | 2,486 | permissive | [
{
"docstring": "Inference",
"name": "Infer",
"signature": "def Infer(self, request, context)"
},
{
"docstring": "Stream Interface",
"name": "StreamInfer",
"signature": "def StreamInfer(self, request_iterator, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016275 | Implement the Python class `PredictServicer` described below.
Class description:
Implement the PredictServicer class.
Method signatures and docstrings:
- def Infer(self, request, context): Inference
- def StreamInfer(self, request_iterator, context): Stream Interface | Implement the Python class `PredictServicer` described below.
Class description:
Implement the PredictServicer class.
Method signatures and docstrings:
- def Infer(self, request, context): Inference
- def StreamInfer(self, request_iterator, context): Stream Interface
<|skeleton|>
class PredictServicer:
def Infe... | f77635e469477b640a5c2d9b7ad3fe13374ce59e | <|skeleton|>
class PredictServicer:
def Infer(self, request, context):
"""Inference"""
<|body_0|>
def StreamInfer(self, request_iterator, context):
"""Stream Interface"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictServicer:
def Infer(self, request, context):
"""Inference"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def StreamInfer(self, request_iterator, context):
... | the_stack_v2_python_sparse | modelci/types/proto/service_pb2_grpc.py | crazyCoderLi/ML-Model-CI | train | 2 | |
0117fb1d5c4b36387cd8969c751330e3ba00da98 | [
"self.min_sum = float('inf')\nself.subtree = TreeNode(None)\nself.helper(root)\nreturn self.subtree",
"if root is None:\n return 0\nsum = self.helper(root.left) + self.helper(root.right) + root.val\nif sum < self.min_sum:\n self.min_sum = sum\n self.subtree = root\nreturn sum"
] | <|body_start_0|>
self.min_sum = float('inf')
self.subtree = TreeNode(None)
self.helper(root)
return self.subtree
<|end_body_0|>
<|body_start_1|>
if root is None:
return 0
sum = self.helper(root.left) + self.helper(root.right) + root.val
if sum < self.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
<|b... | stack_v2_sparse_classes_36k_train_019346 | 1,786 | no_license | [
{
"docstring": "recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode",
"name": "minSubtree",
"signature": "def minSubtree(se... | 2 | stack_v2_sparse_classes_30k_test_000046 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubtree(self, root): recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum fo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubtree(self, root): recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum fo... | e1a4c1bc5d01b4e2ba51a5255deed6426557dcb0 | <|skeleton|>
class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubtree(self, root):
"""recursion-divide conquer (with return) + traversal (global var) 1. sum = left + right + root.val 2. so helper should have return: sum 3. we get sum for each node --> ring game 打擂台 + global var :param root: TreeNode :return: TreeNode"""
self.min_sum = fl... | the_stack_v2_python_sparse | src/minSumOfSubtree.py | xuetingandyang/leetcode | train | 3 | |
90ff7bcebf1be92d549f3460c922799cf32e0e12 | [
"self.reader = paddle.to_tensor(reader)\nself.model = model\nself.optimizer = optimizer\nself.debug = False\nself.result = []",
"for i in range(10):\n out = self.model(self.reader)\n loss = paddle.mean(out)\n loss.backward()\n self.optimizer.step()\n self.optimizer.clear_grad()\n if self.debug:\... | <|body_start_0|>
self.reader = paddle.to_tensor(reader)
self.model = model
self.optimizer = optimizer
self.debug = False
self.result = []
<|end_body_0|>
<|body_start_1|>
for i in range(10):
out = self.model(self.reader)
loss = paddle.mean(out)
... | Runner | Runner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Runner:
"""Runner"""
def __init__(self, reader, model, optimizer):
"""init"""
<|body_0|>
def run(self):
"""run your models"""
<|body_1|>
def check(self, expect=None, rtol=1e-05, atol=1e-08):
"""check result"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_019347 | 1,500 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, reader, model, optimizer)"
},
{
"docstring": "run your models",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "check result",
"name": "check",
"signature": "def check(self, expect=... | 3 | null | Implement the Python class `Runner` described below.
Class description:
Runner
Method signatures and docstrings:
- def __init__(self, reader, model, optimizer): init
- def run(self): run your models
- def check(self, expect=None, rtol=1e-05, atol=1e-08): check result | Implement the Python class `Runner` described below.
Class description:
Runner
Method signatures and docstrings:
- def __init__(self, reader, model, optimizer): init
- def run(self): run your models
- def check(self, expect=None, rtol=1e-05, atol=1e-08): check result
<|skeleton|>
class Runner:
"""Runner"""
... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Runner:
"""Runner"""
def __init__(self, reader, model, optimizer):
"""init"""
<|body_0|>
def run(self):
"""run your models"""
<|body_1|>
def check(self, expect=None, rtol=1e-05, atol=1e-08):
"""check result"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Runner:
"""Runner"""
def __init__(self, reader, model, optimizer):
"""init"""
self.reader = paddle.to_tensor(reader)
self.model = model
self.optimizer = optimizer
self.debug = False
self.result = []
def run(self):
"""run your models"""
... | the_stack_v2_python_sparse | framework/api/optimizer/runner.py | PaddlePaddle/PaddleTest | train | 42 |
abd5c1a29f7f6d7625c832f7e1b9434b41a5d1dd | [
"self.aliyunrequest.set_action_name('DescribeInstances')\nif not isinstance(config, list):\n return self.MResponse(code=20001, msg='config配置不正确', status=False)\nself.Mconfig(config)\nresponse = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)\nreturn response",
"self.aliyunrequest.set_action_n... | <|body_start_0|>
self.aliyunrequest.set_action_name('DescribeInstances')
if not isinstance(config, list):
return self.MResponse(code=20001, msg='config配置不正确', status=False)
self.Mconfig(config)
response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
... | 查询阿里云redis信息 | ALiYunApiRedis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ALiYunApiRedis:
"""查询阿里云redis信息"""
def DescribeInstances(self, config):
"""调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
<|body_0|>
def DescribeInstanceAttribute(self, config):
"""调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_019348 | 7,651 | no_license | [
{
"docstring": "调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:",
"name": "DescribeInstances",
"signature": "def DescribeInstances(self, config)"
},
{
"docstring": "调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:",
"name": "DescribeInstanceAttribute",
"signature": "def DescribeInst... | 2 | stack_v2_sparse_classes_30k_val_000443 | Implement the Python class `ALiYunApiRedis` described below.
Class description:
查询阿里云redis信息
Method signatures and docstrings:
- def DescribeInstances(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:
- def DescribeInstanceAttribute(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return: | Implement the Python class `ALiYunApiRedis` described below.
Class description:
查询阿里云redis信息
Method signatures and docstrings:
- def DescribeInstances(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:
- def DescribeInstanceAttribute(self, config): 调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:
<|... | 401ad869298d55a6cb2f78442385f67f40b9db52 | <|skeleton|>
class ALiYunApiRedis:
"""查询阿里云redis信息"""
def DescribeInstances(self, config):
"""调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
<|body_0|>
def DescribeInstanceAttribute(self, config):
"""调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ALiYunApiRedis:
"""查询阿里云redis信息"""
def DescribeInstances(self, config):
"""调用该API可以查询账户下的某一个或多个实例信息。。 :param config: :return:"""
self.aliyunrequest.set_action_name('DescribeInstances')
if not isinstance(config, list):
return self.MResponse(code=20001, msg='config配置不正确'... | the_stack_v2_python_sparse | utils/maliyun/aliyunapi.py | Alotofwater/cookcmdb | train | 8 |
a14257a8d065c8e525e0b3d5907f0f19e03366d2 | [
"super(Net, self).__init__()\nself.num_channels = params.num_channels\nself.conv1 = nn.Conv2d(3, self.num_channels, 3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(self.num_channels)\nself.conv2 = nn.Conv2d(self.num_channels, self.num_channels * 2, 3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(self.num_chan... | <|body_start_0|>
super(Net, self).__init__()
self.num_channels = params.num_channels
self.conv1 = nn.Conv2d(3, self.num_channels, 3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(self.num_channels)
self.conv2 = nn.Conv2d(self.num_channels, self.num_channels * 2, 3, stride=1, pad... | This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to apply functions such as F.relu,... | Net | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net:
"""This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to ... | stack_v2_sparse_classes_36k_train_019349 | 22,038 | no_license | [
{
"docstring": "We define an convolutional network that predicts the sign from an image. The components required are: Args: params: (Params) contains num_channels",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "This function defines how we use the components of... | 2 | null | Implement the Python class `Net` described below.
Class description:
This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward functi... | Implement the Python class `Net` described below.
Class description:
This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward functi... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Net:
"""This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Net:
"""This is the standard way to define your own network in PyTorch. You typically choose the components (e.g. LSTMs, linear layers etc.) of your network in the __init__ function. You then apply these layers on the input step-by-step in the forward function. You can use torch.nn.functional to apply functio... | the_stack_v2_python_sparse | generated/test_haitongli_knowledge_distillation_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
02d03abf6a56974be9a35706e8e85f85ac632ec8 | [
"super().__init__()\nself.position_encoding = PositionalEncoding(e_dim)\nself.encoder_layers = nn.ModuleList([EncoderLayer(e_dim, h_dim, n_heads, drop_rate) for _ in range(n_layers)])",
"seq_inputs = self.position_encoding(seq_inputs)\nfor layer in self.encoder_layers:\n seq_inputs = layer(seq_inputs)\nreturn ... | <|body_start_0|>
super().__init__()
self.position_encoding = PositionalEncoding(e_dim)
self.encoder_layers = nn.ModuleList([EncoderLayer(e_dim, h_dim, n_heads, drop_rate) for _ in range(n_layers)])
<|end_body_0|>
<|body_start_1|>
seq_inputs = self.position_encoding(seq_inputs)
f... | TransformerEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1):
""":param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例"""
<|body_0|>
def forward(self, seq_inputs):
"... | stack_v2_sparse_classes_36k_train_019350 | 5,825 | no_license | [
{
"docstring": ":param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例",
"name": "__init__",
"signature": "def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1)"
},
{
"docstring": ":param seq_inputs: 已经经过Embe... | 2 | null | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): :param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layer... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1): :param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layer... | 302e14a3f7e5d72ded73b72a538596b6dc1233ff | <|skeleton|>
class TransformerEncoder:
def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1):
""":param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例"""
<|body_0|>
def forward(self, seq_inputs):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoder:
def __init__(self, e_dim, h_dim, n_heads, n_layers, drop_rate=0.1):
""":param e_dim: 输入向量的维度 :param h_dim: 注意力层中间隐含层的维度 :param n_heads: 多头注意力的头目数量 :param n_layers: 编码层的数量 :param drop_rate: drop out的比例"""
super().__init__()
self.position_encoding = PositionalEncoding... | the_stack_v2_python_sparse | deepModel/s47_transformerOnlyEncoder.py | HuichuanLI/Recommand-Algorithme | train | 71 | |
11eb1db94086cfe2581eb2aee651972c7403cc56 | [
"ret = 0\nwhile n != 1:\n ret += 1\n if n & 1 == 0:\n n >>= 1\n elif n == 3 or n >> 1 & 1 == 0:\n n -= 1\n else:\n n += 1\nreturn ret",
"if n == 1:\n return 0\nret = 1\nif n % 2 == 0:\n ret += self.integerReplacement(n / 2)\nelse:\n ret += min(self.integerReplacement(n + ... | <|body_start_0|>
ret = 0
while n != 1:
ret += 1
if n & 1 == 0:
n >>= 1
elif n == 3 or n >> 1 & 1 == 0:
n -= 1
else:
n += 1
return ret
<|end_body_0|>
<|body_start_1|>
if n == 1:
re... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
<|b... | stack_v2_sparse_classes_36k_train_019351 | 1,391 | permissive | [
{
"docstring": "Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int",
"name": "integerReplacement",
"signature": "def integerRep... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n): Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement(self, n): Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def integerReplacement(self, n):
"""Simulation using dp fails since bi-directional Simple recursion Math solution: bit manipulation https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/ 3 is a special case :type n: int :rtype: int"""
ret = 0
w... | the_stack_v2_python_sparse | 397 Integer Replacement.py | Aminaba123/LeetCode | train | 1 | |
fc1b4d58600a9430cdde07a7721fad4500b70b80 | [
"renderer = self.renderer\nwith open(makefile, mode='w') as stream:\n contents = self._generate(**kwds)\n document = renderer.render(document=contents)\n print('\\n'.join(document), file=stream)\nreturn",
"stamp = f\"generated by '{self.pyre_name}' on {datetime.datetime.now().isoformat()}\"\nyield self.r... | <|body_start_0|>
renderer = self.renderer
with open(makefile, mode='w') as stream:
contents = self._generate(**kwds)
document = renderer.render(document=contents)
print('\n'.join(document), file=stream)
return
<|end_body_0|>
<|body_start_1|>
stamp = f... | The base makefile content generator | Generator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
<|body_0|>
def _generate(self, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
renderer... | stack_v2_sparse_classes_36k_train_019352 | 1,415 | permissive | [
{
"docstring": "Generate the makefile preamble",
"name": "generate",
"signature": "def generate(self, makefile, **kwds)"
},
{
"docstring": "Build my contents",
"name": "_generate",
"signature": "def _generate(self, **kwds)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010617 | Implement the Python class `Generator` described below.
Class description:
The base makefile content generator
Method signatures and docstrings:
- def generate(self, makefile, **kwds): Generate the makefile preamble
- def _generate(self, **kwds): Build my contents | Implement the Python class `Generator` described below.
Class description:
The base makefile content generator
Method signatures and docstrings:
- def generate(self, makefile, **kwds): Generate the makefile preamble
- def _generate(self, **kwds): Build my contents
<|skeleton|>
class Generator:
"""The base makefi... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
<|body_0|>
def _generate(self, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
renderer = self.renderer
with open(makefile, mode='w') as stream:
contents = self._generate(**kwds)
document = renderer.render(do... | the_stack_v2_python_sparse | packages/merlin/builders/make/Generator.py | pyre/pyre | train | 27 |
22801a789db6c543f97a0eba0d17f7cc8f0a6a3d | [
"self._release_name = release_name\nprefix_lambda = lambda x: os.path.join(self.RULES_DIR, x) if not self.RULES_DIR in x else x\nself._rules = list(map(prefix_lambda, rules))",
"try:\n packages = PackagerUtil.make_packages(self._rules)\nexcept PackagerUtilError:\n raise Error('one or more of the packages co... | <|body_start_0|>
self._release_name = release_name
prefix_lambda = lambda x: os.path.join(self.RULES_DIR, x) if not self.RULES_DIR in x else x
self._rules = list(map(prefix_lambda, rules))
<|end_body_0|>
<|body_start_1|>
try:
packages = PackagerUtil.make_packages(self._rules... | UpdatePackages | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdatePackages:
def __init__(self, release_name, rules):
"""Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the RULES_DIR directory is not specified as part of the path. prefix the path e.g. for client, the package... | stack_v2_sparse_classes_36k_train_019353 | 4,028 | permissive | [
{
"docstring": "Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the RULES_DIR directory is not specified as part of the path. prefix the path e.g. for client, the package becomes os.path.join(RULES_DIR, 'client')",
"name": "__init__",... | 2 | null | Implement the Python class `UpdatePackages` described below.
Class description:
Implement the UpdatePackages class.
Method signatures and docstrings:
- def __init__(self, release_name, rules): Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the... | Implement the Python class `UpdatePackages` described below.
Class description:
Implement the UpdatePackages class.
Method signatures and docstrings:
- def __init__(self, release_name, rules): Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the... | 70280110ec342a6f6db1c102e96756fcc3c3c01b | <|skeleton|>
class UpdatePackages:
def __init__(self, release_name, rules):
"""Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the RULES_DIR directory is not specified as part of the path. prefix the path e.g. for client, the package... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdatePackages:
def __init__(self, release_name, rules):
"""Args: release_name (string) - string name of release in the releases.yaml rules (list) - the list of rules to build OR if the RULES_DIR directory is not specified as part of the path. prefix the path e.g. for client, the package becomes os.pa... | the_stack_v2_python_sparse | pylib/mps/update_packages.py | room77/py77 | train | 0 | |
fb3cca9c5c363da60d21daf4468ad97f77987884 | [
"super().__init__(restaurant_name, cuisine_type)\nself.flavors = ['바닐라', '딸기', '메론', '체리', '바나나', '쿠키', '커피']\nself.flavors.sort()",
"print('\\n아이스크림 맛 리스트: ')\nfor flavor in self.flavors:\n print(' - ' + flavor)"
] | <|body_start_0|>
super().__init__(restaurant_name, cuisine_type)
self.flavors = ['바닐라', '딸기', '메론', '체리', '바나나', '쿠키', '커피']
self.flavors.sort()
<|end_body_0|>
<|body_start_1|>
print('\n아이스크림 맛 리스트: ')
for flavor in self.flavors:
print(' - ' + flavor)
<|end_body_1|>
| 아이스크림 가판대 | IceCreamStand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IceCreamStand:
"""아이스크림 가판대"""
def __init__(self, restaurant_name, cuisine_type):
"""부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다."""
<|body_0|>
def show_flavors(self):
"""아이스크림 맛 리스트를 출력합니다."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
supe... | stack_v2_sparse_classes_36k_train_019354 | 1,990 | no_license | [
{
"docstring": "부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다.",
"name": "__init__",
"signature": "def __init__(self, restaurant_name, cuisine_type)"
},
{
"docstring": "아이스크림 맛 리스트를 출력합니다.",
"name": "show_flavors",
"signature": "def show_flavors(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001131 | Implement the Python class `IceCreamStand` described below.
Class description:
아이스크림 가판대
Method signatures and docstrings:
- def __init__(self, restaurant_name, cuisine_type): 부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다.
- def show_flavors(self): 아이스크림 맛 리스트를 출력합니다. | Implement the Python class `IceCreamStand` described below.
Class description:
아이스크림 가판대
Method signatures and docstrings:
- def __init__(self, restaurant_name, cuisine_type): 부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다.
- def show_flavors(self): 아이스크림 맛 리스트를 출력합니다.
<|skeleton|>
class IceCreamStand:
"""아이스크림 가... | ab850187581f9a415066d7b75175a92023c0a691 | <|skeleton|>
class IceCreamStand:
"""아이스크림 가판대"""
def __init__(self, restaurant_name, cuisine_type):
"""부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다."""
<|body_0|>
def show_flavors(self):
"""아이스크림 맛 리스트를 출력합니다."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IceCreamStand:
"""아이스크림 가판대"""
def __init__(self, restaurant_name, cuisine_type):
"""부모 클래스의 속성을 초기화하고 아이스크림 맛 리스트를 저장하는 속성을 추가합니다."""
super().__init__(restaurant_name, cuisine_type)
self.flavors = ['바닐라', '딸기', '메론', '체리', '바나나', '쿠키', '커피']
self.flavors.sort()
def s... | the_stack_v2_python_sparse | 9_class/exercises/9-6.py | lmw8864/MyFirstPython_part1_python_basic | train | 0 |
19e90e35aef479ad2a2aebd89bc7f944c01746f3 | [
"while run_flag.running:\n while not queue.empty():\n data = queue.get()\n for subject in [s for s in subjects if not s.is_disposed]:\n subject.on_next(data)\n time.sleep(0.1)",
"self._run_flag = RunFlag()\nself._subjects: List[Subject] = []\nm = Manager()\nq = m.Queue()\nself._shar... | <|body_start_0|>
while run_flag.running:
while not queue.empty():
data = queue.get()
for subject in [s for s in subjects if not s.is_disposed]:
subject.on_next(data)
time.sleep(0.1)
<|end_body_0|>
<|body_start_1|>
self._run_fla... | Reactive wrapper and background process for RuuviTagSensor get_data | RuuviTagReactive | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_019355 | 3,494 | permissive | [
{
"docstring": "Get data from background process and notify all subscribed observers with the new data",
"name": "_data_update",
"signature": "def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag)"
},
{
"docstring": "Start background process for get_data and async task for n... | 4 | stack_v2_sparse_classes_30k_train_020917 | Implement the Python class `RuuviTagReactive` described below.
Class description:
Reactive wrapper and background process for RuuviTagSensor get_data
Method signatures and docstrings:
- def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag): Get data from background process and notify all subscrib... | Implement the Python class `RuuviTagReactive` described below.
Class description:
Reactive wrapper and background process for RuuviTagSensor get_data
Method signatures and docstrings:
- def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag): Get data from background process and notify all subscrib... | f8458d10f37c080c335366f2b893accaf8a2221a | <|skeleton|>
class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuuviTagReactive:
"""Reactive wrapper and background process for RuuviTagSensor get_data"""
def _data_update(subjects: List[Subject], queue: Queue, run_flag: RunFlag):
"""Get data from background process and notify all subscribed observers with the new data"""
while run_flag.running:
... | the_stack_v2_python_sparse | ruuvitag_sensor/ruuvi_rx.py | ttu/ruuvitag-sensor | train | 190 |
5f29ae4fd20888096f5ce44c3f23ce932afc78b2 | [
"self.frame = frame\nself.parent = parent\nself.ctv = lambda: self.calcTimeValues()\nself.frame.rangeStart_spinBox.valueChanged.connect(self.ctv)\nself.frame.rangeEnd_spinBox.valueChanged.connect(self.ctv)\nself.calcTimeValues()",
"rangeStart = self.frame.rangeStart_spinBox.value()\nrangeEnd = self.frame.rangeEnd... | <|body_start_0|>
self.frame = frame
self.parent = parent
self.ctv = lambda: self.calcTimeValues()
self.frame.rangeStart_spinBox.valueChanged.connect(self.ctv)
self.frame.rangeEnd_spinBox.valueChanged.connect(self.ctv)
self.calcTimeValues()
<|end_body_0|>
<|body_start_1|>... | helper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class helper:
def __init__(self, parent, frame):
"""Setup time properties panel."""
<|body_0|>
def calcTimeValues(self):
"""Calculate time values (frame range, duration, in/out, etc.)"""
<|body_1|>
def calcDuration(self, rangeStart, rangeEnd):
"""Calcu... | stack_v2_sparse_classes_36k_train_019356 | 2,937 | permissive | [
{
"docstring": "Setup time properties panel.",
"name": "__init__",
"signature": "def __init__(self, parent, frame)"
},
{
"docstring": "Calculate time values (frame range, duration, in/out, etc.)",
"name": "calcTimeValues",
"signature": "def calcTimeValues(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_val_000263 | Implement the Python class `helper` described below.
Class description:
Implement the helper class.
Method signatures and docstrings:
- def __init__(self, parent, frame): Setup time properties panel.
- def calcTimeValues(self): Calculate time values (frame range, duration, in/out, etc.)
- def calcDuration(self, range... | Implement the Python class `helper` described below.
Class description:
Implement the helper class.
Method signatures and docstrings:
- def __init__(self, parent, frame): Setup time properties panel.
- def calcTimeValues(self): Calculate time values (frame range, duration, in/out, etc.)
- def calcDuration(self, range... | a05abc916f0b6a9ee2c00e9f9b3dec12c09e6abe | <|skeleton|>
class helper:
def __init__(self, parent, frame):
"""Setup time properties panel."""
<|body_0|>
def calcTimeValues(self):
"""Calculate time values (frame range, duration, in/out, etc.)"""
<|body_1|>
def calcDuration(self, rangeStart, rangeEnd):
"""Calcu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class helper:
def __init__(self, parent, frame):
"""Setup time properties panel."""
self.frame = frame
self.parent = parent
self.ctv = lambda: self.calcTimeValues()
self.frame.rangeStart_spinBox.valueChanged.connect(self.ctv)
self.frame.rangeEnd_spinBox.valueChanged.c... | the_stack_v2_python_sparse | tools/settings/settings_time.py | mjbonnington/icarus-gps | train | 0 | |
3fd17ac2423c6b404a7a8e09ddd3dc2c699c6d23 | [
"if self.action in ('list', 'retrieve'):\n result = self.get_access_permissions().check_permissions(self.request.user)\nelif self.action == 'metadata':\n result = self.request.user.is_authenticated or anonymous_is_enabled()\nelif self.action in ('create', 'partial_update', 'update', 'destroy'):\n result = ... | <|body_start_0|>
if self.action in ('list', 'retrieve'):
result = self.get_access_permissions().check_permissions(self.request.user)
elif self.action == 'metadata':
result = self.request.user.is_authenticated or anonymous_is_enabled()
elif self.action in ('create', 'parti... | API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy. | GroupViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupViewSet:
"""API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy."""
def check_view_permissions(self):
"""Returns True if the user has required permissions."""
<|body_0|>
def update(self, reques... | stack_v2_sparse_classes_36k_train_019357 | 28,020 | permissive | [
{
"docstring": "Returns True if the user has required permissions.",
"name": "check_view_permissions",
"signature": "def check_view_permissions(self)"
},
{
"docstring": "Customized endpoint to update a group. Send the signal 'permission_change' if group permissions change.",
"name": "update"... | 3 | stack_v2_sparse_classes_30k_val_000724 | Implement the Python class `GroupViewSet` described below.
Class description:
API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy.
Method signatures and docstrings:
- def check_view_permissions(self): Returns True if the user has required permis... | Implement the Python class `GroupViewSet` described below.
Class description:
API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy.
Method signatures and docstrings:
- def check_view_permissions(self): Returns True if the user has required permis... | dfab9730dcd39b556ec46cc27186a47e75ad014e | <|skeleton|>
class GroupViewSet:
"""API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy."""
def check_view_permissions(self):
"""Returns True if the user has required permissions."""
<|body_0|>
def update(self, reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupViewSet:
"""API endpoint for groups. There are the following views: metadata, list, retrieve, create, partial_update, update and destroy."""
def check_view_permissions(self):
"""Returns True if the user has required permissions."""
if self.action in ('list', 'retrieve'):
... | the_stack_v2_python_sparse | openslides/users/views.py | emanuelschuetze/OpenSlides | train | 1 |
1f45d7634752d535e2fae7d0c26f04eedfae0b39 | [
"super(MeshPooling, self).__init__()\nself.cached = cached\nself.index = index\nself.face = face",
"if self.matrix is None or not self.cached:\n self.face, self.index = unsubdivide(x.pos, x.face)[1:]\nx.pos = x.pos[self.index]\nx.norm = x.norm[self.index]\nx.face = self.face\nif len(args) == 0:\n return x\n... | <|body_start_0|>
super(MeshPooling, self).__init__()
self.cached = cached
self.index = index
self.face = face
<|end_body_0|>
<|body_start_1|>
if self.matrix is None or not self.cached:
self.face, self.index = unsubdivide(x.pos, x.face)[1:]
x.pos = x.pos[self.... | A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- forward(x, *args) pools the ... | MeshPooling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeshPooling:
"""A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Metho... | stack_v2_sparse_classes_36k_train_019358 | 1,745 | permissive | [
{
"docstring": "Parameters ---------- index : LongTensor (optional) the vertices indices (default is None) face : LongTensor (optional) the topology tensor (default is None) cached : bool (optional) if True caches the pooling data, otherwise computes it at every input (default is True)",
"name": "__init__",... | 2 | stack_v2_sparse_classes_30k_train_010613 | Implement the Python class `MeshPooling` described below.
Class description:
A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face... | Implement the Python class `MeshPooling` described below.
Class description:
A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face... | 2615b66dd4addfd5c03d9d91a24c7da414294308 | <|skeleton|>
class MeshPooling:
"""A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeshPooling:
"""A class representing a mesh pooling layer. It supposes the input mesh is trivially poolable Attributes ---------- cached : bool if True caches the pooling data, otherwise computes it at every input index : LongTensor the vertices indices face : LongTensor the topology tensor Methods ------- fo... | the_stack_v2_python_sparse | ACME/layer/MeshPooling.py | mauriziokovacic/ACME | train | 3 |
1af9303bd6ab7ee605a9310914b9bc2a461b8a2d | [
"Parametre.__init__(self, 'charger', 'load')\nself.schema = '<nom_objet>'\nself.aide_courte = 'charge le canon'\nself.aide_longue = \"Cette commande permet de charger un canon avec le projectile spécifié en paramètre. Vous devez posséder sur vous (dans vos mains ou l'un des sacs que vous possédez) le projectile spé... | <|body_start_0|>
Parametre.__init__(self, 'charger', 'load')
self.schema = '<nom_objet>'
self.aide_courte = 'charge le canon'
self.aide_longue = "Cette commande permet de charger un canon avec le projectile spécifié en paramètre. Vous devez posséder sur vous (dans vos mains ou l'un des s... | Commande 'canon charger'. | PrmCharger | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmCharger:
"""Commande 'canon charger'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_masqu... | stack_v2_sparse_classes_36k_train_019359 | 3,847 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode appelée lors de l'ajout de la commande à l'interpréteur",
"name": "ajouter",
"signature": "def ajouter(self)"
},
{
"docstring": "Interprétation du paramètr... | 3 | null | Implement the Python class `PrmCharger` described below.
Class description:
Commande 'canon charger'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masques):... | Implement the Python class `PrmCharger` described below.
Class description:
Commande 'canon charger'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masques):... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmCharger:
"""Commande 'canon charger'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_masqu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmCharger:
"""Commande 'canon charger'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'charger', 'load')
self.schema = '<nom_objet>'
self.aide_courte = 'charge le canon'
self.aide_longue = "Cette commande permet de charger un cano... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/canon/charger.py | vincent-lg/tsunami | train | 5 |
08793fa7d6a00fc8468ad092b5e84b8a69dc36d6 | [
"cache_key = (model_year, drive_system)\nstart_years = WorkFactor.start_years[drive_system]\nif len([yr for yr in start_years if yr <= model_year]) > 0:\n model_year = max([yr for yr in start_years if yr <= model_year])\n xwd = WorkFactor._cache[model_year, drive_system]['xwd']\n workfactor = eval(WorkFact... | <|body_start_0|>
cache_key = (model_year, drive_system)
start_years = WorkFactor.start_years[drive_system]
if len([yr for yr in start_years if yr <= model_year]) > 0:
model_year = max([yr for yr in start_years if yr <= model_year])
xwd = WorkFactor._cache[model_year, driv... | **Work factor definition and calculations.** | WorkFactor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFactor:
"""**Work factor definition and calculations.**"""
def calc_workfactor(model_year, curbweight_lbs, gvwr_lbs, gcwr_lbs, drive_system):
"""Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbweight_lbs (float): vehicle curb weight in lbs gvwr_lbs (f... | stack_v2_sparse_classes_36k_train_019360 | 5,474 | no_license | [
{
"docstring": "Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbweight_lbs (float): vehicle curb weight in lbs gvwr_lbs (float): vehicle gross vehicle weight rating in lbs gcwr_lbs (float): vehicle combined weight rating in lbs drive_system (int): drive system, 2=two wheel drive, 4=... | 2 | stack_v2_sparse_classes_30k_train_000834 | Implement the Python class `WorkFactor` described below.
Class description:
**Work factor definition and calculations.**
Method signatures and docstrings:
- def calc_workfactor(model_year, curbweight_lbs, gvwr_lbs, gcwr_lbs, drive_system): Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbw... | Implement the Python class `WorkFactor` described below.
Class description:
**Work factor definition and calculations.**
Method signatures and docstrings:
- def calc_workfactor(model_year, curbweight_lbs, gvwr_lbs, gcwr_lbs, drive_system): Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbw... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class WorkFactor:
"""**Work factor definition and calculations.**"""
def calc_workfactor(model_year, curbweight_lbs, gvwr_lbs, gcwr_lbs, drive_system):
"""Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbweight_lbs (float): vehicle curb weight in lbs gvwr_lbs (f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkFactor:
"""**Work factor definition and calculations.**"""
def calc_workfactor(model_year, curbweight_lbs, gvwr_lbs, gcwr_lbs, drive_system):
"""Calculate vehicle workfactor. Args: model_year (int): vehicle model year curbweight_lbs (float): vehicle curb weight in lbs gvwr_lbs (float): vehicl... | the_stack_v2_python_sparse | omega_model/policy/workfactor_definition.py | USEPA/EPA_OMEGA_Model | train | 17 |
1f54d3ed8d62c3130efa8b7e3e229ca08480fc9b | [
"self.__dict__.update(other.__dict__)\nloader = other.loader\nself.loader = PluginSourceLoader(loader.name, loader.path)\nself._initializing_internal = False",
"loader = self.loader\nif loader is None:\n return False\nif not isinstance(loader, PluginSourceLoader):\n return False\nif loader._module is None:\... | <|body_start_0|>
self.__dict__.update(other.__dict__)
loader = other.loader
self.loader = PluginSourceLoader(loader.name, loader.path)
self._initializing_internal = False
<|end_body_0|>
<|body_start_1|>
loader = self.loader
if loader is None:
return False
... | Extends the builtin spec with plugin checking. | PluginModuleSpecType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginModuleSpecType:
"""Extends the builtin spec with plugin checking."""
def __init__(self, other):
"""`ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module spec to inherit from."""
<|body_0|>
def is_... | stack_v2_sparse_classes_36k_train_019361 | 1,965 | permissive | [
{
"docstring": "`ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module spec to inherit from.",
"name": "__init__",
"signature": "def __init__(self, other)"
},
{
"docstring": "Returns whether the module spec is initialised. Retur... | 4 | null | Implement the Python class `PluginModuleSpecType` described below.
Class description:
Extends the builtin spec with plugin checking.
Method signatures and docstrings:
- def __init__(self, other): `ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module... | Implement the Python class `PluginModuleSpecType` described below.
Class description:
Extends the builtin spec with plugin checking.
Method signatures and docstrings:
- def __init__(self, other): `ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class PluginModuleSpecType:
"""Extends the builtin spec with plugin checking."""
def __init__(self, other):
"""`ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module spec to inherit from."""
<|body_0|>
def is_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PluginModuleSpecType:
"""Extends the builtin spec with plugin checking."""
def __init__(self, other):
"""`ModuleSpec` subclass implementing rich context for plugins. Parameters ---------- other : ``ModuleSpec`` The other module spec to inherit from."""
self.__dict__.update(other.__dict__)... | the_stack_v2_python_sparse | hata/ext/plugin_loader/import_overwrite/module_spec_type.py | HuyaneMatsu/hata | train | 3 |
019bbe8993330f24e7ef58c357f23706227dbe38 | [
"from supriya.tools import ugentools\nugen = abs(ugentools.HPZ1.ar(source=source)) > threshold\nreturn ugen",
"from supriya.tools import ugentools\nugen = abs(ugentools.HPZ1.kr(source=source)) > threshold\nreturn ugen"
] | <|body_start_0|>
from supriya.tools import ugentools
ugen = abs(ugentools.HPZ1.ar(source=source)) > threshold
return ugen
<|end_body_0|>
<|body_start_1|>
from supriya.tools import ugentools
ugen = abs(ugentools.HPZ1.kr(source=source)) > threshold
return ugen
<|end_body_1... | Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_In[0] -> 1_HPZ1[0:source] 1_HPZ1[0] -> 2_UnaryOpUGen:ABSOLUTE_VALUE[0:sourc... | Changed | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Changed:
"""Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_In[0] -> 1_HPZ1[0:source] 1_HPZ1[0] -> 2... | stack_v2_sparse_classes_36k_train_019362 | 2,724 | permissive | [
{
"docstring": "Constructs an audio-rate Changed. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_In[0] -> 1_HPZ1[0:source] 1_HPZ1[0] -> 2_UnaryOp... | 2 | stack_v2_sparse_classes_30k_train_021037 | Implement the Python class `Changed` described below.
Class description:
Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_I... | Implement the Python class `Changed` described below.
Class description:
Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_I... | 30f79a26e5c5f92514d09d7d31f62452caa2634a | <|skeleton|>
class Changed:
"""Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_In[0] -> 1_HPZ1[0:source] 1_HPZ1[0] -> 2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Changed:
"""Triggers when a value changes. :: >>> source = ugentools.In.ar(bus=0) >>> changed = ugentools.Changed.ar( ... source=source, ... threshold=0, ... ) >>> print(str(changed)) SynthDef 39e1f9d61589c4acaaf297cc961d65e4 { const_0:0.0 -> 0_In[0:bus] 0_In[0] -> 1_HPZ1[0:source] 1_HPZ1[0] -> 2_UnaryOpUGen:... | the_stack_v2_python_sparse | supriya/tools/ugentools/Changed.py | andrewyoung1991/supriya | train | 2 |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\nreturn cls(name, classID)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
return cls(name, classID)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.classID)
return written
<|end_body_1|>
| Class structure. .. py:attribute:: name .. py:attribute:: classID | Class | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Class:
"""Class structure. .. py:attribute:: name .. py:attribute:: classID"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: fi... | stack_v2_sparse_classes_36k_train_019363 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010330 | Implement the Python class `Class` described below.
Class description:
Class structure. .. py:attribute:: name .. py:attribute:: classID
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like ... | Implement the Python class `Class` described below.
Class description:
Class structure. .. py:attribute:: name .. py:attribute:: classID
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like ... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Class:
"""Class structure. .. py:attribute:: name .. py:attribute:: classID"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Class:
"""Class structure. .. py:attribute:: name .. py:attribute:: classID"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
return cls(name, classID)
def... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
119936d66be3ec60a1021821b97d508930512212 | [
"super(PyTorchModel, self).__init__()\nself.linear1 = nn.Linear(D_in, H)\nself.linear2 = nn.Linear(H, D_out)",
"h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred"
] | <|body_start_0|>
super(PyTorchModel, self).__init__()
self.linear1 = nn.Linear(D_in, H)
self.linear2 = nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
<|end_body_1|>
| PyTorchModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyTorchModel:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_019364 | 11,357 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data",
"name": "forward",
"signature... | 2 | null | Implement the Python class `PyTorchModel` described below.
Class description:
Implement the PyTorchModel class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward fu... | Implement the Python class `PyTorchModel` described below.
Class description:
Implement the PyTorchModel class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward fu... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class PyTorchModel:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyTorchModel:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(PyTorchModel, self).__init__()
self.linear1 = nn.Linear(D_in, H)
self.linear2 = nn.Linear(H, D_out)
def forward(self, ... | the_stack_v2_python_sparse | generated/test_bentoml_BentoML.py | jansel/pytorch-jit-paritybench | train | 35 | |
8de80bdece1c7bb9f6ec075e9c21c64bb33d7e7e | [
"valSet = self.data.get(key)\nif valSet is None:\n self.data[key] = set([val])\nelse:\n valSet.add(val)",
"valSet = self.data.get(key)\nif valSet is None:\n self.data[key] = set(valList)\nelse:\n valSet.update(valList)"
] | <|body_start_0|>
valSet = self.data.get(key)
if valSet is None:
self.data[key] = set([val])
else:
valSet.add(val)
<|end_body_0|>
<|body_start_1|>
valSet = self.data.get(key)
if valSet is None:
self.data[key] = set(valList)
else:
... | A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added. | SetDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetDict:
"""A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added."""
def __setitem__(self, key, val):
"""Add a value to the set of values for a given key, creating a new entry if necessary. Duplicate values are silently ... | stack_v2_sparse_classes_36k_train_019365 | 3,694 | no_license | [
{
"docstring": "Add a value to the set of values for a given key, creating a new entry if necessary. Duplicate values are silently ignored. Supports the notation: aListDict[key] = val",
"name": "__setitem__",
"signature": "def __setitem__(self, key, val)"
},
{
"docstring": "Add values to the set... | 2 | null | Implement the Python class `SetDict` described below.
Class description:
A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added.
Method signatures and docstrings:
- def __setitem__(self, key, val): Add a value to the set of values for a given key, creating... | Implement the Python class `SetDict` described below.
Class description:
A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added.
Method signatures and docstrings:
- def __setitem__(self, key, val): Add a value to the set of values for a given key, creating... | fe5578ba978e8a9cd81c08be271c2ef874a84927 | <|skeleton|>
class SetDict:
"""A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added."""
def __setitem__(self, key, val):
"""Add a value to the set of values for a given key, creating a new entry if necessary. Duplicate values are silently ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetDict:
"""A dictionary whose values are a set of items, meaning a list of unique items. Duplicate items are silently not added."""
def __setitem__(self, key, val):
"""Add a value to the set of values for a given key, creating a new entry if necessary. Duplicate values are silently ignored. Supp... | the_stack_v2_python_sparse | python/RO-3.6.9/Alg/MultiDict.py | Subaru-PFS/tron_actorcore | train | 3 |
cc782523c3ca17d4cf5da732e5f49800aeab5ea3 | [
"try:\n employee_id = int(request.data.get('employee_id'))\n role = request.data.get('role')\n email = request.data.get('email')\n name = request.data.get('name')\n phone = request.data.get('phone')\n gender = request.data.get('gender').lower()\n password = request.data.get('password').strip()\... | <|body_start_0|>
try:
employee_id = int(request.data.get('employee_id'))
role = request.data.get('role')
email = request.data.get('email')
name = request.data.get('name')
phone = request.data.get('phone')
gender = request.data.get('gender')... | EmployeeAuthViewSets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeAuthViewSets:
def register(self, request):
"""User Register :param request, email, password, employee_id, name, phone, gender, team, role"""
<|body_0|>
def login(self, request):
"""Normal Login :param request, email, password"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_019366 | 21,490 | no_license | [
{
"docstring": "User Register :param request, email, password, employee_id, name, phone, gender, team, role",
"name": "register",
"signature": "def register(self, request)"
},
{
"docstring": "Normal Login :param request, email, password",
"name": "login",
"signature": "def login(self, re... | 2 | stack_v2_sparse_classes_30k_val_000991 | Implement the Python class `EmployeeAuthViewSets` described below.
Class description:
Implement the EmployeeAuthViewSets class.
Method signatures and docstrings:
- def register(self, request): User Register :param request, email, password, employee_id, name, phone, gender, team, role
- def login(self, request): Norma... | Implement the Python class `EmployeeAuthViewSets` described below.
Class description:
Implement the EmployeeAuthViewSets class.
Method signatures and docstrings:
- def register(self, request): User Register :param request, email, password, employee_id, name, phone, gender, team, role
- def login(self, request): Norma... | dbc42f4bf97be2ca2261ac5d54de822f25e830b7 | <|skeleton|>
class EmployeeAuthViewSets:
def register(self, request):
"""User Register :param request, email, password, employee_id, name, phone, gender, team, role"""
<|body_0|>
def login(self, request):
"""Normal Login :param request, email, password"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeAuthViewSets:
def register(self, request):
"""User Register :param request, email, password, employee_id, name, phone, gender, team, role"""
try:
employee_id = int(request.data.get('employee_id'))
role = request.data.get('role')
email = request.data.... | the_stack_v2_python_sparse | django/employee/views.py | devesh2108/Consultdd-Internship- | train | 0 | |
127b536d18395e0b543d55cd05265cf700cf6b83 | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, project_id=project_id, user_id=user_id, role_id=role_id))\nPROVIDERS.assignment_api.get_grant(project_id=project_id, user_id=user_id, role_id=role_id, inherited_to_projects=True)\nreturn (None, http_... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, project_id=project_id, user_id=user_id, role_id=role_id))
PROVIDERS.assignment_api.get_grant(project_id=project_id, user_id=user_id, role_id=role_id, inherited_to_projects... | OSInheritProjectUserResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSInheritProjectUserResource:
def get(self, project_id, user_id, role_id):
"""Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_id}/users/{user_id} /roles/{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, project_id, user_... | stack_v2_sparse_classes_36k_train_019367 | 19,022 | permissive | [
{
"docstring": "Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_id}/users/{user_id} /roles/{role_id}/inherited_to_projects",
"name": "get",
"signature": "def get(self, project_id, user_id, role_id)"
},
{
"docstring": "Create an inherited grant for a u... | 3 | stack_v2_sparse_classes_30k_train_018106 | Implement the Python class `OSInheritProjectUserResource` described below.
Class description:
Implement the OSInheritProjectUserResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_... | Implement the Python class `OSInheritProjectUserResource` described below.
Class description:
Implement the OSInheritProjectUserResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class OSInheritProjectUserResource:
def get(self, project_id, user_id, role_id):
"""Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_id}/users/{user_id} /roles/{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, project_id, user_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OSInheritProjectUserResource:
def get(self, project_id, user_id, role_id):
"""Check for an inherited grant for a user on a project. GET/HEAD /OS-INHERIT/projects/{project_id}/users/{user_id} /roles/{role_id}/inherited_to_projects"""
ENFORCER.enforce_call(action='identity:check_grant', build_ta... | the_stack_v2_python_sparse | keystone/api/os_inherit.py | sapcc/keystone | train | 0 | |
17d15c857e00a1805908ba740de6a4464bab3be4 | [
"count = 0\nprev_cum_sums = {0: 1}\ncum_sum = 0\nfor num in nums:\n cum_sum = (cum_sum + num % k + k) % k\n count += prev_cum_sums.get(cum_sum, 0)\n prev_cum_sums[cum_sum] = prev_cum_sums.get(cum_sum, 0) + 1\nreturn count",
"count = 0\nprev_cum_sums = [1] + [0] * (k - 1)\ncum_sum = 0\nfor num in nums:\n ... | <|body_start_0|>
count = 0
prev_cum_sums = {0: 1}
cum_sum = 0
for num in nums:
cum_sum = (cum_sum + num % k + k) % k
count += prev_cum_sums.get(cum_sum, 0)
prev_cum_sums[cum_sum] = prev_cum_sums.get(cum_sum, 0) + 1
return count
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative sum modulo K from the start - Additionally, at each step: - Store the cumulative sum modulo K in an... | stack_v2_sparse_classes_36k_train_019368 | 2,530 | no_license | [
{
"docstring": "Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative sum modulo K from the start - Additionally, at each step: - Store the cumulative sum modulo K in an hash-map - Look for the complement of the cumulative sum modulo K in the hash-m... | 3 | stack_v2_sparse_classes_30k_train_010699 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative su... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative su... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative sum modulo K from the start - Additionally, at each step: - Store the cumulative sum modulo K in an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Similar to sub-array sums equal to K, but with modulo. The principle: - Move through the array, keeping a cumulative sum modulo K from the start - Additionally, at each step: - Store the cumulative sum modulo K in an hash-map - Lo... | the_stack_v2_python_sparse | arrays/SubArraySumDivisibleByK.py | QuentinDuval/PythonExperiments | train | 3 | |
273d71f55d4ba7727a290572da3f0fce87b64512 | [
"try:\n approved_token = aff4.Approval.GetApprovalForObject(object_urn, token=token)\nexcept access_control.UnauthorizedAccess as e:\n self.error = e\n approved_token = None\nif approved_token:\n self.reason = approved_token.reason\n return True\nelse:\n return False",
"self.subject = request.RE... | <|body_start_0|>
try:
approved_token = aff4.Approval.GetApprovalForObject(object_urn, token=token)
except access_control.UnauthorizedAccess as e:
self.error = e
approved_token = None
if approved_token:
self.reason = approved_token.reason
... | Check the level of access the user has for a specified client. | CheckAccess | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckAccess:
"""Check the level of access the user has for a specified client."""
def CheckObjectAccess(self, object_urn, token):
"""Check if the user has access to the specified hunt."""
<|body_0|>
def Layout(self, request, response):
"""Checks the level of acce... | stack_v2_sparse_classes_36k_train_019369 | 16,884 | permissive | [
{
"docstring": "Check if the user has access to the specified hunt.",
"name": "CheckObjectAccess",
"signature": "def CheckObjectAccess(self, object_urn, token)"
},
{
"docstring": "Checks the level of access the user has to this client.",
"name": "Layout",
"signature": "def Layout(self, r... | 2 | null | Implement the Python class `CheckAccess` described below.
Class description:
Check the level of access the user has for a specified client.
Method signatures and docstrings:
- def CheckObjectAccess(self, object_urn, token): Check if the user has access to the specified hunt.
- def Layout(self, request, response): Che... | Implement the Python class `CheckAccess` described below.
Class description:
Check the level of access the user has for a specified client.
Method signatures and docstrings:
- def CheckObjectAccess(self, object_urn, token): Check if the user has access to the specified hunt.
- def Layout(self, request, response): Che... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class CheckAccess:
"""Check the level of access the user has for a specified client."""
def CheckObjectAccess(self, object_urn, token):
"""Check if the user has access to the specified hunt."""
<|body_0|>
def Layout(self, request, response):
"""Checks the level of acce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckAccess:
"""Check the level of access the user has for a specified client."""
def CheckObjectAccess(self, object_urn, token):
"""Check if the user has access to the specified hunt."""
try:
approved_token = aff4.Approval.GetApprovalForObject(object_urn, token=token)
... | the_stack_v2_python_sparse | gui/plugins/acl_manager.py | defaultnamehere/grr | train | 3 |
32cdc7d3d31e7fe0b6c21899917d01a057c4b87a | [
"with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()):\n with slim.arg_scope([slim.conv2d], padding='SAME') as arg_sc:\n return arg_sc",
"if rate == 1:\n outputs = slim.repe... | <|body_start_0|>
with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu, weights_regularizer=slim.l2_regularizer(weight_decay), biases_initializer=tf.zeros_initializer()):
with slim.arg_scope([slim.conv2d], padding='SAME') as arg_sc:
return arg_sc
<|end_bod... | Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features. | BevVggLfe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BevVggLfe:
"""Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features."""
def vgg_arg_scope(self, weight_decay=0.0005):
"""Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope."""
... | stack_v2_sparse_classes_36k_train_019370 | 6,290 | no_license | [
{
"docstring": "Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope.",
"name": "vgg_arg_scope",
"signature": "def vgg_arg_scope(self, weight_decay=0.0005)"
},
{
"docstring": "implimentation of dilated convolution by using batch_to_space https:/... | 3 | stack_v2_sparse_classes_30k_train_004060 | Implement the Python class `BevVggLfe` described below.
Class description:
Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features.
Method signatures and docstrings:
- def vgg_arg_scope(self, weight_decay=0.0005): Defines the VGG arg scope. Args: weight_decay: The ... | Implement the Python class `BevVggLfe` described below.
Class description:
Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features.
Method signatures and docstrings:
- def vgg_arg_scope(self, weight_decay=0.0005): Defines the VGG arg scope. Args: weight_decay: The ... | ac8256bd76fe4b81cfc48dc4c0b9d9dc92bc61c6 | <|skeleton|>
class BevVggLfe:
"""Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features."""
def vgg_arg_scope(self, weight_decay=0.0005):
"""Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BevVggLfe:
"""Contains modified VGG model definition to extract features from Bird's eye view input using pyramid features."""
def vgg_arg_scope(self, weight_decay=0.0005):
"""Defines the VGG arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope."""
with ... | the_stack_v2_python_sparse | mlod/core/feature_extractors/bev_vgg_lfe.py | songsanling/MLOD | train | 0 |
d4595a02e8c2621d5556424c67e54217d107e1da | [
"path: str = '../python_api/scenes'\nceiling_materials = set()\nfloor_materials = set()\nwall_materials = set()\nshape_set = set()\nmaterial_files = set()\nsalient_materials = set()\nfor dir_path, dir_names, file_names in walk(path):\n for file_name in file_names:\n if str(file_name).endswith('.json'):\n ... | <|body_start_0|>
path: str = '../python_api/scenes'
ceiling_materials = set()
floor_materials = set()
wall_materials = set()
shape_set = set()
material_files = set()
salient_materials = set()
for dir_path, dir_names, file_names in walk(path):
f... | Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation. | McsInspector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class McsInspector:
"""Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation."""
def find_objects(self):
"""Traverses th... | stack_v2_sparse_classes_36k_train_019371 | 9,641 | no_license | [
{
"docstring": "Traverses the scenes in `python_api/scenes` and returns a catalog of all the materials and objects that appear in them. Returns: A tuple containing: * The set of all ceiling materials that occur in any scene * The set of all floor materials that occur in any scene * The set of all wall materials... | 3 | null | Implement the Python class `McsInspector` described below.
Class description:
Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation.
Method signatur... | Implement the Python class `McsInspector` described below.
Class description:
Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation.
Method signatur... | 424cbf65fd65e912430cb99d942e2fa69235aa61 | <|skeleton|>
class McsInspector:
"""Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation."""
def find_objects(self):
"""Traverses th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class McsInspector:
"""Inspector used to extract materials and object types from provided scenegraphs. Needed since object types were not documented when we started experimenting. Also helped find undocumented options for wider dataset generation."""
def find_objects(self):
"""Traverses the scenes in `... | the_stack_v2_python_sparse | datasets/mcs_implant/ai2thor_inspector.py | AdejuwonF/intphys-renderer | train | 0 |
df93d798d49f9c953bc5a10a6a6e09c5b731f84a | [
"self.output_splits = output_splits\nself.n_out = sum([v[1] for v in output_splits])\noutput_keys = [v[0] for v in output_splits] + ['f0_hz']\nsuper().__init__(output_keys=output_keys, **kwargs)\nself.net = net\nself.f0_residual = f0_residual\nself.dense_out = tfkl.Dense(self.n_out)\nself.norm = nn.Normalize('layer... | <|body_start_0|>
self.output_splits = output_splits
self.n_out = sum([v[1] for v in output_splits])
output_keys = [v[0] for v in output_splits] + ['f0_hz']
super().__init__(output_keys=output_keys, **kwargs)
self.net = net
self.f0_residual = f0_residual
self.dense... | Decodes MIDI notes (& velocities) to f0, amps, hd, noise. | MidiToHarmonicDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidiToHarmonicDecoder:
"""Decodes MIDI notes (& velocities) to f0, amps, hd, noise."""
def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60), ('magnitudes', 65)), midi_zero_silence=True, **kwargs):
""... | stack_v2_sparse_classes_36k_train_019372 | 9,400 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60), ('magnitudes', 65)), midi_zero_silence=True, **kwargs)"
},
{
"docstring": "Forward pass for ... | 2 | null | Implement the Python class `MidiToHarmonicDecoder` described below.
Class description:
Decodes MIDI notes (& velocities) to f0, amps, hd, noise.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60)... | Implement the Python class `MidiToHarmonicDecoder` described below.
Class description:
Decodes MIDI notes (& velocities) to f0, amps, hd, noise.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60)... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class MidiToHarmonicDecoder:
"""Decodes MIDI notes (& velocities) to f0, amps, hd, noise."""
def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60), ('magnitudes', 65)), midi_zero_silence=True, **kwargs):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MidiToHarmonicDecoder:
"""Decodes MIDI notes (& velocities) to f0, amps, hd, noise."""
def __init__(self, net=None, f0_residual=True, norm=True, output_splits=(('f0_midi', 1), ('amplitudes', 1), ('harmonic_distribution', 60), ('magnitudes', 65)), midi_zero_silence=True, **kwargs):
"""Constructor.... | the_stack_v2_python_sparse | ddsp/training/decoders.py | magenta/ddsp | train | 2,666 |
68cc031343eb69e7a8c0cdd0d0336eb9ccdba79e | [
"super().__init__(var, *args, **kwargs)\nself._df['FLAG'] = np.int8(-128)\nself.descriptions[-128] = 'A fill value. No flagging information has been provided'\nself.descriptions[0] = 'Data are assumed to be valid and representative of the physical quantity measured'\nself.meanings = {}",
"s = pd.Series(self._df['... | <|body_start_0|>
super().__init__(var, *args, **kwargs)
self._df['FLAG'] = np.int8(-128)
self.descriptions[-128] = 'A fill value. No flagging information has been provided'
self.descriptions[0] = 'Data are assumed to be valid and representative of the physical quantity measured'
... | DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data. | DecadesClassicFlag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecadesClassicFlag:
"""DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data."""
def __init__(self, var, *args, **kwargs):
"""Initialisation overide. Args: var... | stack_v2_sparse_classes_36k_train_019373 | 11,557 | no_license | [
{
"docstring": "Initialisation overide. Args: var: the DecadesVariable that this flag is associated with.",
"name": "__init__",
"signature": "def __init__(self, var, *args, **kwargs)"
},
{
"docstring": "Return flag values when the instance is called.",
"name": "__call__",
"signature": "d... | 6 | stack_v2_sparse_classes_30k_train_019668 | Implement the Python class `DecadesClassicFlag` described below.
Class description:
DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `DecadesClassicFlag` described below.
Class description:
DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data.
Method signatures and docstrings:
- def __init__(self,... | e8c54f78a97166c5f66b2196ea4d6eb7a33a0bc4 | <|skeleton|>
class DecadesClassicFlag:
"""DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data."""
def __init__(self, var, *args, **kwargs):
"""Initialisation overide. Args: var... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecadesClassicFlag:
"""DecadesClassicFlag: a flag for the traditional DECADES flagging strategy. That is, integer flag values with increasingly large values generally associated with lower quality data."""
def __init__(self, var, *args, **kwargs):
"""Initialisation overide. Args: var: the Decades... | the_stack_v2_python_sparse | ppodd/decades/flags.py | FAAM-146/decades-ppandas | train | 0 |
9952f694bb8ef912ef3ce1c4e089c40a803fd9f5 | [
"Parametre.__init__(self, 'voir', 'view')\nself.schema = '<cle>'\nself.aide_courte = \"affiche le détail d'un cap\"\nself.aide_longue = \"Cette commande permet d'obtenir plus d'informations sur un cap maritime : son point de départ, ses points intermédiaires et son point d'arrivée.\"",
"cle = dic_masques['cle'].c... | <|body_start_0|>
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle>'
self.aide_courte = "affiche le détail d'un cap"
self.aide_longue = "Cette commande permet d'obtenir plus d'informations sur un cap maritime : son point de départ, ses points intermédiaires et son point d'arri... | Commande 'cap voir'. | PrmVoir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVoir:
"""Commande 'cap voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__init__(... | stack_v2_sparse_classes_36k_train_019374 | 3,921 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019217 | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'cap voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'cap voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmVoir:
"""Commande 'cap voir'."""
... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVoir:
"""Commande 'cap voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmVoir:
"""Commande 'cap voir'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle>'
self.aide_courte = "affiche le détail d'un cap"
self.aide_longue = "Cette commande permet d'obtenir plus d'informa... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/cap/voir.py | vincent-lg/tsunami | train | 5 |
bea655b1a9dc4075e504d6de139d02d093366659 | [
"LOG.debug('Initializing a polling monitor...')\nsuper(PollingMonitor, self).__init__(monitor_plugins)\nself.polling_timers = []",
"LOG.debug('Starting a polling monitor...')\ntry:\n for plugin in self.monitor_plugins:\n self.polling_timers.append(self.tg.add_timer(plugin.get_polling_interval(), self.ca... | <|body_start_0|>
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
<|end_body_0|>
<|body_start_1|>
LOG.debug('Starting a polling monitor...')
try:
for plugin in self.monitor_plugins:
... | A polling based monitor. | PollingMonitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_36k_train_019375 | 2,095 | permissive | [
{
"docstring": "Initialize a polling monitor.",
"name": "__init__",
"signature": "def __init__(self, monitor_plugins)"
},
{
"docstring": "Start polling.",
"name": "start_monitoring",
"signature": "def start_monitoring(self)"
},
{
"docstring": "Stop polling.",
"name": "stop_mo... | 3 | stack_v2_sparse_classes_30k_train_020859 | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling. | Implement the Python class `PollingMonitor` described below.
Class description:
A polling based monitor.
Method signatures and docstrings:
- def __init__(self, monitor_plugins): Initialize a polling monitor.
- def start_monitoring(self): Start polling.
- def stop_monitoring(self): Stop polling.
<|skeleton|>
class Po... | 5ecdc85538f8172eb63b13441dc08b166851befe | <|skeleton|>
class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
<|body_0|>
def start_monitoring(self):
"""Start polling."""
<|body_1|>
def stop_monitoring(self):
"""Stop polling."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PollingMonitor:
"""A polling based monitor."""
def __init__(self, monitor_plugins):
"""Initialize a polling monitor."""
LOG.debug('Initializing a polling monitor...')
super(PollingMonitor, self).__init__(monitor_plugins)
self.polling_timers = []
def start_monitoring(s... | the_stack_v2_python_sparse | blazar/monitor/polling_monitor.py | ChameleonCloud/blazar | train | 1 |
c63cb5ee6c88757f99046e35bea84a5373ecc517 | [
"described = descriptor.describe_file_set([])\ndescribed.check_initialized()\nself.assertEquals(descriptor.FileSet(), described)",
"modules = [types.ModuleType('package1'), types.ModuleType('package1')]\nfile1 = descriptor.FileDescriptor()\nfile1.package = 'package1'\nfile2 = descriptor.FileDescriptor()\nfile2.pa... | <|body_start_0|>
described = descriptor.describe_file_set([])
described.check_initialized()
self.assertEquals(descriptor.FileSet(), described)
<|end_body_0|>
<|body_start_1|>
modules = [types.ModuleType('package1'), types.ModuleType('package1')]
file1 = descriptor.FileDescriptor... | Test describing multiple modules. | DescribeFileSetTest | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
<|body_0|>
def testWithModules(self):
"""Test what happens when no modules provided."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_019376 | 17,140 | permissive | [
{
"docstring": "Test what happens when no modules provided.",
"name": "testNoModules",
"signature": "def testNoModules(self)"
},
{
"docstring": "Test what happens when no modules provided.",
"name": "testWithModules",
"signature": "def testWithModules(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009331 | Implement the Python class `DescribeFileSetTest` described below.
Class description:
Test describing multiple modules.
Method signatures and docstrings:
- def testNoModules(self): Test what happens when no modules provided.
- def testWithModules(self): Test what happens when no modules provided. | Implement the Python class `DescribeFileSetTest` described below.
Class description:
Test describing multiple modules.
Method signatures and docstrings:
- def testNoModules(self): Test what happens when no modules provided.
- def testWithModules(self): Test what happens when no modules provided.
<|skeleton|>
class D... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
<|body_0|>
def testWithModules(self):
"""Test what happens when no modules provided."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DescribeFileSetTest:
"""Test describing multiple modules."""
def testNoModules(self):
"""Test what happens when no modules provided."""
described = descriptor.describe_file_set([])
described.check_initialized()
self.assertEquals(descriptor.FileSet(), described)
def te... | the_stack_v2_python_sparse | third_party/google-endpoints/apitools/base/protorpclite/descriptor_test.py | catapult-project/catapult | train | 2,032 |
de8e2c61ef548c7b2dc0f74fff9bdc1df469d1d6 | [
"if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exists():\n record = AuthenticationCode.objects.filter(phone_num=phone, is_active=True).first()\n if (timezone.now() - record.created_at).total_seconds() > seconds:\n AuthenticationCode.objects.filter(phone_num=phone).update(is_acti... | <|body_start_0|>
if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exists():
record = AuthenticationCode.objects.filter(phone_num=phone, is_active=True).first()
if (timezone.now() - record.created_at).total_seconds() > seconds:
AuthenticationCode.objec... | AuthenticationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
<|body_0|>
def check_code(self, code, phone, seconds=6... | stack_v2_sparse_classes_36k_train_019377 | 7,061 | no_license | [
{
"docstring": "Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold",
"name": "already_sent",
"signature": "def already_sent(self, phone, seconds=60)"
},
{
"docstring": "Check the code :param code au... | 3 | stack_v2_sparse_classes_30k_train_014854 | Implement the Python class `AuthenticationManager` described below.
Class description:
Implement the AuthenticationManager class.
Method signatures and docstrings:
- def already_sent(self, phone, seconds=60): Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone pho... | Implement the Python class `AuthenticationManager` described below.
Class description:
Implement the AuthenticationManager class.
Method signatures and docstrings:
- def already_sent(self, phone, seconds=60): Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone pho... | e3cd0b466393b3e9822a752d27082c063ee79ff6 | <|skeleton|>
class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
<|body_0|>
def check_code(self, code, phone, seconds=6... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticationManager:
def already_sent(self, phone, seconds=60):
"""Check if a valid authentication code has already sent to the given phone number in `seconds` :param phone phone number :param seconds time threshold"""
if AuthenticationCode.objects.filter(phone_num=phone, is_active=True).exi... | the_stack_v2_python_sparse | User/models.py | huangy10/SingingVoice | train | 0 | |
53f36807f85cb5c6de0e623b2795c303145f83d3 | [
"super(MultiLayerPerceptron, self).__init__()\nself.dims = [input_dim] + hidden_dims\nif isinstance(activation, str):\n self.activation = getattr(F, activation)\nelse:\n logger.info(f'Warning, activation passed {activation} is not string and ignored')\n self.activation = None\nif dropout > 0:\n self.dro... | <|body_start_0|>
super(MultiLayerPerceptron, self).__init__()
self.dims = [input_dim] + hidden_dims
if isinstance(activation, str):
self.activation = getattr(F, activation)
else:
logger.info(f'Warning, activation passed {activation} is not string and ignored')
... | Multi-layer Perceptron. Note there is no activation or dropout in the last layer. | MultiLayerPerceptron | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dim... | stack_v2_sparse_classes_36k_train_019378 | 15,380 | permissive | [
{
"docstring": "Initialize multi-layer perceptron. Args: input_dim: input dimension hidden_dim: hidden dimensions activation: activation function dropout: dropout rate",
"name": "__init__",
"signature": "def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0)... | 2 | stack_v2_sparse_classes_30k_train_019520 | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Multi-layer Perceptron. Note there is no activation or dropout in the last layer.
Method signatures and docstrings:
- def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None: Init... | Implement the Python class `MultiLayerPerceptron` described below.
Class description:
Multi-layer Perceptron. Note there is no activation or dropout in the last layer.
Method signatures and docstrings:
- def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None: Init... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiLayerPerceptron:
"""Multi-layer Perceptron. Note there is no activation or dropout in the last layer."""
def __init__(self, input_dim: int, hidden_dims: List[int], activation: str='relu', dropout: float=0) -> None:
"""Initialize multi-layer perceptron. Args: input_dim: input dimension hidden... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/diffusion/geodiff/model/layers.py | GT4SD/gt4sd-core | train | 239 |
7304121193dc001c0a21f9601ef97df6c48d5f25 | [
"if unsafe:\n if unit is None:\n self._Factorization__unit = ZZ._one_element\n else:\n self._Factorization__unit = unit\n self._Factorization__x = x\n self._Factorization__universe = ZZ\n self._Factorization__cr = cr\n if sort:\n self.sort()\n if simplify:\n self.sim... | <|body_start_0|>
if unsafe:
if unit is None:
self._Factorization__unit = ZZ._one_element
else:
self._Factorization__unit = unit
self._Factorization__x = x
self._Factorization__universe = ZZ
self._Factorization__cr = cr
... | A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` object upon initialization. However, for the typical ... | IntegerFactorization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegerFactorization:
"""A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` objec... | stack_v2_sparse_classes_36k_train_019379 | 4,464 | no_license | [
{
"docstring": "Sets ``self`` to the factorization object with list ``x``, which must be a sorted list of pairs, where each pair contains a factor and an exponent. If the flag ``unsafe`` is set to ``False`` this method delegates the initialization to the parent class, which means that a rather lenient and caref... | 2 | null | Implement the Python class `IntegerFactorization` described below.
Class description:
A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passe... | Implement the Python class `IntegerFactorization` described below.
Class description:
A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passe... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class IntegerFactorization:
"""A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` objec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntegerFactorization:
"""A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` object upon initia... | the_stack_v2_python_sparse | sage/src/sage/structure/factorization_integer.py | bopopescu/geosci | train | 0 |
3111a3e3fe013fa15418adbdc9e47df1f519ea4e | [
"self.isKey = False\nself.val = 0\nself.kids = dict()",
"current_node = self\nfor idx, letter in enumerate(key):\n if letter not in current_node.kids:\n current_node.kids[letter] = MapSum()\n current_node = current_node.kids[letter]\n if idx == len(key) - 1:\n current_node.val = val\n ... | <|body_start_0|>
self.isKey = False
self.val = 0
self.kids = dict()
<|end_body_0|>
<|body_start_1|>
current_node = self
for idx, letter in enumerate(key):
if letter not in current_node.kids:
current_node.kids[letter] = MapSum()
current_nod... | MapSum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapSum:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, key, val):
""":type key: str :type val: int :rtype: void"""
<|body_1|>
def sum(self, prefix):
""":type prefix: str :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_019380 | 1,659 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type key: str :type val: int :rtype: void",
"name": "insert",
"signature": "def insert(self, key, val)"
},
{
"docstring": ":type prefix: str :rtype: in... | 3 | stack_v2_sparse_classes_30k_train_014940 | Implement the Python class `MapSum` described below.
Class description:
Implement the MapSum class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, key, val): :type key: str :type val: int :rtype: void
- def sum(self, prefix): :type prefix: str :rtype: i... | Implement the Python class `MapSum` described below.
Class description:
Implement the MapSum class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, key, val): :type key: str :type val: int :rtype: void
- def sum(self, prefix): :type prefix: str :rtype: i... | f462b66ae849f4332a4b150f206dd49c7519e83b | <|skeleton|>
class MapSum:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, key, val):
""":type key: str :type val: int :rtype: void"""
<|body_1|>
def sum(self, prefix):
""":type prefix: str :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MapSum:
def __init__(self):
"""Initialize your data structure here."""
self.isKey = False
self.val = 0
self.kids = dict()
def insert(self, key, val):
""":type key: str :type val: int :rtype: void"""
current_node = self
for idx, letter in enumerate(k... | the_stack_v2_python_sparse | LeetCode/DataStructure/trie/map_sum.py | hooyao/Coding-Py3 | train | 0 | |
4950d8b39f6cb29bedca280893103d832fa60d4a | [
"assert df_desc.index.is_unique\nself.df_desc = df_desc.copy()\nself.df_desc.index = df_desc.index.map(str)\nself.df_links = df_links.copy()\nself.df_links[['id1', 'id2']] = self.df_links[['id1', 'id2']].astype(str)\nself.df_links[['id1', 'id2']] = np.sort(self.df_links[['id1', 'id2']], axis=1)\nif pickmin:\n se... | <|body_start_0|>
assert df_desc.index.is_unique
self.df_desc = df_desc.copy()
self.df_desc.index = df_desc.index.map(str)
self.df_links = df_links.copy()
self.df_links[['id1', 'id2']] = self.df_links[['id1', 'id2']].astype(str)
self.df_links[['id1', 'id2']] = np.sort(self... | clanswriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class clanswriter:
def __init__(self, df_links, df_desc, pickmin=True, cf=conversion_empty_function):
"""Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame with id (index!), sequence, group data pickmin: In the case of redundant links (id1->id2 and id2->id1... | stack_v2_sparse_classes_36k_train_019381 | 7,057 | no_license | [
{
"docstring": "Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame with id (index!), sequence, group data pickmin: In the case of redundant links (id1->id2 and id2->id1 present) the one with lowest (pickmin=True) or highest (pickmin=Flase) score will be taken cf: Function to... | 2 | null | Implement the Python class `clanswriter` described below.
Class description:
Implement the clanswriter class.
Method signatures and docstrings:
- def __init__(self, df_links, df_desc, pickmin=True, cf=conversion_empty_function): Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame w... | Implement the Python class `clanswriter` described below.
Class description:
Implement the clanswriter class.
Method signatures and docstrings:
- def __init__(self, df_links, df_desc, pickmin=True, cf=conversion_empty_function): Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame w... | 9219aee5571e15c6123e5e191d84a1cb821cd5b3 | <|skeleton|>
class clanswriter:
def __init__(self, df_links, df_desc, pickmin=True, cf=conversion_empty_function):
"""Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame with id (index!), sequence, group data pickmin: In the case of redundant links (id1->id2 and id2->id1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class clanswriter:
def __init__(self, df_links, df_desc, pickmin=True, cf=conversion_empty_function):
"""Args: df_links: A Pandas DatFrame with id1, id2, value data df_desc: A Pandas DataFrame with id (index!), sequence, group data pickmin: In the case of redundant links (id1->id2 and id2->id1 present) the ... | the_stack_v2_python_sparse | lbs/clans/clanswriter.py | labstructbioinf/lbs-tools | train | 9 | |
e604de2ee2fcf48a388b44ea7bf154e91e27e16d | [
"try:\n from config_parser import config_parser\n self.conf_file = current_file_path + '/../../conf/appviewx.conf'\n self.conf_data = config_parser(self.conf_file)\n self.hostname = socket.gethostbyname(socket.gethostname())\n self.ip = ip\nexcept Exception as e:\n print(colored(e, 'red'))\n lg... | <|body_start_0|>
try:
from config_parser import config_parser
self.conf_file = current_file_path + '/../../conf/appviewx.conf'
self.conf_data = config_parser(self.conf_file)
self.hostname = socket.gethostbyname(socket.gethostname())
self.ip = ip
... | . | InitializeMongoDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitializeMongoDB:
"""."""
def __init__(self, ip=False):
"""."""
<|body_0|>
def initialize(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
from config_parser import config_parser
self.conf_file = current_... | stack_v2_sparse_classes_36k_train_019382 | 2,724 | no_license | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, ip=False)"
},
{
"docstring": ".",
"name": "initialize",
"signature": "def initialize(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003530 | Implement the Python class `InitializeMongoDB` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, ip=False): .
- def initialize(self): . | Implement the Python class `InitializeMongoDB` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, ip=False): .
- def initialize(self): .
<|skeleton|>
class InitializeMongoDB:
"""."""
def __init__(self, ip=False):
"""."""
<|body_0|>
def initializ... | e513224364dce05ea4d17ac25ecfa981238b1311 | <|skeleton|>
class InitializeMongoDB:
"""."""
def __init__(self, ip=False):
"""."""
<|body_0|>
def initialize(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitializeMongoDB:
"""."""
def __init__(self, ip=False):
"""."""
try:
from config_parser import config_parser
self.conf_file = current_file_path + '/../../conf/appviewx.conf'
self.conf_data = config_parser(self.conf_file)
self.hostname = soc... | the_stack_v2_python_sparse | scripts_avx/scripts/scripts/Mongodb/initialize_mongodb.py | Poonammahunta/Integration | train | 0 |
c3cc1234c7d285ccaa1542d18c7f2500e6e9b700 | [
"fn = os.path.join(self._base_data_dir, 'MASSIVEBLACKII/StellarMass_HaloMass/tab_new.txt')\nself._validation_data = dict(zip(('x', 'y', 'y-', 'y+'), np.loadtxt(fn, unpack=True, usecols=(0, 1, 3, 4))))\nself._validation_data['cov'] = np.diag(((self._validation_data['y+'] - self._validation_data['y-']) * 0.5) ** 2.0)... | <|body_start_0|>
fn = os.path.join(self._base_data_dir, 'MASSIVEBLACKII/StellarMass_HaloMass/tab_new.txt')
self._validation_data = dict(zip(('x', 'y', 'y-', 'y+'), np.loadtxt(fn, unpack=True, usecols=(0, 1, 3, 4))))
self._validation_data['cov'] = np.diag(((self._validation_data['y+'] - self._val... | validation test class object to compute stellar mass halo mass relation | StellarMassHaloMassTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StellarMassHaloMassTest:
"""validation test class object to compute stellar mass halo mass relation"""
def _subclass_init(self, **kwargs):
"""load tabulated stellar mass halo mass function data"""
<|body_0|>
def _get_quantities_from_catalog(self, galaxy_catalog):
... | stack_v2_sparse_classes_36k_train_019383 | 4,421 | permissive | [
{
"docstring": "load tabulated stellar mass halo mass function data",
"name": "_subclass_init",
"signature": "def _subclass_init(self, **kwargs)"
},
{
"docstring": "obtain the masses and mask fom the galaxy catalog Parameters ---------- galaxy_catalog : galaxy catalog reader object",
"name":... | 3 | null | Implement the Python class `StellarMassHaloMassTest` described below.
Class description:
validation test class object to compute stellar mass halo mass relation
Method signatures and docstrings:
- def _subclass_init(self, **kwargs): load tabulated stellar mass halo mass function data
- def _get_quantities_from_catalo... | Implement the Python class `StellarMassHaloMassTest` described below.
Class description:
validation test class object to compute stellar mass halo mass relation
Method signatures and docstrings:
- def _subclass_init(self, **kwargs): load tabulated stellar mass halo mass function data
- def _get_quantities_from_catalo... | d7bd97f4b98ec37ebe2343dbc57fb74267acd62b | <|skeleton|>
class StellarMassHaloMassTest:
"""validation test class object to compute stellar mass halo mass relation"""
def _subclass_init(self, **kwargs):
"""load tabulated stellar mass halo mass function data"""
<|body_0|>
def _get_quantities_from_catalog(self, galaxy_catalog):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StellarMassHaloMassTest:
"""validation test class object to compute stellar mass halo mass relation"""
def _subclass_init(self, **kwargs):
"""load tabulated stellar mass halo mass function data"""
fn = os.path.join(self._base_data_dir, 'MASSIVEBLACKII/StellarMass_HaloMass/tab_new.txt')
... | the_stack_v2_python_sparse | v1/descqa/StellarMassHaloMassTest.py | LSSTDESC/descqa | train | 8 |
1cc63622bf211cd68929c7d9fe26c52de86e52f5 | [
"try:\n this_record = ProfileImages.objects.get(pk=self.pk)\n if this_record.image != self.image:\n this_record.image.delete(save=False)\n this_record.image_thumb.delete(save=False)\nexcept:\n pass\nself.create_thumbnail(width=300, height=300, from_img=self.image, to_img=self.image_thumb)\nfo... | <|body_start_0|>
try:
this_record = ProfileImages.objects.get(pk=self.pk)
if this_record.image != self.image:
this_record.image.delete(save=False)
this_record.image_thumb.delete(save=False)
except:
pass
self.create_thumbnail(wid... | Изображения пользователя | ProfileImages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileImages:
"""Изображения пользователя"""
def save(self, *args, **kwargs):
"""Сохранение фото"""
<|body_0|>
def delete(self, *args, **kwargs):
"""Удаление фото"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
this_record = Pr... | stack_v2_sparse_classes_36k_train_019384 | 6,955 | no_license | [
{
"docstring": "Сохранение фото",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Удаление фото",
"name": "delete",
"signature": "def delete(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014553 | Implement the Python class `ProfileImages` described below.
Class description:
Изображения пользователя
Method signatures and docstrings:
- def save(self, *args, **kwargs): Сохранение фото
- def delete(self, *args, **kwargs): Удаление фото | Implement the Python class `ProfileImages` described below.
Class description:
Изображения пользователя
Method signatures and docstrings:
- def save(self, *args, **kwargs): Сохранение фото
- def delete(self, *args, **kwargs): Удаление фото
<|skeleton|>
class ProfileImages:
"""Изображения пользователя"""
def... | 23b9102913b67f2e5fdc92c7ef1e85fa52492834 | <|skeleton|>
class ProfileImages:
"""Изображения пользователя"""
def save(self, *args, **kwargs):
"""Сохранение фото"""
<|body_0|>
def delete(self, *args, **kwargs):
"""Удаление фото"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileImages:
"""Изображения пользователя"""
def save(self, *args, **kwargs):
"""Сохранение фото"""
try:
this_record = ProfileImages.objects.get(pk=self.pk)
if this_record.image != self.image:
this_record.image.delete(save=False)
th... | the_stack_v2_python_sparse | pages/userprofile/models.py | snakent/faunamira | train | 0 |
a94570d1a23c3567d5d1ef72e726c30f863b4e82 | [
"url = self._get_base_url()\nresp = self.request('POST', url, request_entity=CreateTenant(tenant_id))\nreturn resp",
"url = '{base}/{tenant_id}'.format(base=self._get_base_url(), tenant_id=tenant_id)\nresp = self.request('GET', url, response_entity_type=Tenant)\nreturn resp",
"url = '{base}/{tenant_id}/token'.f... | <|body_start_0|>
url = self._get_base_url()
resp = self.request('POST', url, request_entity=CreateTenant(tenant_id))
return resp
<|end_body_0|>
<|body_start_1|>
url = '{base}/{tenant_id}'.format(base=self._get_base_url(), tenant_id=tenant_id)
resp = self.request('GET', url, resp... | TenantClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantClient:
def create_tenant(self, tenant_id):
"""@summary: Creates a tenant with the given id @param tenant_id:"""
<|body_0|>
def get_tenant(self, tenant_id):
"""@summary: Retrieves the version information from the API"""
<|body_1|>
def validate_toke... | stack_v2_sparse_classes_36k_train_019385 | 6,572 | permissive | [
{
"docstring": "@summary: Creates a tenant with the given id @param tenant_id:",
"name": "create_tenant",
"signature": "def create_tenant(self, tenant_id)"
},
{
"docstring": "@summary: Retrieves the version information from the API",
"name": "get_tenant",
"signature": "def get_tenant(sel... | 4 | stack_v2_sparse_classes_30k_train_021462 | Implement the Python class `TenantClient` described below.
Class description:
Implement the TenantClient class.
Method signatures and docstrings:
- def create_tenant(self, tenant_id): @summary: Creates a tenant with the given id @param tenant_id:
- def get_tenant(self, tenant_id): @summary: Retrieves the version info... | Implement the Python class `TenantClient` described below.
Class description:
Implement the TenantClient class.
Method signatures and docstrings:
- def create_tenant(self, tenant_id): @summary: Creates a tenant with the given id @param tenant_id:
- def get_tenant(self, tenant_id): @summary: Retrieves the version info... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class TenantClient:
def create_tenant(self, tenant_id):
"""@summary: Creates a tenant with the given id @param tenant_id:"""
<|body_0|>
def get_tenant(self, tenant_id):
"""@summary: Retrieves the version information from the API"""
<|body_1|>
def validate_toke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantClient:
def create_tenant(self, tenant_id):
"""@summary: Creates a tenant with the given id @param tenant_id:"""
url = self._get_base_url()
resp = self.request('POST', url, request_entity=CreateTenant(tenant_id))
return resp
def get_tenant(self, tenant_id):
"... | the_stack_v2_python_sparse | cloudcafe/meniscus/tenant_api/client.py | kurhula/cloudcafe | train | 0 | |
4a2686406b220a6c21244889000fa0b7a858aa81 | [
"tests = ['KIF.test1', 'KIF.test2']\nexpected = 'NAME:test1|test2'\nself.assertEqual(expected, test_apps.get_kif_test_filter(tests))",
"tests = ['KIF.test1', 'KIF.test2']\nexpected = '-NAME:test1|test2'\nself.assertEqual(expected, test_apps.get_kif_test_filter(tests, invert=True))"
] | <|body_start_0|>
tests = ['KIF.test1', 'KIF.test2']
expected = 'NAME:test1|test2'
self.assertEqual(expected, test_apps.get_kif_test_filter(tests))
<|end_body_0|>
<|body_start_1|>
tests = ['KIF.test1', 'KIF.test2']
expected = '-NAME:test1|test2'
self.assertEqual(expected,... | Tests for test_runner.get_kif_test_filter. | GetKIFTestFilterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_019386 | 1,492 | permissive | [
{
"docstring": "Ensures correctness of filter.",
"name": "test_correct",
"signature": "def test_correct(self)"
},
{
"docstring": "Ensures correctness of inverted filter.",
"name": "test_correct_inverted",
"signature": "def test_correct_inverted(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018194 | Implement the Python class `GetKIFTestFilterTest` described below.
Class description:
Tests for test_runner.get_kif_test_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter. | Implement the Python class `GetKIFTestFilterTest` described below.
Class description:
Tests for test_runner.get_kif_test_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter.
<|skeleton|>
class Get... | 64bee65c921db7e78e25d08f1e98da2668b57be5 | <|skeleton|>
class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetKIFTestFilterTest:
"""Tests for test_runner.get_kif_test_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
tests = ['KIF.test1', 'KIF.test2']
expected = 'NAME:test1|test2'
self.assertEqual(expected, test_apps.get_kif_test_filter(tests))
def te... | the_stack_v2_python_sparse | ios/build/bots/scripts/test_apps_test.py | otcshare/chromium-src | train | 18 |
76099d1e141be2c47a5a0c71a385c426959eec49 | [
"self.project = project\nself.previously_indexed = []\nself.logger = logging.getLogger(__name__)\nself.project_logger = ProjectLogger(self.logger, project)",
"without_stops = []\nfor word in words:\n if word.word.lower() not in app.config['STOPWORDS']:\n without_stops.append(word)\nreturn without_stops"... | <|body_start_0|>
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = ProjectLogger(self.logger, project)
<|end_body_0|>
<|body_start_1|>
without_stops = []
for word in words:
if word.word.lower()... | Process given input into Sequences. | SequenceProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_36k_train_019387 | 8,706 | no_license | [
{
"docstring": "Set up local variables for the SequenceProcessor.",
"name": "__init__",
"signature": "def __init__(self, project)"
},
{
"docstring": "Remove every sort of stop from the sentences. :param list words: A list of TaggedWord objects. :return list: The list without stops.",
"name":... | 4 | stack_v2_sparse_classes_30k_train_012518 | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | 93b90e6a8592a26c6efa09ea5f5aa4fab044f9d7 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = Pro... | the_stack_v2_python_sparse | app/preprocessor/sequenceprocessor.py | xiaobaozi34/wordseer | train | 0 |
312509458ab71519b147186903172acf4a3ed926 | [
"def decorator(subclass):\n cls.subclasses[impact_type] = subclass\n return subclass\nreturn decorator",
"if impact_type not in cls.subclasses:\n raise ValueError('Bad impact type {}'.format(impact_type))\nif vampire_defaults is None:\n vp = VampireDefaults.VampireDefaults()\nelse:\n vp = vampire_d... | <|body_start_0|>
def decorator(subclass):
cls.subclasses[impact_type] = subclass
return subclass
return decorator
<|end_body_0|>
<|body_start_1|>
if impact_type not in cls.subclasses:
raise ValueError('Bad impact type {}'.format(impact_type))
if vampi... | Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to generate config file sections related to impact of the data product. | BaseImpactProduct | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseImpactProduct:
"""Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to generate config file sections related to ... | stack_v2_sparse_classes_36k_train_019388 | 27,246 | no_license | [
{
"docstring": "Register product impact with the productimpact manager. Registers the data product impact identified by impact_type with the product impact manager. This allows the appropriate product impact to be created automatically when requested. :param impact_type: Product name. :type impact_type: string"... | 2 | null | Implement the Python class `BaseImpactProduct` described below.
Class description:
Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to ge... | Implement the Python class `BaseImpactProduct` described below.
Class description:
Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to ge... | 143ae8d1c518ef2771447dbf6dcb544e5e199f1e | <|skeleton|>
class BaseImpactProduct:
"""Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to generate config file sections related to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseImpactProduct:
"""Base class for data product impact configuration objects. Manages registration of data product impact configurations and creation of data product impact configuration objects. Data product impact configurations provide the ability to generate config file sections related to impact of the... | the_stack_v2_python_sparse | vampire/config_products/BaseImpactProduct.py | asrofialkindi/vampire | train | 1 |
19dbbd6c7bcfe30e6cf125f1e2a22fa9e8e235eb | [
"self.tester = tester.Tester()\nself.tester.register_handler(event_types.BeginEvent, on_begin)\nself.tester.register_handler(event_types.CaseTestedEvent, on_case)\nself.tester.register_handler(event_types.FinishEvent, on_finish)\nself.truncate_amount = truncate_amount\nself.show_correct_output = show_correct_output... | <|body_start_0|>
self.tester = tester.Tester()
self.tester.register_handler(event_types.BeginEvent, on_begin)
self.tester.register_handler(event_types.CaseTestedEvent, on_case)
self.tester.register_handler(event_types.FinishEvent, on_finish)
self.truncate_amount = truncate_amount... | A text based display mechanism for test case results | TextHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextHandler:
"""A text based display mechanism for test case results"""
def __init__(self, show_time=True, show_score=True, show_correct_output=True, truncate_amount=TRUNCATE_AMOUNT):
"""Constructor :param show_time: Controls whether the run time is shown :param show_score: Controls ... | stack_v2_sparse_classes_36k_train_019389 | 2,286 | no_license | [
{
"docstring": "Constructor :param show_time: Controls whether the run time is shown :param show_score: Controls whether a score is shown in the end :param show_correct_output: Controls whether correct output is shown in case of a WA :param truncate_amount: How much to truncate output by (if it is being display... | 2 | stack_v2_sparse_classes_30k_train_004837 | Implement the Python class `TextHandler` described below.
Class description:
A text based display mechanism for test case results
Method signatures and docstrings:
- def __init__(self, show_time=True, show_score=True, show_correct_output=True, truncate_amount=TRUNCATE_AMOUNT): Constructor :param show_time: Controls w... | Implement the Python class `TextHandler` described below.
Class description:
A text based display mechanism for test case results
Method signatures and docstrings:
- def __init__(self, show_time=True, show_score=True, show_correct_output=True, truncate_amount=TRUNCATE_AMOUNT): Constructor :param show_time: Controls w... | 6bac81405275f76b429d8aae53c395c97b178f83 | <|skeleton|>
class TextHandler:
"""A text based display mechanism for test case results"""
def __init__(self, show_time=True, show_score=True, show_correct_output=True, truncate_amount=TRUNCATE_AMOUNT):
"""Constructor :param show_time: Controls whether the run time is shown :param show_score: Controls ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextHandler:
"""A text based display mechanism for test case results"""
def __init__(self, show_time=True, show_score=True, show_correct_output=True, truncate_amount=TRUNCATE_AMOUNT):
"""Constructor :param show_time: Controls whether the run time is shown :param show_score: Controls whether a sco... | the_stack_v2_python_sparse | tester/handlers/text_handler.py | plasmatic1/PYTester | train | 0 |
1eb76ce3da77c8d9e57f2a7dee93307b98ed617d | [
"if not nums:\n return 1\nn = len(nums)\nprint(n)\nfor i, num in enumerate(nums):\n while 0 < nums[i] <= n and nums[i] != nums[nums[i] - 1]:\n nums[nums[i] - 1], nums[i] = (nums[i], nums[nums[i] - 1])\n print(nums)\nfor i, num in enumerate(nums):\n if num != i + 1:\n return i + 1\nreturn n... | <|body_start_0|>
if not nums:
return 1
n = len(nums)
print(n)
for i, num in enumerate(nums):
while 0 < nums[i] <= n and nums[i] != nums[nums[i] - 1]:
nums[nums[i] - 1], nums[i] = (nums[i], nums[nums[i] - 1])
print(nums)
for i, n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositiveEasyUnderstand(self, nums):
""":type nums: List[int] :rtype: int 1. for any array whose length is l, the first missing positive must be in range... | stack_v2_sparse_classes_36k_train_019390 | 2,537 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 1. for any array whose length is l, the first missing positive must be in range [1,...,l+1], so we only hav... | 2 | stack_v2_sparse_classes_30k_train_019552 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositiveEasyUnderstand(self, nums): :type nums: List[int] :rtype: int 1. for any array w... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositiveEasyUnderstand(self, nums): :type nums: List[int] :rtype: int 1. for any array w... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositiveEasyUnderstand(self, nums):
""":type nums: List[int] :rtype: int 1. for any array whose length is l, the first missing positive must be in range... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 1
n = len(nums)
print(n)
for i, num in enumerate(nums):
while 0 < nums[i] <= n and nums[i] != nums[nums[i] - 1]:
nums[nums... | the_stack_v2_python_sparse | F/FirstMissingPositive.py | bssrdf/pyleet | train | 2 | |
cdb0a9508fc9e0594a98159e57824fd462f54e7c | [
"coords = [0, math.inf]\nheights = [0, 0]\nres = []\nfor l, h in positions:\n r = l + h\n l_idx = bisect.bisect_right(coords, l)\n r_idx = bisect.bisect_left(coords, r)\n new_h = max(heights[l_idx - 1:r_idx]) + h\n coords[l_idx:r_idx] = [l, r]\n heights[l_idx:r_idx] = [new_h, heights[r_idx - 1]]\n... | <|body_start_0|>
coords = [0, math.inf]
heights = [0, 0]
res = []
for l, h in positions:
r = l + h
l_idx = bisect.bisect_right(coords, l)
r_idx = bisect.bisect_left(coords, r)
new_h = max(heights[l_idx - 1:r_idx]) + h
coords[l_i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fallingSquares_OJBest(self, positions):
""":type positions: List[List[int]] :rtype: List[int]"""
<|body_0|>
def fallingSquares(self, positions):
""":type positions: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_019391 | 3,726 | no_license | [
{
"docstring": ":type positions: List[List[int]] :rtype: List[int]",
"name": "fallingSquares_OJBest",
"signature": "def fallingSquares_OJBest(self, positions)"
},
{
"docstring": ":type positions: List[List[int]] :rtype: List[int]",
"name": "fallingSquares",
"signature": "def fallingSquar... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fallingSquares_OJBest(self, positions): :type positions: List[List[int]] :rtype: List[int]
- def fallingSquares(self, positions): :type positions: List[List[int]] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fallingSquares_OJBest(self, positions): :type positions: List[List[int]] :rtype: List[int]
- def fallingSquares(self, positions): :type positions: List[List[int]] :rtype: Lis... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def fallingSquares_OJBest(self, positions):
""":type positions: List[List[int]] :rtype: List[int]"""
<|body_0|>
def fallingSquares(self, positions):
""":type positions: List[List[int]] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fallingSquares_OJBest(self, positions):
""":type positions: List[List[int]] :rtype: List[int]"""
coords = [0, math.inf]
heights = [0, 0]
res = []
for l, h in positions:
r = l + h
l_idx = bisect.bisect_right(coords, l)
r_... | the_stack_v2_python_sparse | code699FallingSquares.py | cybelewang/leetcode-python | train | 0 | |
b1ee6afd7de1b8d8b2d980eaf72dabb2537f1946 | [
"output = []\nqueue = [root]\nwhile queue:\n current = queue.pop(0)\n output.append(str(current.val) if current else '#')\n if current is None:\n continue\n queue.append(current.left)\n queue.append(current.right)\nreturn ','.join(output)",
"queue = data.split(',')\nqueue = [None if val == '... | <|body_start_0|>
output = []
queue = [root]
while queue:
current = queue.pop(0)
output.append(str(current.val) if current else '#')
if current is None:
continue
queue.append(current.left)
queue.append(current.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_019392 | 1,538 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002579 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 684e4d72e80bd56d159f37913cc9af9877388b5d | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
output = []
queue = [root]
while queue:
current = queue.pop(0)
output.append(str(current.val) if current else '#')
if current is None:... | the_stack_v2_python_sparse | serialize_and_deserialize_binary_tree_297.py | gowthamgoli/Leetcode | train | 0 | |
4e17baec440eed22ff47d5ed9e440e91edc021ef | [
"pidb = ParsedItemsDb()\nif is_zip(path):\n with ZipFile(path) as fzip:\n for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):\n pidb = cls._parse_data(file_from_zip(path, fname).decode('utf-8'), pidb)\n return pidb\nreturn cls._parse_data(Path(path).read_text(enco... | <|body_start_0|>
pidb = ParsedItemsDb()
if is_zip(path):
with ZipFile(path) as fzip:
for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):
pidb = cls._parse_data(file_from_zip(path, fname).decode('utf-8'), pidb)
return... | nmap xml output parser | ParserModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserModule:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(cls, data, pidb):
"""parse raw string data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pidb = ParsedItemsDb()
... | stack_v2_sparse_classes_36k_train_019393 | 3,775 | permissive | [
{
"docstring": "parse data from path",
"name": "parse_path",
"signature": "def parse_path(cls, path)"
},
{
"docstring": "parse raw string data",
"name": "_parse_data",
"signature": "def _parse_data(cls, data, pidb)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013809 | Implement the Python class `ParserModule` described below.
Class description:
nmap xml output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(cls, data, pidb): parse raw string data | Implement the Python class `ParserModule` described below.
Class description:
nmap xml output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(cls, data, pidb): parse raw string data
<|skeleton|>
class ParserModule:
"""nmap xml output parser"""
def... | d5d8e9cdd6dd058dd91eb119965a3f9f737e5c34 | <|skeleton|>
class ParserModule:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(cls, data, pidb):
"""parse raw string data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserModule:
"""nmap xml output parser"""
def parse_path(cls, path):
"""parse data from path"""
pidb = ParsedItemsDb()
if is_zip(path):
with ZipFile(path) as fzip:
for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):
... | the_stack_v2_python_sparse | sner/plugin/nmap/parser.py | bodik/sner4 | train | 13 |
f200a142c48d3fd1c792c6150aa8f9d2e7b830d9 | [
"if not matrix:\n return False\nmaxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)\nmaxColIndex = bisect.bisect_right(matrix[0], target)\nfor ri in range(maxRowIndex):\n row = matrix[ri]\n if self.binary_search(row, 0, maxColIndex, target) != -1:\n return True\nreturn False",
"i... | <|body_start_0|>
if not matrix:
return False
maxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)
maxColIndex = bisect.bisect_right(matrix[0], target)
for ri in range(maxRowIndex):
row = matrix[ri]
if self.binary_search(row, 0, maxColI... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix3(self, matrix, target):
"""152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param m... | stack_v2_sparse_classes_36k_train_019394 | 3,455 | permissive | [
{
"docstring": "268ms :type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def searchMatrix2(self, matrix, target)"
},
{
"docstring": "152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param matrix: :param target: :r... | 4 | stack_v2_sparse_classes_30k_val_000350 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix2(self, matrix, target): 268ms :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix3(self, matrix, target): 152ms 一行一行的进行二叉查找 如果第一个元素比t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix2(self, matrix, target): 268ms :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix3(self, matrix, target): 152ms 一行一行的进行二叉查找 如果第一个元素比t... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix3(self, matrix, target):
"""152ms 一行一行的进行二叉查找 如果第一个元素比target大,结束查找并返回False 每一行查找的有边界是上一行的最后一个小于target的元素的下标 :param m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix2(self, matrix, target):
"""268ms :type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
maxRowIndex = bisect.bisect_right([row[0] for row in matrix], target)
maxColIndex = bisect.bisect_right(matrix[0],... | the_stack_v2_python_sparse | leetcode/medium/Search_a_2D_Matrix_II.py | shhuan/algorithms | train | 0 | |
8c4ab4508eb926c092c898d9562bea264f96e2ba | [
"self._points = [_format_LatLng(lat, lng, precision) for lat, lng in zip(lats, lngs)]\nedge_color = kwargs.get('edge_color')\nself._edge_color = _get_hex_color(edge_color) if edge_color is not None else None\nself._edge_alpha = kwargs.get('edge_alpha')\nself._edge_width = kwargs.get('edge_width')\nface_color = kwar... | <|body_start_0|>
self._points = [_format_LatLng(lat, lng, precision) for lat, lng in zip(lats, lngs)]
edge_color = kwargs.get('edge_color')
self._edge_color = _get_hex_color(edge_color) if edge_color is not None else None
self._edge_alpha = kwargs.get('edge_alpha')
self._edge_wid... | _Polygon | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Polygon:
def __init__(self, lats, lngs, precision, **kwargs):
"""Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the polygon's edge. Can be hex ('#... | stack_v2_sparse_classes_36k_train_019395 | 2,418 | permissive | [
{
"docstring": "Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the polygon's edge. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib-like ('c'). edge_alpha (float): Op... | 2 | stack_v2_sparse_classes_30k_val_000405 | Implement the Python class `_Polygon` described below.
Class description:
Implement the _Polygon class.
Method signatures and docstrings:
- def __init__(self, lats, lngs, precision, **kwargs): Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to ... | Implement the Python class `_Polygon` described below.
Class description:
Implement the _Polygon class.
Method signatures and docstrings:
- def __init__(self, lats, lngs, precision, **kwargs): Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to ... | 8654a5a370b5ec309e1282c457eaf375c3dcb4bb | <|skeleton|>
class _Polygon:
def __init__(self, lats, lngs, precision, **kwargs):
"""Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the polygon's edge. Can be hex ('#... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Polygon:
def __init__(self, lats, lngs, precision, **kwargs):
"""Args: lats ([float]): Latitudes. lngs ([float]): Longitudes. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: edge_color (str): Color of the polygon's edge. Can be hex ('#00FFFF'), name... | the_stack_v2_python_sparse | gmplot/drawables/polygon.py | fishke22/gmplot | train | 0 | |
44635dea5130342b4c472cd00307d82ed1808b76 | [
"if isinstance(value, dict):\n value = BytesIO(bytes(value.values()))\nmultipolygon = value\nif multipolygon is not None:\n try:\n zip_file = zipfile.ZipFile(value.temporary_file_path())\n except AttributeError:\n zip_file = zipfile.ZipFile(value)\n try:\n shpfile = get_shapefile(zi... | <|body_start_0|>
if isinstance(value, dict):
value = BytesIO(bytes(value.values()))
multipolygon = value
if multipolygon is not None:
try:
zip_file = zipfile.ZipFile(value.temporary_file_path())
except AttributeError:
zip_file =... | Custom Field for Shapefile | ShapeFileField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeFileField:
"""Custom Field for Shapefile"""
def to_internal_value(self, value):
"""Custom Conversion for shapefile field"""
<|body_0|>
def to_representation(self, value):
"""Custom conversion to representation for ShapeFileField"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_019396 | 6,527 | permissive | [
{
"docstring": "Custom Conversion for shapefile field",
"name": "to_internal_value",
"signature": "def to_internal_value(self, value)"
},
{
"docstring": "Custom conversion to representation for ShapeFileField",
"name": "to_representation",
"signature": "def to_representation(self, value)... | 2 | stack_v2_sparse_classes_30k_train_009702 | Implement the Python class `ShapeFileField` described below.
Class description:
Custom Field for Shapefile
Method signatures and docstrings:
- def to_internal_value(self, value): Custom Conversion for shapefile field
- def to_representation(self, value): Custom conversion to representation for ShapeFileField | Implement the Python class `ShapeFileField` described below.
Class description:
Custom Field for Shapefile
Method signatures and docstrings:
- def to_internal_value(self, value): Custom Conversion for shapefile field
- def to_representation(self, value): Custom conversion to representation for ShapeFileField
<|skele... | 5faff50a2f3575f0df91a6b20afe37d43a592381 | <|skeleton|>
class ShapeFileField:
"""Custom Field for Shapefile"""
def to_internal_value(self, value):
"""Custom Conversion for shapefile field"""
<|body_0|>
def to_representation(self, value):
"""Custom conversion to representation for ShapeFileField"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShapeFileField:
"""Custom Field for Shapefile"""
def to_internal_value(self, value):
"""Custom Conversion for shapefile field"""
if isinstance(value, dict):
value = BytesIO(bytes(value.values()))
multipolygon = value
if multipolygon is not None:
try... | the_stack_v2_python_sparse | tasking/serializers/location.py | onaio/tasking | train | 6 |
a7a0e54a1bf8a0e5b3f369ffedbbd455d4f42209 | [
"if fmt is None:\n fmt = self.DEFAULT_FORMAT\nif datefmt is None:\n datefmt = self.DEFAULT_DATE_FORMAT\nif colors is None:\n colors = self.DEFAULT_COLORS\nlogging.Formatter.__init__(self, datefmt=datefmt)\nself._fmt = fmt\nself._colors = {}\nself._normal = ''\nif color and check_color_support():\n self.... | <|body_start_0|>
if fmt is None:
fmt = self.DEFAULT_FORMAT
if datefmt is None:
datefmt = self.DEFAULT_DATE_FORMAT
if colors is None:
colors = self.DEFAULT_COLORS
logging.Formatter.__init__(self, datefmt=datefmt)
self._fmt = fmt
self._co... | Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems. | BaseFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_36k_train_019397 | 5,254 | permissive | [
{
"docstring": "Parameters ---------- color: Enable color support. bool, default: True fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. str, default: None datefmt... | 2 | stack_v2_sparse_classes_30k_train_004720 | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=None, colors=... | the_stack_v2_python_sparse | mridc/utils/formaters/base.py | wdika/mridc | train | 40 |
8706418d80a22006c4432b5d9cb8e0e556ea38bd | [
"self.learning_rate = learning_rate\nself.mu = mu\nself.rho = rho\nself.k = 0\nself.first_moment = 0\nself.second_moment = 0\nself.epsilon = np.finfo(float).eps",
"self.k += 1\nself.first_moment = self.mu * self.first_moment + (1 - self.mu) * gradient_tensor\nself.second_moment = self.rho * self.second_moment + (... | <|body_start_0|>
self.learning_rate = learning_rate
self.mu = mu
self.rho = rho
self.k = 0
self.first_moment = 0
self.second_moment = 0
self.epsilon = np.finfo(float).eps
<|end_body_0|>
<|body_start_1|>
self.k += 1
self.first_moment = self.mu * se... | Implementation of the "Adaptive Moment Estimation (Adam)"-method. | Adam | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adam:
"""Implementation of the "Adaptive Moment Estimation (Adam)"-method."""
def __init__(self, learning_rate, mu, rho):
"""Constructor for the "Adaptive Moment Estimation (Adam)"-method. :param learning_rate: Learning rate. :param mu: Hyperparameter for the calculation of the first... | stack_v2_sparse_classes_36k_train_019398 | 3,815 | no_license | [
{
"docstring": "Constructor for the \"Adaptive Moment Estimation (Adam)\"-method. :param learning_rate: Learning rate. :param mu: Hyperparameter for the calculation of the first moment (v). :param rho: Hyperparamter for the calculation of the second moment (r).",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_test_000251 | Implement the Python class `Adam` described below.
Class description:
Implementation of the "Adaptive Moment Estimation (Adam)"-method.
Method signatures and docstrings:
- def __init__(self, learning_rate, mu, rho): Constructor for the "Adaptive Moment Estimation (Adam)"-method. :param learning_rate: Learning rate. :... | Implement the Python class `Adam` described below.
Class description:
Implementation of the "Adaptive Moment Estimation (Adam)"-method.
Method signatures and docstrings:
- def __init__(self, learning_rate, mu, rho): Constructor for the "Adaptive Moment Estimation (Adam)"-method. :param learning_rate: Learning rate. :... | 1d2d990c75bb7977d76430a50a31bd9ce31da37d | <|skeleton|>
class Adam:
"""Implementation of the "Adaptive Moment Estimation (Adam)"-method."""
def __init__(self, learning_rate, mu, rho):
"""Constructor for the "Adaptive Moment Estimation (Adam)"-method. :param learning_rate: Learning rate. :param mu: Hyperparameter for the calculation of the first... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adam:
"""Implementation of the "Adaptive Moment Estimation (Adam)"-method."""
def __init__(self, learning_rate, mu, rho):
"""Constructor for the "Adaptive Moment Estimation (Adam)"-method. :param learning_rate: Learning rate. :param mu: Hyperparameter for the calculation of the first moment (v). ... | the_stack_v2_python_sparse | Exercise 2/src_to_implement/Optimization/Optimizers.py | StefanFischer/Deep-Learning-Framework | train | 0 |
3fc75d3637da262df86231214a687d706bb34b51 | [
"try:\n report = next(self.state.database_it)\nexcept (StopIteration, BadInputData, DeserializationFail):\n raise NoReportExtractedException()\ndispatchers = self.state.report_filter.route(report)\nreturn (report, dispatchers)",
"try:\n report, dispatchers = self._get_report_dispatcher()\n self.state.... | <|body_start_0|>
try:
report = next(self.state.database_it)
except (StopIteration, BadInputData, DeserializationFail):
raise NoReportExtractedException()
dispatchers = self.state.report_filter.route(report)
return (report, dispatchers)
<|end_body_0|>
<|body_start... | Puller timeout, read the database. | TimeoutHandler | [
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeoutHandler:
"""Puller timeout, read the database."""
def _get_report_dispatcher(self):
"""read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extracted report and dispatcher to sent this report Raise: NoRep... | stack_v2_sparse_classes_36k_train_019399 | 4,765 | permissive | [
{
"docstring": "read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extracted report and dispatcher to sent this report Raise: NoReportExtractedException : if the database doesn't contains report anymore",
"name": "_get_report_dispatc... | 2 | stack_v2_sparse_classes_30k_train_008552 | Implement the Python class `TimeoutHandler` described below.
Class description:
Puller timeout, read the database.
Method signatures and docstrings:
- def _get_report_dispatcher(self): read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extract... | Implement the Python class `TimeoutHandler` described below.
Class description:
Puller timeout, read the database.
Method signatures and docstrings:
- def _get_report_dispatcher(self): read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extract... | b66e013a830270cecd9a452acc0f12f15fdc4a9b | <|skeleton|>
class TimeoutHandler:
"""Puller timeout, read the database."""
def _get_report_dispatcher(self):
"""read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extracted report and dispatcher to sent this report Raise: NoRep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeoutHandler:
"""Puller timeout, read the database."""
def _get_report_dispatcher(self):
"""read one report of the database and filter it, then return the tuple (report, dispatcher). :return (Report, DispatcherActor): extracted report and dispatcher to sent this report Raise: NoReportExtractedE... | the_stack_v2_python_sparse | powerapi/puller/handlers.py | Kayoku/powerapi | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.