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
39017c91fcb49dc9a62c590010bfd0dd887e318e
[ "super(MarginLoss, self).__init__()\nself.margin = margin\nself.n_classes = n_classes\nself.beta_constant = beta_constant\nself.beta_val = beta\nself.beta = beta if beta_constant else torch.nn.Parameter(torch.ones(n_classes) * beta)\nself.nu = nu\nself.sampling_method = sampling_method\nself.sampler = TupleSampler(...
<|body_start_0|> super(MarginLoss, self).__init__() self.margin = margin self.n_classes = n_classes self.beta_constant = beta_constant self.beta_val = beta self.beta = beta if beta_constant else torch.nn.Parameter(torch.ones(n_classes) * beta) self.nu = nu ...
MarginLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarginLoss: def __init__(self, margin=0.2, nu=0, beta=1.2, n_classes=100, beta_constant=False, sampling_method='distance'): """Basic Margin Loss as proposed in 'Sampling Matters in Deep Embedding Learning'. Args: margin: float, fixed triplet margin (see also TripletLoss). nu: float, regu...
stack_v2_sparse_classes_36k_train_033600
29,027
no_license
[ { "docstring": "Basic Margin Loss as proposed in 'Sampling Matters in Deep Embedding Learning'. Args: margin: float, fixed triplet margin (see also TripletLoss). nu: float, regularisation weight for beta. Zero by default (in literature as well). beta: float, initial value for trainable class margins. Set to def...
2
stack_v2_sparse_classes_30k_train_011879
Implement the Python class `MarginLoss` described below. Class description: Implement the MarginLoss class. Method signatures and docstrings: - def __init__(self, margin=0.2, nu=0, beta=1.2, n_classes=100, beta_constant=False, sampling_method='distance'): Basic Margin Loss as proposed in 'Sampling Matters in Deep Emb...
Implement the Python class `MarginLoss` described below. Class description: Implement the MarginLoss class. Method signatures and docstrings: - def __init__(self, margin=0.2, nu=0, beta=1.2, n_classes=100, beta_constant=False, sampling_method='distance'): Basic Margin Loss as proposed in 'Sampling Matters in Deep Emb...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class MarginLoss: def __init__(self, margin=0.2, nu=0, beta=1.2, n_classes=100, beta_constant=False, sampling_method='distance'): """Basic Margin Loss as proposed in 'Sampling Matters in Deep Embedding Learning'. Args: margin: float, fixed triplet margin (see also TripletLoss). nu: float, regu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MarginLoss: def __init__(self, margin=0.2, nu=0, beta=1.2, n_classes=100, beta_constant=False, sampling_method='distance'): """Basic Margin Loss as proposed in 'Sampling Matters in Deep Embedding Learning'. Args: margin: float, fixed triplet margin (see also TripletLoss). nu: float, regularisation wei...
the_stack_v2_python_sparse
generated/test_Confusezius_Deep_Metric_Learning_Baselines.py
jansel/pytorch-jit-paritybench
train
35
a242aff3f776de3c6d9b4d6887621e4d6daf964f
[ "nums.sort()\nout_lst = []\nfor j in range(len(nums) - 2):\n if j > 0 and nums[j] == nums[j - 1]:\n continue\n c = nums[j]\n target_a_add_b = -c\n out_lst += self.find_two_sum_target(nums[j + 1:], target_a_add_b)\nreturn out_lst", "out_lst_part = []\ni = 0\nj = len(lst) - 1\nwhile True:\n if...
<|body_start_0|> nums.sort() out_lst = [] for j in range(len(nums) - 2): if j > 0 and nums[j] == nums[j - 1]: continue c = nums[j] target_a_add_b = -c out_lst += self.find_two_sum_target(nums[j + 1:], target_a_add_b) return ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def find_two_sum_target(self, lst, target): """把lst中两个元素加起来为target的两个元素找出来,返回 [[a,b, -(a+b)]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> nums.sor...
stack_v2_sparse_classes_36k_train_033601
1,941
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "threeSum", "signature": "def threeSum(self, nums)" }, { "docstring": "把lst中两个元素加起来为target的两个元素找出来,返回 [[a,b, -(a+b)]]", "name": "find_two_sum_target", "signature": "def find_two_sum_target(self, lst, target)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] - def find_two_sum_target(self, lst, target): 把lst中两个元素加起来为target的两个元素找出来,返回 [[a,b, -(a+b)]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] - def find_two_sum_target(self, lst, target): 把lst中两个元素加起来为target的两个元素找出来,返回 [[a,b, -(a+b)]] <|skeleton|>...
f1a3930c571a6d062208ee1c1aadfe93a5684c40
<|skeleton|> class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def find_two_sum_target(self, lst, target): """把lst中两个元素加起来为target的两个元素找出来,返回 [[a,b, -(a+b)]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def threeSum(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" nums.sort() out_lst = [] for j in range(len(nums) - 2): if j > 0 and nums[j] == nums[j - 1]: continue c = nums[j] target_a_add_b = -c ...
the_stack_v2_python_sparse
solution/problem 16.py
Fay321/leetcode-exercise
train
0
40156aeda5db65df5bac7d87240906e4c30c5f1b
[ "super().__init__(num_heads, block, different_layout_per_head)\nself.num_local_blocks = num_local_blocks\nif num_local_blocks % num_global_blocks != 0:\n raise ValueError(f'Number of blocks in a local window, {num_local_blocks}, must be dividable by number of global blocks, {num_global_blocks}!')\nself.num_globa...
<|body_start_0|> super().__init__(num_heads, block, different_layout_per_head) self.num_local_blocks = num_local_blocks if num_local_blocks % num_global_blocks != 0: raise ValueError(f'Number of blocks in a local window, {num_local_blocks}, must be dividable by number of global block...
Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This class extends parent class of `SparsityConfig` and customizes it for `Fixed` sparsity.
FixedSparsityConfig
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FixedSparsityConfig: """Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This class extends parent class of `SparsityConf...
stack_v2_sparse_classes_36k_train_033602
42,463
permissive
[ { "docstring": "Initialize `Fixed` Sparsity Pattern Config. For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial Arguments: num_heads: required: an integer determining number of attention heads of the layer. block: optional: an integer determining the block size. Current implementation of sp...
4
null
Implement the Python class `FixedSparsityConfig` described below. Class description: Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This clas...
Implement the Python class `FixedSparsityConfig` described below. Class description: Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This clas...
55d9964c59c0c6e23158b5789a5c36c28939a7b0
<|skeleton|> class FixedSparsityConfig: """Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This class extends parent class of `SparsityConf...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FixedSparsityConfig: """Configuration class to store `Fixed` sparsity configuration. For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. This class extends parent class of `SparsityConfig` and custo...
the_stack_v2_python_sparse
deepspeed/ops/sparse_attention/sparsity_config.py
microsoft/DeepSpeed
train
27,557
331772b0ebc859af4973ed77bdfe515837eb68bc
[ "if hdu is None:\n binning = '2,2'\n gain = None\n ronoise = None\n datasec = None\n oscansec = None\nelse:\n binning = self.get_meta_value(self.get_headarr(hdu), 'binning')\n gain = np.atleast_1d(hdu[1].header['GAIN'])\n ronoise = np.atleast_1d(hdu[1].header['RDNOISE'])\n datasec = None\...
<|body_start_0|> if hdu is None: binning = '2,2' gain = None ronoise = None datasec = None oscansec = None else: binning = self.get_meta_value(self.get_headarr(hdu), 'binning') gain = np.atleast_1d(hdu[1].header['GAIN'])...
SOARGoodmanBlueSpectrograph
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SOARGoodmanBlueSpectrograph: def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively **required** for SOAR/Goodman-Blue. The ...
stack_v2_sparse_classes_36k_train_033603
24,077
permissive
[ { "docstring": "Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively **required** for SOAR/Goodman-Blue. The optional use of ``hdu`` is only viable for automatically generated documentation. A...
4
null
Implement the Python class `SOARGoodmanBlueSpectrograph` described below. Class description: Implement the SOARGoodmanBlueSpectrograph class. Method signatures and docstrings: - def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters...
Implement the Python class `SOARGoodmanBlueSpectrograph` described below. Class description: Implement the SOARGoodmanBlueSpectrograph class. Method signatures and docstrings: - def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters...
0d2e2196afc6904050b1af4d572f5c643bb07e38
<|skeleton|> class SOARGoodmanBlueSpectrograph: def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively **required** for SOAR/Goodman-Blue. The ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SOARGoodmanBlueSpectrograph: def get_detector_par(self, det, hdu=None): """Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively **required** for SOAR/Goodman-Blue. The optional use o...
the_stack_v2_python_sparse
pypeit/spectrographs/soar_goodman.py
pypeit/PypeIt
train
136
403b4b9ba23ba10354f7848c7a985f2d35c59b54
[ "summaries = []\nselector = '#ae-content tr'\nrows = self.doc.cssselect(selector)\nassert len(rows)\nfor row in rows:\n children = list(row)\n assert len(children) == 5, [child.text for child in children]\n summaries.append({'appengine_release': Value.from_str(text(children[0])), 'total_instances': Value.f...
<|body_start_0|> summaries = [] selector = '#ae-content tr' rows = self.doc.cssselect(selector) assert len(rows) for row in rows: children = list(row) assert len(children) == 5, [child.text for child in children] summaries.append({'appengine_re...
An API for the contents of /instance_summary as structured data.
InstanceSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstanceSummary: """An API for the contents of /instance_summary as structured data.""" def summaries(self): """Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like these, where value is a Value instance whose .text() is shown...
stack_v2_sparse_classes_36k_train_033604
15,505
no_license
[ { "docstring": "Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like these, where value is a Value instance whose .text() is shown as an example: [{'appengine_release': '1.9.2', 'total_instances': '100 total', 'average_qps': '2.243', 'average_latency': '...
2
stack_v2_sparse_classes_30k_train_006796
Implement the Python class `InstanceSummary` described below. Class description: An API for the contents of /instance_summary as structured data. Method signatures and docstrings: - def summaries(self): Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like thes...
Implement the Python class `InstanceSummary` described below. Class description: An API for the contents of /instance_summary as structured data. Method signatures and docstrings: - def summaries(self): Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like thes...
c4ad2ad67b497ce411a9e5d6d6db407ee304491f
<|skeleton|> class InstanceSummary: """An API for the contents of /instance_summary as structured data.""" def summaries(self): """Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like these, where value is a Value instance whose .text() is shown...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstanceSummary: """An API for the contents of /instance_summary as structured data.""" def summaries(self): """Performance statistics summarized by App Engine release. Returns: A list of one or more dicts with fields like these, where value is a Value instance whose .text() is shown as an exampl...
the_stack_v2_python_sparse
src/gae_dashboard/parsers.py
summer-liu/analytics
train
1
1a4fcfbc2af81d0722cb695cfefe25bddde9d8ad
[ "fields = super(HistoricalRecords, self).copy_fields(model)\nfor name, field in self.additional_fields.items():\n assert name not in fields\n assert hasattr(self, 'get_%s_value' % name)\n fields[name] = field\nreturn fields", "extra_fields = super(HistoricalRecords, self).get_extra_fields(model, fields)\...
<|body_start_0|> fields = super(HistoricalRecords, self).copy_fields(model) for name, field in self.additional_fields.items(): assert name not in fields assert hasattr(self, 'get_%s_value' % name) fields[name] = field return fields <|end_body_0|> <|body_start...
simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user
HistoricalRecords
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistoricalRecords: """simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user""" def copy_fields(self, model): """Add additional_fields...
stack_v2_sparse_classes_36k_train_033605
7,986
no_license
[ { "docstring": "Add additional_fields to the historic model.", "name": "copy_fields", "signature": "def copy_fields(self, model)" }, { "docstring": "Remove fields moved to changeset.", "name": "get_extra_fields", "signature": "def get_extra_fields(self, model, fields)" }, { "docs...
4
stack_v2_sparse_classes_30k_train_010446
Implement the Python class `HistoricalRecords` described below. Class description: simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user Method signatures and docstrin...
Implement the Python class `HistoricalRecords` described below. Class description: simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user Method signatures and docstrin...
bc092964153b03381aaff74a4d80f43a2b2dec19
<|skeleton|> class HistoricalRecords: """simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user""" def copy_fields(self, model): """Add additional_fields...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HistoricalRecords: """simple_history.HistoricalRecords with modifications. Changes from simple_history: * Can add additional fields (e.g., preserve relationship order) * References a history_changeset instead of a history_user""" def copy_fields(self, model): """Add additional_fields to the histo...
the_stack_v2_python_sparse
browsercompat/webplatformcompat/history.py
WeilerWebServices/MDN-Web-Docs
train
1
26db360cbafd14ccfdb0466d616245d11efd3415
[ "self.api = api\nself.station = station\nsuper().__init__(hass, _LOGGER, name=name, update_interval=MIN_TIME_BETWEEN_UPDATES)", "try:\n return await self.api.async_get_station_measurements(self.station.uuid)\nexcept CONNECT_ERRORS as err:\n raise UpdateFailed(f'Failed to communicate with API: {err}') from e...
<|body_start_0|> self.api = api self.station = station super().__init__(hass, _LOGGER, name=name, update_interval=MIN_TIME_BETWEEN_UPDATES) <|end_body_0|> <|body_start_1|> try: return await self.api.async_get_station_measurements(self.station.uuid) except CONNECT_ERR...
DataUpdateCoordinator for the pegel_online integration.
PegelOnlineDataUpdateCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PegelOnlineDataUpdateCoordinator: """DataUpdateCoordinator for the pegel_online integration.""" def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: """Initialize the PegelOnlineDataUpdateCoordinator.""" <|body_0|> async def _as...
stack_v2_sparse_classes_36k_train_033606
1,227
permissive
[ { "docstring": "Initialize the PegelOnlineDataUpdateCoordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None" }, { "docstring": "Fetch data from API endpoint.", "name": "_async_update_data", "signature...
2
stack_v2_sparse_classes_30k_train_003843
Implement the Python class `PegelOnlineDataUpdateCoordinator` described below. Class description: DataUpdateCoordinator for the pegel_online integration. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: Initialize the PegelOnlineDataUp...
Implement the Python class `PegelOnlineDataUpdateCoordinator` described below. Class description: DataUpdateCoordinator for the pegel_online integration. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: Initialize the PegelOnlineDataUp...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class PegelOnlineDataUpdateCoordinator: """DataUpdateCoordinator for the pegel_online integration.""" def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: """Initialize the PegelOnlineDataUpdateCoordinator.""" <|body_0|> async def _as...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PegelOnlineDataUpdateCoordinator: """DataUpdateCoordinator for the pegel_online integration.""" def __init__(self, hass: HomeAssistant, name: str, api: PegelOnline, station: Station) -> None: """Initialize the PegelOnlineDataUpdateCoordinator.""" self.api = api self.station = stat...
the_stack_v2_python_sparse
homeassistant/components/pegel_online/coordinator.py
home-assistant/core
train
35,501
e18c788b49dd6a6d784af2a7ddda8e1ae40903f9
[ "super().__init__()\nself.model = model\nself.optimizer = optimizer\nself.loss_module = nn.CrossEntropyLoss()\nself.data_loader = data_loader\nself.data_iter = iter(self.data_loader)", "try:\n batch = next(self.data_iter)\nexcept StopIteration:\n self.data_iter = iter(self.data_loader)\n batch = next(sel...
<|body_start_0|> super().__init__() self.model = model self.optimizer = optimizer self.loss_module = nn.CrossEntropyLoss() self.data_loader = data_loader self.data_iter = iter(self.data_loader) <|end_body_0|> <|body_start_1|> try: batch = next(self.da...
DistributionFitting
[ "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DistributionFitting: def __init__(self, model, optimizer, data_loader): """Creates a DistributionFitting object that summarizes all functionalities for performing the distribution fitting stage of ENCO. Parameters ---------- model : MultivarMLP PyTorch module of the neural networks that ...
stack_v2_sparse_classes_36k_train_033607
3,579
permissive
[ { "docstring": "Creates a DistributionFitting object that summarizes all functionalities for performing the distribution fitting stage of ENCO. Parameters ---------- model : MultivarMLP PyTorch module of the neural networks that model the conditional distributions. optimizer : torch.optim.Optimizer Standard PyT...
5
stack_v2_sparse_classes_30k_train_008684
Implement the Python class `DistributionFitting` described below. Class description: Implement the DistributionFitting class. Method signatures and docstrings: - def __init__(self, model, optimizer, data_loader): Creates a DistributionFitting object that summarizes all functionalities for performing the distribution ...
Implement the Python class `DistributionFitting` described below. Class description: Implement the DistributionFitting class. Method signatures and docstrings: - def __init__(self, model, optimizer, data_loader): Creates a DistributionFitting object that summarizes all functionalities for performing the distribution ...
cffd2793fddc7df4acb31758d71e19f88986dc14
<|skeleton|> class DistributionFitting: def __init__(self, model, optimizer, data_loader): """Creates a DistributionFitting object that summarizes all functionalities for performing the distribution fitting stage of ENCO. Parameters ---------- model : MultivarMLP PyTorch module of the neural networks that ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DistributionFitting: def __init__(self, model, optimizer, data_loader): """Creates a DistributionFitting object that summarizes all functionalities for performing the distribution fitting stage of ENCO. Parameters ---------- model : MultivarMLP PyTorch module of the neural networks that model the cond...
the_stack_v2_python_sparse
causal_discovery/distribution_fitting.py
codeaudit/ENCO
train
0
9a238eecc6a435a2df9e7d85a2e37fc6b7a677d1
[ "self._len = capacity\nself._caches = {}\nself._priority = []", "if key in self._caches.keys():\n self._priority.remove(key)\n self._priority.append(key)\ntry:\n return self._caches[key]\nexcept:\n return -1", "if len(self._caches) < self._len:\n self._caches[key] = value\nelse:\n self._caches...
<|body_start_0|> self._len = capacity self._caches = {} self._priority = [] <|end_body_0|> <|body_start_1|> if key in self._caches.keys(): self._priority.remove(key) self._priority.append(key) try: return self._caches[key] except: ...
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_033608
989
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_007409
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...
a6d0e392134afe19d1aed2dfe7914b674e05ecc6
<|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._len = capacity self._caches = {} self._priority = [] def get(self, key): """:type key: int :rtype: int""" if key in self._caches.keys(): self._priority.remove(key) ...
the_stack_v2_python_sparse
146LRUCache.py
Ting007/leetcodePractice
train
0
1d83103e7ca98b2c2cab1e66dbf098a4dc62c3f0
[ "num_lessons = len(lessons)\nfor index, lesson in enumerate(lessons):\n if index < num_lessons - 1 and lesson.completion_criteria is None:\n raise TrainerConfigError(f'A non-terminal lesson does not have a completion_criteria for {parameter_name}.')\n if index == num_lessons - 1 and lesson.completion_c...
<|body_start_0|> num_lessons = len(lessons) for index, lesson in enumerate(lessons): if index < num_lessons - 1 and lesson.completion_criteria is None: raise TrainerConfigError(f'A non-terminal lesson does not have a completion_criteria for {parameter_name}.') if ...
EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.
EnvironmentParameterSettings
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnvironmentParameterSettings: """EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.""" def _check_lesson_chain(lessons, parameter_name): """Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that th...
stack_v2_sparse_classes_36k_train_033609
33,986
permissive
[ { "docstring": "Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that the terminal lesson does not contain a CompletionCriteria.", "name": "_check_lesson_chain", "signature": "def _check_lesson_chain(lessons, parameter_name)" }, { "docstring": "He...
2
stack_v2_sparse_classes_30k_train_010930
Implement the Python class `EnvironmentParameterSettings` described below. Class description: EnvironmentParameterSettings is an ordered list of lessons for one environment parameter. Method signatures and docstrings: - def _check_lesson_chain(lessons, parameter_name): Ensures that when using curriculum, all non-term...
Implement the Python class `EnvironmentParameterSettings` described below. Class description: EnvironmentParameterSettings is an ordered list of lessons for one environment parameter. Method signatures and docstrings: - def _check_lesson_chain(lessons, parameter_name): Ensures that when using curriculum, all non-term...
768405d0f80d30acb29e1f7c201a98ce67a668b3
<|skeleton|> class EnvironmentParameterSettings: """EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.""" def _check_lesson_chain(lessons, parameter_name): """Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnvironmentParameterSettings: """EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.""" def _check_lesson_chain(lessons, parameter_name): """Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that the terminal le...
the_stack_v2_python_sparse
ml-agents/mlagents/trainers/settings.py
xogur6889/ml-agents
train
2
5ed24ef9d8f73acc807faf6202f76d4d42890b52
[ "self.min_heap = []\nself.max_heap = []\nself.count = 0", "if self.count % 2 == 0:\n heapq.heappush(self.max_heap, -num)\n if self.min_heap and -self.max_heap[0] > self.min_heap[0]:\n to_min = -heapq.heappop(self.max_heap)\n to_max = heapq.heappop(self.min_heap)\n heapq.heappush(self.ma...
<|body_start_0|> self.min_heap = [] self.max_heap = [] self.count = 0 <|end_body_0|> <|body_start_1|> if self.count % 2 == 0: heapq.heappush(self.max_heap, -num) if self.min_heap and -self.max_heap[0] > self.min_heap[0]: to_min = -heapq.heappop(se...
MedianFinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: void""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_033610
1,466
no_license
[ { "docstring": "initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":type num: int :rtype: void", "name": "addNum", "signature": "def addNum(self, num)" }, { "docstring": ":rtype: float", "name": "findMedian", "s...
3
null
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: void - def findMedian(self): :rtype: float
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: void - def findMedian(self): :rtype: float <|skeleton|> class Me...
5c2086fff42dc0641456f7ba4819107617bbcc05
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: void""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MedianFinder: def __init__(self): """initialize your data structure here.""" self.min_heap = [] self.max_heap = [] self.count = 0 def addNum(self, num): """:type num: int :rtype: void""" if self.count % 2 == 0: heapq.heappush(self.max_heap, -num...
the_stack_v2_python_sparse
Numbers/295_FindMedianfromDataStream.py
neelamy/Leetcode
train
0
033a85890e059277f4345ea0ede809a4057f7b05
[ "self.stacks = [[]]\nself.capacity = capacity\nself.active_list = [0]\nself.pop_list = []", "idx = self.active_list[0]\nself.stacks[idx].append(val)\nif idx not in self.pop_list:\n bisect.insort(self.pop_list, idx)\nif len(self.stacks[idx]) == self.capacity:\n self.active_list = self.active_list[1:]\n if...
<|body_start_0|> self.stacks = [[]] self.capacity = capacity self.active_list = [0] self.pop_list = [] <|end_body_0|> <|body_start_1|> idx = self.active_list[0] self.stacks[idx].append(val) if idx not in self.pop_list: bisect.insort(self.pop_list, idx...
DinnerPlates
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def push(self, val): """:type val: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int""" <|body_2|> def popAtStack(self, index): """:t...
stack_v2_sparse_classes_36k_train_033611
6,046
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type val: int :rtype: None", "name": "push", "signature": "def push(self, val)" }, { "docstring": ":rtype: int", "name": "pop", "signature": "def pop(...
4
null
Implement the Python class `DinnerPlates` described below. Class description: Implement the DinnerPlates class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def push(self, val): :type val: int :rtype: None - def pop(self): :rtype: int - def popAtStack(self, index): :type ind...
Implement the Python class `DinnerPlates` described below. Class description: Implement the DinnerPlates class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def push(self, val): :type val: int :rtype: None - def pop(self): :rtype: int - def popAtStack(self, index): :type ind...
a5cb862f0c5a3cfd21468141800568c2dedded0a
<|skeleton|> class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def push(self, val): """:type val: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int""" <|body_2|> def popAtStack(self, index): """:t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" self.stacks = [[]] self.capacity = capacity self.active_list = [0] self.pop_list = [] def push(self, val): """:type val: int :rtype: None""" idx = self.active_list[0] self...
the_stack_v2_python_sparse
python/leetcode/design/1172_dinner_plate_stacks.py
Levintsky/topcoder
train
0
5e01cbb925cdcc5aeec7a01cbc1afadff696d863
[ "jobs = len(job_difficulty)\nif jobs < days:\n return -1\ndp = [[float('inf')] * jobs + [0] for _ in range(days + 1)]\nfor day in range(1, days + 1):\n right = jobs - day + 1\n for cut in range(right):\n max_so_far, ans = (0, float('inf'))\n for job_rate in range(cut, right):\n max...
<|body_start_0|> jobs = len(job_difficulty) if jobs < days: return -1 dp = [[float('inf')] * jobs + [0] for _ in range(days + 1)] for day in range(1, days + 1): right = jobs - day + 1 for cut in range(right): max_so_far, ans = (0, float...
JobSchedule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobSchedule: def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: """Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:""" <|body_0|> def minimum_difficulty_top_down(...
stack_v2_sparse_classes_36k_train_033612
2,851
no_license
[ { "docstring": "Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:", "name": "minimum_difficulty_bottom_up", "signature": "def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int" }, { "docst...
2
null
Implement the Python class `JobSchedule` described below. Class description: Implement the JobSchedule class. Method signatures and docstrings: - def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :par...
Implement the Python class `JobSchedule` described below. Class description: Implement the JobSchedule class. Method signatures and docstrings: - def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :par...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class JobSchedule: def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: """Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:""" <|body_0|> def minimum_difficulty_top_down(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobSchedule: def minimum_difficulty_bottom_up(self, job_difficulty: List[int], days: int) -> int: """Approach: DP Table (bottom up) Time Complexity: O(N^2 * D) Space Complexity: O(ND) :param job_difficulty: :param days: :return:""" jobs = len(job_difficulty) if jobs < days: ...
the_stack_v2_python_sparse
revisited_2021/dp/minimum_difficulty_of_job_schedule.py
Shiv2157k/leet_code
train
1
c9e7e3d5e8f606eb66e7deb9bbb78af1be35a30a
[ "super().__init__()\nself.input_table = input_table\nself.output_gmt = output_gmt\nself.name_col = name_col\nself.group_col = group_col\nself.descriptor = descriptor\nif self.input_table.endswith('.csv'):\n self.table = rc.ReadCsv(self.input_table, use_cols=[self.name_col, self.group_col]).get_data()\nelif self....
<|body_start_0|> super().__init__() self.input_table = input_table self.output_gmt = output_gmt self.name_col = name_col self.group_col = group_col self.descriptor = descriptor if self.input_table.endswith('.csv'): self.table = rc.ReadCsv(self.input_ta...
This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs
GroupGmt
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupGmt: """This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs""" def __init__(self, input_table, outpu...
stack_v2_sparse_classes_36k_train_033613
13,420
permissive
[ { "docstring": ":param input_table: str, the filename path :param output_gmt: str, the output gmt file path :param name_col: str, the name of the column to write the genes :param group_col: str, the name of the column to group :param descriptor: str, the descriptor to use", "name": "__init__", "signatur...
2
stack_v2_sparse_classes_30k_train_017814
Implement the Python class `GroupGmt` described below. Class description: This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs Metho...
Implement the Python class `GroupGmt` described below. Class description: This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs Metho...
62307f90af4c72c50aca4cbf8c61e924e69467be
<|skeleton|> class GroupGmt: """This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs""" def __init__(self, input_table, outpu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupGmt: """This function generates a gmt file of multiple setnames. From the table file, it groups the names in the group_col (the column you want to use to group them) and prints the genes in the name_col. Set the descriptor according to your needs""" def __init__(self, input_table, output_gmt, name_c...
the_stack_v2_python_sparse
pygna/converters.py
science4fun/pygna
train
0
f0bdc18bbdc65c9e968d24215b8e50bef2352cc7
[ "super(Conv2dSubsampling6, self).__init__()\nself.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 5, 3), torch.nn.ReLU())\nself.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim), pos_enc if pos_enc is not None else Positional...
<|body_start_0|> super(Conv2dSubsampling6, self).__init__() self.conv = torch.nn.Sequential(torch.nn.Conv2d(1, odim, 3, 2), torch.nn.ReLU(), torch.nn.Conv2d(odim, odim, 5, 3), torch.nn.ReLU()) self.out = torch.nn.Sequential(torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim), pos_enc if p...
Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.
Conv2dSubsampling6
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Conv2dSubsampling6: """Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc=None): ...
stack_v2_sparse_classes_36k_train_033614
14,351
permissive
[ { "docstring": "Construct an Conv2dSubsampling6 object.", "name": "__init__", "signature": "def __init__(self, idim, odim, dropout_rate, pos_enc=None)" }, { "docstring": "Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). ...
2
null
Implement the Python class `Conv2dSubsampling6` described below. Class description: Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer. Method signatures and docstr...
Implement the Python class `Conv2dSubsampling6` described below. Class description: Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer. Method signatures and docstr...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class Conv2dSubsampling6: """Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Conv2dSubsampling6: """Convolutional 2D subsampling (to 1/6 length). Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (torch.nn.Module): Custom position encoding layer.""" def __init__(self, idim, odim, dropout_rate, pos_enc=None): """Co...
the_stack_v2_python_sparse
espnet/nets/pytorch_backend/transformer/subsampling.py
espnet/espnet
train
7,242
ae0a61107fd9475b4573f074a62a37b22765108a
[ "self.definition_body = definition_body\nself.definition_uri = definition_uri\nself.working_dir = working_dir\nif not self.definition_body and (not self.definition_uri):\n raise ValueError('Require value for either DefinitionBody or DefinitionUri')", "swagger = None\nif self.definition_body:\n swagger = sel...
<|body_start_0|> self.definition_body = definition_body self.definition_uri = definition_uri self.working_dir = working_dir if not self.definition_body and (not self.definition_uri): raise ValueError('Require value for either DefinitionBody or DefinitionUri') <|end_body_0|> ...
Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource
SwaggerReader
[ "Apache-2.0", "BSD-3-Clause", "MIT", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SwaggerReader: """Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource""" def __init__(self, definition_body=None, definition_uri=None, working_dir=None): """Initialize the class with...
stack_v2_sparse_classes_36k_train_033615
9,397
permissive
[ { "docstring": "Initialize the class with swagger location Parameters ---------- definition_body : dict Swagger document as a dictionary directly or inlined using AWS::Include transform. definition_uri : str or dict Location of the Swagger file. Supports three formats: - S3 URI Ex: ``s3://mybucket/swagger.yaml`...
6
null
Implement the Python class `SwaggerReader` described below. Class description: Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource Method signatures and docstrings: - def __init__(self, definition_body=None, definiti...
Implement the Python class `SwaggerReader` described below. Class description: Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource Method signatures and docstrings: - def __init__(self, definition_body=None, definiti...
b297ff015f2b69d7c74059c2d42ece1c29ea73ee
<|skeleton|> class SwaggerReader: """Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource""" def __init__(self, definition_body=None, definition_uri=None, working_dir=None): """Initialize the class with...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SwaggerReader: """Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as available in Serverless::Api SAM resource""" def __init__(self, definition_body=None, definition_uri=None, working_dir=None): """Initialize the class with swagger loca...
the_stack_v2_python_sparse
samcli/commands/local/lib/swagger/reader.py
aws/aws-sam-cli
train
1,402
1536532db132ea2cee453822a29297f2e6f5b670
[ "from collections import defaultdict\nself.sums = defaultdict(int)\nsums = 0\nfor i, num in enumerate(nums):\n sums += num\n self.sums[i] = sums", "if i > j:\n return 0\nreturn self.sums[j] - self.sums[i - 1]" ]
<|body_start_0|> from collections import defaultdict self.sums = defaultdict(int) sums = 0 for i, num in enumerate(nums): sums += num self.sums[i] = sums <|end_body_0|> <|body_start_1|> if i > j: return 0 return self.sums[j] - self.sum...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_033616
889
no_license
[ { "docstring": "initialize your data structure here. :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, ...
2
null
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): initialize your data structure here. :type nums: List[int] - def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ...
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): initialize your data structure here. :type nums: List[int] - def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ...
7bdb0ddd042fab4c7f615cd8630de78275c175d9
<|skeleton|> class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" from collections import defaultdict self.sums = defaultdict(int) sums = 0 for i, num in enumerate(nums): sums += num self.sums[i] = sums def...
the_stack_v2_python_sparse
leetcode/303-Range_Sum_Query_Immutable.py
JFluo2011/leetcode
train
0
35ab15fdf5f7209529c8e1d25cdc1d813a5a5c01
[ "username = self.cleaned_data.get('username', self.data['username'])\nif not username or not User.objects.filter(username=username).exists():\n raise forms.ValidationError('No user with that username was found in our system.')\nreturn username", "cleaned_data = super(LocalSuperAuthUserCreationForm, self).clean...
<|body_start_0|> username = self.cleaned_data.get('username', self.data['username']) if not username or not User.objects.filter(username=username).exists(): raise forms.ValidationError('No user with that username was found in our system.') return username <|end_body_0|> <|body_start...
Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to log in to. That page is where the AuthenticatedSession object will be created after they select the...
LocalSuperAuthUserCreationForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LocalSuperAuthUserCreationForm: """Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to log in to. That page is where the Authent...
stack_v2_sparse_classes_36k_train_033617
5,352
no_license
[ { "docstring": "Cleans the username and makes sure that it is a valid username that matches an existing user.", "name": "clean_username", "signature": "def clean_username(self)" }, { "docstring": "Override of the base classes clean method. Override: This override authenticates the username and p...
3
stack_v2_sparse_classes_30k_train_007460
Implement the Python class `LocalSuperAuthUserCreationForm` described below. Class description: Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to lo...
Implement the Python class `LocalSuperAuthUserCreationForm` described below. Class description: Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to lo...
cbf36b09cbfb8b97eb02f2d0b2ffcdca8d3280c2
<|skeleton|> class LocalSuperAuthUserCreationForm: """Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to log in to. That page is where the Authent...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LocalSuperAuthUserCreationForm: """Form to log a user in to a client. This does not create the login session. It just validates the user. After they are validated by this, the user will have to be redirected to a page to select their app that they want to log in to. That page is where the AuthenticatedSession...
the_stack_v2_python_sparse
Servers/client_server/core/forms.py
cps410/FingerPrintVerification
train
0
6c3761492949c5e01b9ffc33892575fdc908336f
[ "if SeedForumsTasks._large_thread is None:\n return\ndiscussion_id, thread_id = SeedForumsTasks._large_thread\nresponse_id = super(SeedForumsTasks, self).create_response(thread_id)\nif not SeedForumsTasks._large_thread_response_ids or random.randint(1, len(SeedForumsTasks._large_thread_response_ids)) <= 1:\n ...
<|body_start_0|> if SeedForumsTasks._large_thread is None: return discussion_id, thread_id = SeedForumsTasks._large_thread response_id = super(SeedForumsTasks, self).create_response(thread_id) if not SeedForumsTasks._large_thread_response_ids or random.randint(1, len(SeedForu...
Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed. * LARGE_THREAD_ID: Thread id for the larg...
SeedForumsTasks
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeedForumsTasks: """Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed...
stack_v2_sparse_classes_36k_train_033618
14,154
permissive
[ { "docstring": "Post a response to an existing thread.", "name": "create_response", "signature": "def create_response(self)" }, { "docstring": "Post a response to an existing thread.", "name": "create_comment", "signature": "def create_comment(self)" }, { "docstring": "This on_st...
3
stack_v2_sparse_classes_30k_train_011984
Implement the Python class `SeedForumsTasks` described below. Class description: Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be c...
Implement the Python class `SeedForumsTasks` described below. Class description: Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be c...
1a6dc891d2fb72575f354521988a531489f30032
<|skeleton|> class SeedForumsTasks: """Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeedForumsTasks: """Seed large thread for Forums (LMS) TaskSet. This class supports environment-based configuration to override default values for the following: * LARGE_TOPIC_ID: Topic id for the large thread to be extended. If blank, a new thread will be created and the topic id will be printed. * LARGE_THR...
the_stack_v2_python_sparse
loadtests/lms/forums.py
kavithachandra/edx-load-tests
train
0
7f889974320321eef23830119ebf3bfde0256ec3
[ "if parent and parent.is_audio_clip and parent.warping:\n self.set_range((0, len(parent.available_warp_modes) - 1))\n super(WarpProperty, self).set_parent(parent)\nelse:\n super(WarpProperty, self).set_parent(None)\nreturn", "if self._parent.warping and current_value != new_value:\n modes = list(self....
<|body_start_0|> if parent and parent.is_audio_clip and parent.warping: self.set_range((0, len(parent.available_warp_modes) - 1)) super(WarpProperty, self).set_parent(parent) else: super(WarpProperty, self).set_parent(None) return <|end_body_0|> <|body_start_...
WarpProperty specializes PropertyControl to control a clip's warp mode.
WarpProperty
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WarpProperty: """WarpProperty specializes PropertyControl to control a clip's warp mode.""" def set_parent(self, parent): """Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes.""" <|body_0|> def set...
stack_v2_sparse_classes_36k_train_033619
13,552
no_license
[ { "docstring": "Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes.", "name": "set_parent", "signature": "def set_parent(self, parent)" }, { "docstring": "Overrides standard to set the warp mode based on the available warp ...
4
stack_v2_sparse_classes_30k_val_000771
Implement the Python class `WarpProperty` described below. Class description: WarpProperty specializes PropertyControl to control a clip's warp mode. Method signatures and docstrings: - def set_parent(self, parent): Extends standard to only set parent if it's an audio clip and to set the property's range based on the...
Implement the Python class `WarpProperty` described below. Class description: WarpProperty specializes PropertyControl to control a clip's warp mode. Method signatures and docstrings: - def set_parent(self, parent): Extends standard to only set parent if it's an audio clip and to set the property's range based on the...
e3ec6846470eed7da8a4d4f78562ed49dc00727b
<|skeleton|> class WarpProperty: """WarpProperty specializes PropertyControl to control a clip's warp mode.""" def set_parent(self, parent): """Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes.""" <|body_0|> def set...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WarpProperty: """WarpProperty specializes PropertyControl to control a clip's warp mode.""" def set_parent(self, parent): """Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes.""" if parent and parent.is_audio_clip a...
the_stack_v2_python_sparse
Live 10.1.18/_NKFW2/ClipPropertiesComponent.py
notelba/midi-remote-scripts
train
0
7c34d220af52dd3a8698eb1068b03c95808eef40
[ "scope_specs_map = self.hubclient.ToPyDefaultDict(self.messages.ScopeFeatureSpec, feature.scopeSpecs)\ncluster_upgrade_spec = scope_specs_map[scope_name].clusterupgrade or self.messages.ClusterUpgradeScopeSpec()\nself.HandleUpstreamScopes(cluster_upgrade_spec)\nself.HandleDefaultSoakTime(cluster_upgrade_spec)\nself...
<|body_start_0|> scope_specs_map = self.hubclient.ToPyDefaultDict(self.messages.ScopeFeatureSpec, feature.scopeSpecs) cluster_upgrade_spec = scope_specs_map[scope_name].clusterupgrade or self.messages.ClusterUpgradeScopeSpec() self.HandleUpstreamScopes(cluster_upgrade_spec) self.HandleDe...
Base class for updating the Cluster Upgrade Feature.
UpdateCommand
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateCommand: """Base class for updating the Cluster Upgrade Feature.""" def Update(self, feature, scope_name): """Updates Cluster Upgrade Feature information.""" <|body_0|> def HandleUpstreamScopes(self, cluster_upgrade_spec): """Updates the Cluster Upgrade Fea...
stack_v2_sparse_classes_36k_train_033620
13,475
permissive
[ { "docstring": "Updates Cluster Upgrade Feature information.", "name": "Update", "signature": "def Update(self, feature, scope_name)" }, { "docstring": "Updates the Cluster Upgrade Feature's upstreamScopes field based on provided arguments.", "name": "HandleUpstreamScopes", "signature": ...
4
null
Implement the Python class `UpdateCommand` described below. Class description: Base class for updating the Cluster Upgrade Feature. Method signatures and docstrings: - def Update(self, feature, scope_name): Updates Cluster Upgrade Feature information. - def HandleUpstreamScopes(self, cluster_upgrade_spec): Updates th...
Implement the Python class `UpdateCommand` described below. Class description: Base class for updating the Cluster Upgrade Feature. Method signatures and docstrings: - def Update(self, feature, scope_name): Updates Cluster Upgrade Feature information. - def HandleUpstreamScopes(self, cluster_upgrade_spec): Updates th...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class UpdateCommand: """Base class for updating the Cluster Upgrade Feature.""" def Update(self, feature, scope_name): """Updates Cluster Upgrade Feature information.""" <|body_0|> def HandleUpstreamScopes(self, cluster_upgrade_spec): """Updates the Cluster Upgrade Fea...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateCommand: """Base class for updating the Cluster Upgrade Feature.""" def Update(self, feature, scope_name): """Updates Cluster Upgrade Feature information.""" scope_specs_map = self.hubclient.ToPyDefaultDict(self.messages.ScopeFeatureSpec, feature.scopeSpecs) cluster_upgrade_...
the_stack_v2_python_sparse
lib/googlecloudsdk/command_lib/container/fleet/scopes/rollout_sequencing/base.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
731e2a1ec51dd25ff6b080b779eb0578ce1f8ad9
[ "hour = 0\nfor count in piles:\n hour += count / k\n if count % k != 0:\n hour += 1\nreturn hour", "if not piles:\n return 0\nleft = 1\nright = max(piles)\nwhile left + 1 < right:\n middle = (left + right) / 2\n hour = self.calHour(middle, piles)\n if hour == H:\n right = middle\n ...
<|body_start_0|> hour = 0 for count in piles: hour += count / k if count % k != 0: hour += 1 return hour <|end_body_0|> <|body_start_1|> if not piles: return 0 left = 1 right = max(piles) while left + 1 < right:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" <|body_0|> def minEatingSpeed(self, piles, H): """:type piles: List[int] :type H: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_033621
1,004
no_license
[ { "docstring": "calculate how many hours koko takes eating up all piles of bananas", "name": "calHour", "signature": "def calHour(self, k, piles)" }, { "docstring": ":type piles: List[int] :type H: int :rtype: int", "name": "minEatingSpeed", "signature": "def minEatingSpeed(self, piles, ...
2
stack_v2_sparse_classes_30k_train_006091
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calHour(self, k, piles): calculate how many hours koko takes eating up all piles of bananas - def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calHour(self, k, piles): calculate how many hours koko takes eating up all piles of bananas - def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: ...
1d8821da01c9c200732a6b7037b8631689e2f7e7
<|skeleton|> class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" <|body_0|> def minEatingSpeed(self, piles, H): """:type piles: List[int] :type H: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" hour = 0 for count in piles: hour += count / k if count % k != 0: hour += 1 return hour def minEatingSpeed(self, piles, H...
the_stack_v2_python_sparse
Leetcode0875_BinarySearch.py
xiaojinghu/Leetcode
train
0
c2ce97ab822b5f9eb23902211ca40ce393b28ea9
[ "post_data = dict(self.request.POST.lists())\npregunta = Pregunta.objects.get(id=int(self.kwargs['pk']))\nself.object = form.save(commit=False)\nself.object.texto_opcion = post_data['texto_opcion'][0]\nself.object.pregunta = pregunta\nself.object.save()\nfor i in range(1, len(post_data['texto_opcion'])):\n opcio...
<|body_start_0|> post_data = dict(self.request.POST.lists()) pregunta = Pregunta.objects.get(id=int(self.kwargs['pk'])) self.object = form.save(commit=False) self.object.texto_opcion = post_data['texto_opcion'][0] self.object.pregunta = pregunta self.object.save() ...
! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0
OpcionesCreate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpcionesCreate: """! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0""" def form_valid(self, form): ""...
stack_v2_sparse_classes_36k_train_033622
22,004
no_license
[ { "docstring": "! Metodo que valida si el formulario es valido @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright GNU/GPLv2 @date 20-02-2017 @param self <b>{object}</b> Objeto que instancia la clase @param form <b>{object}</b> Objeto que contiene el formulario de registro @return Retorna el formulario v...
2
stack_v2_sparse_classes_30k_train_017583
Implement the Python class `OpcionesCreate` described below. Class description: ! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0 Method...
Implement the Python class `OpcionesCreate` described below. Class description: ! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0 Method...
93cefc3c94c62e66b103510a2f668a419e5c5cae
<|skeleton|> class OpcionesCreate: """! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0""" def form_valid(self, form): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpcionesCreate: """! Clase que gestiona la creación de opciones @author Rodrigo Boet (rboet at cenditel.gob.ve) @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> @date 20-02-2017 @version 1.0.0""" def form_valid(self, form): """! Metodo que...
the_stack_v2_python_sparse
consulta/views.py
rudmanmrrod/gestor_consulta
train
1
7bdfcbd1d5ec3e5f636840ef70d58e80b5bafe15
[ "try:\n return self.select_related('user').get(openid=openid)\nexcept OauthQQ.DoesNotExist:\n return None", "try:\n user = self.get(openid=open_id)\n return None\nexcept OauthQQ.DoesNotExist:\n return self.create(user=user, openid=open_id)" ]
<|body_start_0|> try: return self.select_related('user').get(openid=openid) except OauthQQ.DoesNotExist: return None <|end_body_0|> <|body_start_1|> try: user = self.get(openid=open_id) return None except OauthQQ.DoesNotExist: ...
QQ登录模型管理类
QqManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QqManager: """QQ登录模型管理类""" def existed_user(self, openid): """判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None""" <|body_0|> def create_qq_user(self, user, open_id): """用户第一次使用QQ登录,绑定创建对象 :return: qq_user""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_033623
1,918
permissive
[ { "docstring": "判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None", "name": "existed_user", "signature": "def existed_user(self, openid)" }, { "docstring": "用户第一次使用QQ登录,绑定创建对象 :return: qq_user", "name": "create_qq_user", "signature": "def create_qq_user(self, user, open_id)" } ...
2
null
Implement the Python class `QqManager` described below. Class description: QQ登录模型管理类 Method signatures and docstrings: - def existed_user(self, openid): 判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None - def create_qq_user(self, user, open_id): 用户第一次使用QQ登录,绑定创建对象 :return: qq_user
Implement the Python class `QqManager` described below. Class description: QQ登录模型管理类 Method signatures and docstrings: - def existed_user(self, openid): 判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None - def create_qq_user(self, user, open_id): 用户第一次使用QQ登录,绑定创建对象 :return: qq_user <|skeleton|> class QqManage...
13cb59130d15e782f78bc5148409bef0f1c516e0
<|skeleton|> class QqManager: """QQ登录模型管理类""" def existed_user(self, openid): """判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None""" <|body_0|> def create_qq_user(self, user, open_id): """用户第一次使用QQ登录,绑定创建对象 :return: qq_user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QqManager: """QQ登录模型管理类""" def existed_user(self, openid): """判断用户是否存在 :param openid: openid用户唯一标识 :return:用户对象 or None""" try: return self.select_related('user').get(openid=openid) except OauthQQ.DoesNotExist: return None def create_qq_user(self, user...
the_stack_v2_python_sparse
oauth_app/models.py
lmyfzx/Django-Mall
train
0
e630b92501fa860ec161e7f1ffec1b2a22ecbdfa
[ "runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt')\nif os.path.exists(runScriptPath):\n with open(runScriptPath, 'r') as runScriptIter:\n for script in runScriptIter.readlines():\n script = script.strip()\n if script.startswith('script') and script.endswith('.py'):...
<|body_start_0|> runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt') if os.path.exists(runScriptPath): with open(runScriptPath, 'r') as runScriptIter: for script in runScriptIter.readlines(): script = script.strip() if ...
CaseConfig
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CaseConfig: def getScriptFromProjectSetting(): """@summary:从project.txt中获取配置的脚本""" <|body_0|> def parseScriptConfig(scriptModule): """@summary:解析脚本配置文件 @param scriptModule:要解析的脚本""" <|body_1|> <|end_skeleton|> <|body_start_0|> runScriptPath = os.pat...
stack_v2_sparse_classes_36k_train_033624
3,578
no_license
[ { "docstring": "@summary:从project.txt中获取配置的脚本", "name": "getScriptFromProjectSetting", "signature": "def getScriptFromProjectSetting()" }, { "docstring": "@summary:解析脚本配置文件 @param scriptModule:要解析的脚本", "name": "parseScriptConfig", "signature": "def parseScriptConfig(scriptModule)" } ]
2
stack_v2_sparse_classes_30k_test_000536
Implement the Python class `CaseConfig` described below. Class description: Implement the CaseConfig class. Method signatures and docstrings: - def getScriptFromProjectSetting(): @summary:从project.txt中获取配置的脚本 - def parseScriptConfig(scriptModule): @summary:解析脚本配置文件 @param scriptModule:要解析的脚本
Implement the Python class `CaseConfig` described below. Class description: Implement the CaseConfig class. Method signatures and docstrings: - def getScriptFromProjectSetting(): @summary:从project.txt中获取配置的脚本 - def parseScriptConfig(scriptModule): @summary:解析脚本配置文件 @param scriptModule:要解析的脚本 <|skeleton|> class CaseC...
8935e20a426638462cd1cc7bc048a16751287a2f
<|skeleton|> class CaseConfig: def getScriptFromProjectSetting(): """@summary:从project.txt中获取配置的脚本""" <|body_0|> def parseScriptConfig(scriptModule): """@summary:解析脚本配置文件 @param scriptModule:要解析的脚本""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CaseConfig: def getScriptFromProjectSetting(): """@summary:从project.txt中获取配置的脚本""" runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt') if os.path.exists(runScriptPath): with open(runScriptPath, 'r') as runScriptIter: for script in runScriptI...
the_stack_v2_python_sparse
autotest/core/conf/CaseConfig.py
wanghaoplus/gatog
train
0
3bc51fd4e9886015bddf3648900f7dfb567a5d2c
[ "result = empty_result()\ntry:\n result['data'] = {'interface_status': get_interface_states(hostname)}\nexcept ValueError as e:\n return (empty_result('error', 'Could not get interface states, invalid input: {}'.format(e)), 400)\nexcept Exception as e:\n return (empty_result('error', 'Could not get interfa...
<|body_start_0|> result = empty_result() try: result['data'] = {'interface_status': get_interface_states(hostname)} except ValueError as e: return (empty_result('error', 'Could not get interface states, invalid input: {}'.format(e)), 400) except Exception as e: ...
InterfaceStatusApi
[ "BSD-2-Clause-Views", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InterfaceStatusApi: def get(self, hostname): """List all interfaces status""" <|body_0|> def put(self, hostname): """Bounce selected interfaces by appling bounce-down/bounce-up template""" <|body_1|> <|end_skeleton|> <|body_start_0|> result = empty_...
stack_v2_sparse_classes_36k_train_033625
15,267
permissive
[ { "docstring": "List all interfaces status", "name": "get", "signature": "def get(self, hostname)" }, { "docstring": "Bounce selected interfaces by appling bounce-down/bounce-up template", "name": "put", "signature": "def put(self, hostname)" } ]
2
stack_v2_sparse_classes_30k_train_021539
Implement the Python class `InterfaceStatusApi` described below. Class description: Implement the InterfaceStatusApi class. Method signatures and docstrings: - def get(self, hostname): List all interfaces status - def put(self, hostname): Bounce selected interfaces by appling bounce-down/bounce-up template
Implement the Python class `InterfaceStatusApi` described below. Class description: Implement the InterfaceStatusApi class. Method signatures and docstrings: - def get(self, hostname): List all interfaces status - def put(self, hostname): Bounce selected interfaces by appling bounce-down/bounce-up template <|skeleto...
d755dfed69bebe0c7bea66ad1802cba2cd89fec8
<|skeleton|> class InterfaceStatusApi: def get(self, hostname): """List all interfaces status""" <|body_0|> def put(self, hostname): """Bounce selected interfaces by appling bounce-down/bounce-up template""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InterfaceStatusApi: def get(self, hostname): """List all interfaces status""" result = empty_result() try: result['data'] = {'interface_status': get_interface_states(hostname)} except ValueError as e: return (empty_result('error', 'Could not get interfac...
the_stack_v2_python_sparse
src/cnaas_nms/api/interface.py
SUNET/cnaas-nms
train
67
7c4a3f29fb25565247f92b3778b63daf99998c98
[ "self.map = mMap\nself.position = position\nself.speed = 1\nself.walkCycle = 0\nself.destination = self.position\nself.direction = DIR_UP\nself.stepQueue = []\nself.busy = False", "if self.direction == DIR_UP:\n return (0, -1 * self.walkCycle * globs.TILESIZE[1] / 8)\nelif self.direction == DIR_DOWN:\n retu...
<|body_start_0|> self.map = mMap self.position = position self.speed = 1 self.walkCycle = 0 self.destination = self.position self.direction = DIR_UP self.stepQueue = [] self.busy = False <|end_body_0|> <|body_start_1|> if self.direction == DIR_UP:...
Dummy sprite class allowing dynamic camera movement.
DummySprite
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DummySprite: """Dummy sprite class allowing dynamic camera movement.""" def __init__(self, mMap, position): """Set up the dummy. mMap - the map the dummy is on. position - the initial position.""" <|body_0|> def getMoveOffset(self): """Calculate the offset due to...
stack_v2_sparse_classes_36k_train_033626
17,845
no_license
[ { "docstring": "Set up the dummy. mMap - the map the dummy is on. position - the initial position.", "name": "__init__", "signature": "def __init__(self, mMap, position)" }, { "docstring": "Calculate the offset due to movement of the dummy.", "name": "getMoveOffset", "signature": "def ge...
4
null
Implement the Python class `DummySprite` described below. Class description: Dummy sprite class allowing dynamic camera movement. Method signatures and docstrings: - def __init__(self, mMap, position): Set up the dummy. mMap - the map the dummy is on. position - the initial position. - def getMoveOffset(self): Calcul...
Implement the Python class `DummySprite` described below. Class description: Dummy sprite class allowing dynamic camera movement. Method signatures and docstrings: - def __init__(self, mMap, position): Set up the dummy. mMap - the map the dummy is on. position - the initial position. - def getMoveOffset(self): Calcul...
72841fc503c716ac3b524e42f2311cbd9d18a092
<|skeleton|> class DummySprite: """Dummy sprite class allowing dynamic camera movement.""" def __init__(self, mMap, position): """Set up the dummy. mMap - the map the dummy is on. position - the initial position.""" <|body_0|> def getMoveOffset(self): """Calculate the offset due to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DummySprite: """Dummy sprite class allowing dynamic camera movement.""" def __init__(self, mMap, position): """Set up the dummy. mMap - the map the dummy is on. position - the initial position.""" self.map = mMap self.position = position self.speed = 1 self.walkCyc...
the_stack_v2_python_sparse
eng/camera.py
andrew-turner/Ditto
train
0
690e87179e082128c986dd24fe1642113d37d163
[ "corpus1 = []\nfor sentence in tokenized_corpus1:\n corpus1.append(' '.join(sentence))\ncorpus2 = []\nfor sentence in tokenized_corpus2:\n corpus2.append(' '.join(sentence))\nself._tfidf_vectorizer1 = TfidfVectorizer(min_df=min_occurences, ngram_range=ngram_range, max_features=max_features)\nself._tfidf_vecto...
<|body_start_0|> corpus1 = [] for sentence in tokenized_corpus1: corpus1.append(' '.join(sentence)) corpus2 = [] for sentence in tokenized_corpus2: corpus2.append(' '.join(sentence)) self._tfidf_vectorizer1 = TfidfVectorizer(min_df=min_occurences, ngram_ra...
Tfidf
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tfidf: def __init__(self, tokenized_corpus1, tokenized_corpus2, min_occurences=1, ngram_range=(1, 1), max_features=None): """:param tokenized_corpus1: first corpus to be vectorized. We are going to use this corpus to fit our TF-IDF model. :param tokenized_corpus2: second corpus to be vec...
stack_v2_sparse_classes_36k_train_033627
2,930
no_license
[ { "docstring": ":param tokenized_corpus1: first corpus to be vectorized. We are going to use this corpus to fit our TF-IDF model. :param tokenized_corpus2: second corpus to be vectorized. We are going to use this corpus to fit our TF-IDF model. :param min_occurences: the minimum number of occurences a word must...
2
stack_v2_sparse_classes_30k_train_009069
Implement the Python class `Tfidf` described below. Class description: Implement the Tfidf class. Method signatures and docstrings: - def __init__(self, tokenized_corpus1, tokenized_corpus2, min_occurences=1, ngram_range=(1, 1), max_features=None): :param tokenized_corpus1: first corpus to be vectorized. We are going...
Implement the Python class `Tfidf` described below. Class description: Implement the Tfidf class. Method signatures and docstrings: - def __init__(self, tokenized_corpus1, tokenized_corpus2, min_occurences=1, ngram_range=(1, 1), max_features=None): :param tokenized_corpus1: first corpus to be vectorized. We are going...
0c2b3cc4c999cab93d58afcf62b50afdb854fb41
<|skeleton|> class Tfidf: def __init__(self, tokenized_corpus1, tokenized_corpus2, min_occurences=1, ngram_range=(1, 1), max_features=None): """:param tokenized_corpus1: first corpus to be vectorized. We are going to use this corpus to fit our TF-IDF model. :param tokenized_corpus2: second corpus to be vec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tfidf: def __init__(self, tokenized_corpus1, tokenized_corpus2, min_occurences=1, ngram_range=(1, 1), max_features=None): """:param tokenized_corpus1: first corpus to be vectorized. We are going to use this corpus to fit our TF-IDF model. :param tokenized_corpus2: second corpus to be vectorized. We ar...
the_stack_v2_python_sparse
src/TfIdfWrapper.py
PierreElm/NLP-QualityMT
train
0
8fb8a228c08dc5a74701271bd6db5937c47f0de2
[ "use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'\nCHUNK_SIZE = 64 * kilobyte\nif not use_openssl_only:\n m = SHA256.new()\nelse:\n backend = default_backend()\n chosen_hash = hashes.SHA256()\n hasher = hashes.Hash(chosen_hash, backend)\nwhile True:\n chunk = src.read(CHUNK_SIZE...
<|body_start_0|> use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True' CHUNK_SIZE = 64 * kilobyte if not use_openssl_only: m = SHA256.new() else: backend = default_backend() chosen_hash = hashes.SHA256() hasher = hashes.Has...
SnowflakeFileUtil
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" <|body_0|> def compress_with_gzip_from_stream(src_stream: IO[bytes]) -> tupl...
stack_v2_sparse_classes_36k_train_033628
5,427
permissive
[ { "docstring": "Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.", "name": "get_digest_and_size", "signature": "def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]" }, { "docstring": "Compresses a stream of bytes with GZIP. ...
6
null
Implement the Python class `SnowflakeFileUtil` described below. Class description: Implement the SnowflakeFileUtil class. Method signatures and docstrings: - def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's s...
Implement the Python class `SnowflakeFileUtil` described below. Class description: Implement the SnowflakeFileUtil class. Method signatures and docstrings: - def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's s...
da1ae4ed1e940e4210348c59c9c660ebaa78fc2e
<|skeleton|> class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" <|body_0|> def compress_with_gzip_from_stream(src_stream: IO[bytes]) -> tupl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnowflakeFileUtil: def get_digest_and_size(src: IO[bytes]) -> tuple[str, int]: """Gets stream digest and size. Args: src: The input stream. Returns: Tuple of src's digest and src's size in bytes.""" use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True' CHUNK_SIZE = 64 ...
the_stack_v2_python_sparse
src/snowflake/connector/file_util.py
snowflakedb/snowflake-connector-python
train
492
73a08a944039b4fc8c0b18c7f70d89221dee9841
[ "_id = request.args.get('id', None)\nif not _id:\n return ({'msg': 'params error !'}, 400)\ntry:\n result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'model_section': 1})\n if not result:\n return ({'msg': 'id is not exist !'}, 200)\nexcept Exception as e:\n logging.error(e, ...
<|body_start_0|> _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'model_section': 1}) if not result: return ({'msg': 'id is not ...
ModelSectionViews
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelSectionViews: def get(self): """get one model section through id :return:""" <|body_0|> def post(self): """add an model section record :return:""" <|body_1|> def put(self): """update model section record :return:""" <|body_2|> <|end...
stack_v2_sparse_classes_36k_train_033629
20,183
no_license
[ { "docstring": "get one model section through id :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "add an model section record :return:", "name": "post", "signature": "def post(self)" }, { "docstring": "update model section record :return:", "name": "p...
3
stack_v2_sparse_classes_30k_train_003007
Implement the Python class `ModelSectionViews` described below. Class description: Implement the ModelSectionViews class. Method signatures and docstrings: - def get(self): get one model section through id :return: - def post(self): add an model section record :return: - def put(self): update model section record :re...
Implement the Python class `ModelSectionViews` described below. Class description: Implement the ModelSectionViews class. Method signatures and docstrings: - def get(self): get one model section through id :return: - def post(self): add an model section record :return: - def put(self): update model section record :re...
054324b50e807d6f4e98f4a1b67afac9a0653b06
<|skeleton|> class ModelSectionViews: def get(self): """get one model section through id :return:""" <|body_0|> def post(self): """add an model section record :return:""" <|body_1|> def put(self): """update model section record :return:""" <|body_2|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelSectionViews: def get(self): """get one model section through id :return:""" _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'model_s...
the_stack_v2_python_sparse
services/AlgoVersion/views.py
condilin/DMS
train
0
d0c44c99119ac2e02260ff2f0b0d23a3c6d45be4
[ "super().__init__(reduction='none')\nself.recon_loss_coeff = recon_loss_coeff\nself.proj_coeff = proj_coeff\nself.lambda1 = lambda1\nself.lambda2 = lambda2\nself.loss = torch.nn.BCELoss()", "score, recon, code, dictionary_features_latent, drug_pair_features_latent, drug_pair_features = x\nbatch_size, _ = drug_pai...
<|body_start_0|> super().__init__(reduction='none') self.recon_loss_coeff = recon_loss_coeff self.proj_coeff = proj_coeff self.lambda1 = lambda1 self.lambda2 = lambda2 self.loss = torch.nn.BCELoss() <|end_body_0|> <|body_start_1|> score, recon, code, dictionary_f...
An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs: class prediction loss, input reconstruction loss, and dictionary projection loss. .. [...
CASTERSupervisedLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CASTERSupervisedLoss: """An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs: class prediction loss, input reconstru...
stack_v2_sparse_classes_36k_train_033630
25,672
no_license
[ { "docstring": "Initialize the custom loss function for the supervised learning stage of the CASTER algorithm. :param recon_loss_coeff: coefficient for the reconstruction loss :param proj_coeff: coefficient for the projection loss :param lambda1: regularization coefficient for the projection loss :param lambda2...
2
stack_v2_sparse_classes_30k_train_006225
Implement the Python class `CASTERSupervisedLoss` described below. Class description: An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs:...
Implement the Python class `CASTERSupervisedLoss` described below. Class description: An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs:...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class CASTERSupervisedLoss: """An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs: class prediction loss, input reconstru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CASTERSupervisedLoss: """An implementation of the custom loss function for the supervised learning stage of the CASTER algorithm. The algorithm is described in [huang2020]_. The loss function combines three separate loss functions on different model outputs: class prediction loss, input reconstruction loss, a...
the_stack_v2_python_sparse
generated/test_AstraZeneca_chemicalx.py
jansel/pytorch-jit-paritybench
train
35
77b27aa9bcdf38a485b7e177d47c3a15aa13c0a5
[ "self.canvas = canvas\nself.size = size\nself.w = screen_width\nself.h = screen_height\nself.color = color\nself.x_speed = x_speed\nself.y_speed = y_speed\nself.x = self.w / 2.0\nself.y = self.h / 2.0\nself.prev_x = self.x\nself.prev_y = self.y", "x = self.x\ny = self.y\nsize = self.size\nw = self.w\nh = self.h\n...
<|body_start_0|> self.canvas = canvas self.size = size self.w = screen_width self.h = screen_height self.color = color self.x_speed = x_speed self.y_speed = y_speed self.x = self.w / 2.0 self.y = self.h / 2.0 self.prev_x = self.x se...
Bouncing box.
Box
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Box: """Bouncing box.""" def __init__(self, screen_width, screen_height, size, canvas, x_speed, y_speed, color): """Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Square side length. display (SSD1351): OLED display object....
stack_v2_sparse_classes_36k_train_033631
4,151
permissive
[ { "docstring": "Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Square side length. display (SSD1351): OLED display object. color (int): RGB565 color value.", "name": "__init__", "signature": "def __init__(self, screen_width, screen_height, si...
3
stack_v2_sparse_classes_30k_train_007595
Implement the Python class `Box` described below. Class description: Bouncing box. Method signatures and docstrings: - def __init__(self, screen_width, screen_height, size, canvas, x_speed, y_speed, color): Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Sq...
Implement the Python class `Box` described below. Class description: Bouncing box. Method signatures and docstrings: - def __init__(self, screen_width, screen_height, size, canvas, x_speed, y_speed, color): Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Sq...
a4ccb16b17f915fb85d66facec2978166151af2b
<|skeleton|> class Box: """Bouncing box.""" def __init__(self, screen_width, screen_height, size, canvas, x_speed, y_speed, color): """Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Square side length. display (SSD1351): OLED display object....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Box: """Bouncing box.""" def __init__(self, screen_width, screen_height, size, canvas, x_speed, y_speed, color): """Initialize box. Args: screen_width (int): Width of screen. screen_height (int): Width of height. size (int): Square side length. display (SSD1351): OLED display object. color (int):...
the_stack_v2_python_sparse
st7735_demos/demo_bouncing_boxes.py
amirgon/lv_mpy_examples
train
0
fd882d7f488189aa7acacf7e7a2fcf477ded1d74
[ "import sys\nif root is None:\n return 0\ntree_node_values = self.inorderTraversal(root)\nmin_diff = sys.maxsize\nfor index in range(len(tree_node_values) - 1):\n if min_diff > tree_node_values[index + 1] - tree_node_values[index]:\n min_diff = tree_node_values[index + 1] - tree_node_values[index]\nret...
<|body_start_0|> import sys if root is None: return 0 tree_node_values = self.inorderTraversal(root) min_diff = sys.maxsize for index in range(len(tree_node_values) - 1): if min_diff > tree_node_values[index + 1] - tree_node_values[index]: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getMinimumDifference(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> import sys if root ...
stack_v2_sparse_classes_36k_train_033632
1,453
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "getMinimumDifference", "signature": "def getMinimumDifference(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "inorderTraversal", "signature": "def inorderTraversal(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMinimumDifference(self, root): :type root: TreeNode :rtype: int - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getMinimumDifference(self, root): :type root: TreeNode :rtype: int - def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] <|skeleton|> class Solution: ...
79ca9fdc471a1c84fce188cb05d2ef7b2469eb69
<|skeleton|> class Solution: def getMinimumDifference(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def inorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getMinimumDifference(self, root): """:type root: TreeNode :rtype: int""" import sys if root is None: return 0 tree_node_values = self.inorderTraversal(root) min_diff = sys.maxsize for index in range(len(tree_node_values) - 1): ...
the_stack_v2_python_sparse
getMinimumDifference.py
athmey/MyLeetCode
train
0
91425c5d7ce527039483f69d6551b7de3bc112bc
[ "task, document = create_dummy_document()\nresponse = self.client.get(reverse('qe:document', kwargs={'task_id': task.id, 'document_id': document.id}))\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.context['document'].id, document.id)", "task, document = create_dummy_document()\nresponse ...
<|body_start_0|> task, document = create_dummy_document() response = self.client.get(reverse('qe:document', kwargs={'task_id': task.id, 'document_id': document.id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['document'].id, document.id) <|end_body_0|> ...
UrlTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UrlTests: def test_document_existing_task(self): """When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the requested task""" <|body_0|> def test_document_nonexisting_task(self): """W...
stack_v2_sparse_classes_36k_train_033633
3,820
no_license
[ { "docstring": "When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the requested task", "name": "test_document_existing_task", "signature": "def test_document_existing_task(self)" }, { "docstring": "When task/ta...
2
stack_v2_sparse_classes_30k_train_020493
Implement the Python class `UrlTests` described below. Class description: Implement the UrlTests class. Method signatures and docstrings: - def test_document_existing_task(self): When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the...
Implement the Python class `UrlTests` described below. Class description: Implement the UrlTests class. Method signatures and docstrings: - def test_document_existing_task(self): When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the...
3255f19ef53b8c994d53d9e5f1a6b8404c33e4b6
<|skeleton|> class UrlTests: def test_document_existing_task(self): """When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the requested task""" <|body_0|> def test_document_nonexisting_task(self): """W...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UrlTests: def test_document_existing_task(self): """When task/task_id/document/document_id is given in the URL then the view should return results if the requested document is included in the requested task""" task, document = create_dummy_document() response = self.client.get(reverse(...
the_stack_v2_python_sparse
qe/tests.py
lefterav/qegui
train
1
c25d7dafdeaf49c5244ff060abf91e3f73419a66
[ "if not data.get('project_id'):\n data['project_id'] = uuid.uuid4().hex\nreturn data", "try:\n git_url = GitURL.parse(data['git_url'])\nexcept UnicodeError as e:\n raise ValidationError('`git_url` contains unsupported characters') from e\nexcept errors.InvalidGitURL as e:\n raise ValidationError('Inva...
<|body_start_0|> if not data.get('project_id'): data['project_id'] = uuid.uuid4().hex return data <|end_body_0|> <|body_start_1|> try: git_url = GitURL.parse(data['git_url']) except UnicodeError as e: raise ValidationError('`git_url` contains unsuppor...
Context schema for project clone.
ProjectCloneContext
[ "Apache-2.0", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectCloneContext: """Context schema for project clone.""" def set_missing_id(self, data, **kwargs): """Set project_id when missing.""" <|body_0|> def set_owner_name(self, data, **kwargs): """Set owner and name fields.""" <|body_1|> def format_url(...
stack_v2_sparse_classes_36k_train_033634
14,192
permissive
[ { "docstring": "Set project_id when missing.", "name": "set_missing_id", "signature": "def set_missing_id(self, data, **kwargs)" }, { "docstring": "Set owner and name fields.", "name": "set_owner_name", "signature": "def set_owner_name(self, data, **kwargs)" }, { "docstring": "Fo...
4
stack_v2_sparse_classes_30k_test_000713
Implement the Python class `ProjectCloneContext` described below. Class description: Context schema for project clone. Method signatures and docstrings: - def set_missing_id(self, data, **kwargs): Set project_id when missing. - def set_owner_name(self, data, **kwargs): Set owner and name fields. - def format_url(self...
Implement the Python class `ProjectCloneContext` described below. Class description: Context schema for project clone. Method signatures and docstrings: - def set_missing_id(self, data, **kwargs): Set project_id when missing. - def set_owner_name(self, data, **kwargs): Set owner and name fields. - def format_url(self...
e0ff587f507d049eeeb873e8488ba8bb10ac1a15
<|skeleton|> class ProjectCloneContext: """Context schema for project clone.""" def set_missing_id(self, data, **kwargs): """Set project_id when missing.""" <|body_0|> def set_owner_name(self, data, **kwargs): """Set owner and name fields.""" <|body_1|> def format_url(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectCloneContext: """Context schema for project clone.""" def set_missing_id(self, data, **kwargs): """Set project_id when missing.""" if not data.get('project_id'): data['project_id'] = uuid.uuid4().hex return data def set_owner_name(self, data, **kwargs): ...
the_stack_v2_python_sparse
renku/ui/service/serializers/cache.py
SwissDataScienceCenter/renku-python
train
30
82bb39dbb7391161dd61f37312a2e56b4923b0f9
[ "is_cloud_admin = self.helper.is_user_cloud_admin()\napps_user_is_admin_on = self.helper.get_owned_apps()\napp_name = self.request.get('appid')\nif not is_cloud_admin and app_name not in apps_user_is_admin_on:\n response = json.dumps({'error': True, 'message': 'Not authorized'})\n self.response.out.write(resp...
<|body_start_0|> is_cloud_admin = self.helper.is_user_cloud_admin() apps_user_is_admin_on = self.helper.get_owned_apps() app_name = self.request.get('appid') if not is_cloud_admin and app_name not in apps_user_is_admin_on: response = json.dumps({'error': True, 'message': 'Not...
Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application.
InstanceStats
[ "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstanceStats: """Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application.""" def get(self): """Makes sure the user is allowed to see instance data for the named application, and if so, retrieves it ...
stack_v2_sparse_classes_36k_train_033635
37,207
permissive
[ { "docstring": "Makes sure the user is allowed to see instance data for the named application, and if so, retrieves it for them.", "name": "get", "signature": "def get(self)" }, { "docstring": "Adds information about one or more instances to the Datastore, for later viewing.", "name": "post"...
4
stack_v2_sparse_classes_30k_train_019042
Implement the Python class `InstanceStats` described below. Class description: Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application. Method signatures and docstrings: - def get(self): Makes sure the user is allowed to see instance...
Implement the Python class `InstanceStats` described below. Class description: Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application. Method signatures and docstrings: - def get(self): Makes sure the user is allowed to see instance...
aa36e8dfaa295d53bec616ed07f91ec8c02fa4e1
<|skeleton|> class InstanceStats: """Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application.""" def get(self): """Makes sure the user is allowed to see instance data for the named application, and if so, retrieves it ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstanceStats: """Class that returns instance statistics in JSON relating to the number of AppServer processes running for a particular App Engine application.""" def get(self): """Makes sure the user is allowed to see instance data for the named application, and if so, retrieves it for them.""" ...
the_stack_v2_python_sparse
AppDashboard/dashboard.py
shatterednirvana/appscale
train
6
5f50cac7bab77100f94eb1a636a9bf86fef3c89c
[ "if obj.organization_address is None:\n return None\nserializer = OrganizationAddressSerializer(obj.organization_address, read_only=True)\nreturn serializer.data", "request = self.context.get('request')\nif not request.user.has_perm('VIEW_FUEL_SUPPLIERS') and request.user.organization.id != obj.id:\n return...
<|body_start_0|> if obj.organization_address is None: return None serializer = OrganizationAddressSerializer(obj.organization_address, read_only=True) return serializer.data <|end_body_0|> <|body_start_1|> request = self.context.get('request') if not request.user.has...
Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier
OrganizationSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrganizationSerializer: """Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier""" def get_organization_address(self, obj): """Shows the organization address""" <|body_0|> def get_organization_balance(self, obj): """Only...
stack_v2_sparse_classes_36k_train_033636
8,700
permissive
[ { "docstring": "Shows the organization address", "name": "get_organization_address", "signature": "def get_organization_address(self, obj)" }, { "docstring": "Only show the credit balance if the logged in user has permission to view fuel suppliers", "name": "get_organization_balance", "s...
2
stack_v2_sparse_classes_30k_train_002585
Implement the Python class `OrganizationSerializer` described below. Class description: Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier Method signatures and docstrings: - def get_organization_address(self, obj): Shows the organization address - def get_organization_bal...
Implement the Python class `OrganizationSerializer` described below. Class description: Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier Method signatures and docstrings: - def get_organization_address(self, obj): Shows the organization address - def get_organization_bal...
80ae1ef5938ef5e580128ed0c622071b307fc7e1
<|skeleton|> class OrganizationSerializer: """Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier""" def get_organization_address(self, obj): """Shows the organization address""" <|body_0|> def get_organization_balance(self, obj): """Only...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrganizationSerializer: """Serializer for the Fuel Supplier Loads most of the fields and the balance for the Fuel Supplier""" def get_organization_address(self, obj): """Shows the organization address""" if obj.organization_address is None: return None serializer = Org...
the_stack_v2_python_sparse
backend/api/serializers/Organization.py
kuanfandevops/tfrs
train
0
b81790009ff02e0b56764083d8ceca130011f3d3
[ "self.Whh = randn(hidden_size, hidden_size) * (2 / hidden_size ** 0.5)\nself.Wxh = randn(hidden_size, input_size) * (2 / hidden_size ** 0.5)\nself.Why = randn(output_size, hidden_size) * (2 / output_size ** 0.5)\nself.bh = np.zeros((hidden_size, 1))\nself.by = np.zeros((output_size, 1))\nself.x = None\nself.h = dic...
<|body_start_0|> self.Whh = randn(hidden_size, hidden_size) * (2 / hidden_size ** 0.5) self.Wxh = randn(hidden_size, input_size) * (2 / hidden_size ** 0.5) self.Why = randn(output_size, hidden_size) * (2 / output_size ** 0.5) self.bh = np.zeros((hidden_size, 1)) self.by = np.zero...
RNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNN: def __init__(self, input_size, output_size, hidden_size=64): """:param input_size: :param output_size: :param hidden_size:""" <|body_0|> def forward(self, x): """RNN forward. :param x: :return:""" <|body_1|> def backward(self, eta, lr=0.01): ...
stack_v2_sparse_classes_36k_train_033637
2,861
no_license
[ { "docstring": ":param input_size: :param output_size: :param hidden_size:", "name": "__init__", "signature": "def __init__(self, input_size, output_size, hidden_size=64)" }, { "docstring": "RNN forward. :param x: :return:", "name": "forward", "signature": "def forward(self, x)" }, {...
3
stack_v2_sparse_classes_30k_train_011449
Implement the Python class `RNN` described below. Class description: Implement the RNN class. Method signatures and docstrings: - def __init__(self, input_size, output_size, hidden_size=64): :param input_size: :param output_size: :param hidden_size: - def forward(self, x): RNN forward. :param x: :return: - def backwa...
Implement the Python class `RNN` described below. Class description: Implement the RNN class. Method signatures and docstrings: - def __init__(self, input_size, output_size, hidden_size=64): :param input_size: :param output_size: :param hidden_size: - def forward(self, x): RNN forward. :param x: :return: - def backwa...
f361c91788e1cfed2b0eb5a5bc6ee855aaf1f956
<|skeleton|> class RNN: def __init__(self, input_size, output_size, hidden_size=64): """:param input_size: :param output_size: :param hidden_size:""" <|body_0|> def forward(self, x): """RNN forward. :param x: :return:""" <|body_1|> def backward(self, eta, lr=0.01): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNN: def __init__(self, input_size, output_size, hidden_size=64): """:param input_size: :param output_size: :param hidden_size:""" self.Whh = randn(hidden_size, hidden_size) * (2 / hidden_size ** 0.5) self.Wxh = randn(hidden_size, input_size) * (2 / hidden_size ** 0.5) self.Why...
the_stack_v2_python_sparse
python/alea/rnn.py
WJHoddish/kata
train
0
538e5a04d8610d0e42b2716f2bd42d2b2962f055
[ "CtrlDev.__init__(self, parent)\nself._name = 'Disco Rigido'\nself._category = 'Armazenamento'\nself._diag = DiagHarddisk(self)\nself._compat = CompatHarddisk(self)\nself._guiClass = GUIHarddisk", "self._callInfo()\nself._callCompat()\nself._callDiag()" ]
<|body_start_0|> CtrlDev.__init__(self, parent) self._name = 'Disco Rigido' self._category = 'Armazenamento' self._diag = DiagHarddisk(self) self._compat = CompatHarddisk(self) self._guiClass = GUIHarddisk <|end_body_0|> <|body_start_1|> self._callInfo() ...
Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição.
CtrlHarddisk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CtrlHarddisk: """Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição.""" def __init__(self, parent): """Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe ...
stack_v2_sparse_classes_36k_train_033638
1,196
no_license
[ { "docstring": "Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe base 'CtrlDev'.", "name": "__init__", "signature": "def __init__(self, parent)" }, { "docstring": "Executa o info, compat, diag e cria as telas de exibição.", "name": "execute_lib", ...
2
stack_v2_sparse_classes_30k_train_006541
Implement the Python class `CtrlHarddisk` described below. Class description: Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição. Method signatures and docstrings: - def __init__(self, parent): Construtor que inicializa os atribu...
Implement the Python class `CtrlHarddisk` described below. Class description: Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição. Method signatures and docstrings: - def __init__(self, parent): Construtor que inicializa os atribu...
bda0c2c8977dd1246339f1f0f4718d29e8795f21
<|skeleton|> class CtrlHarddisk: """Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição.""" def __init__(self, parent): """Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CtrlHarddisk: """Estende a classe 'CtrlDev'. Classe de controle que chama os testes de identificação, compatibilidade, diagnóstico e cria a tela de exibição.""" def __init__(self, parent): """Construtor que inicializa os atributos '_diag', '_compat' e '_guiClass' definidos na classe base 'CtrlDev...
the_stack_v2_python_sparse
src/libs/harddisk/ctrl_harddisk.py
adrianomelo/ldc-desktop
train
1
aaff995ffa4966888ef6a26f9bd5a84e65e7fd97
[ "super().__init__(event)\nself.user = IDNamePair(event['user']['id'], event['user']['name'])\nself.team = IDNamePair(event['team']['id'], event['team']['domain'])\nself.channel = IDNamePair(event['channel']['id'], event['channel']['name'])\nself.callback_id = event['callback_id']\nself.event_type = event['type']\ns...
<|body_start_0|> super().__init__(event) self.user = IDNamePair(event['user']['id'], event['user']['name']) self.team = IDNamePair(event['team']['id'], event['team']['domain']) self.channel = IDNamePair(event['channel']['id'], event['channel']['name']) self.callback_id = event['c...
DialogInteractiveEvent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DialogInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary""" <|body_0|> def require_any(self, requirements: List[str]) -> dict: """Convenience method t...
stack_v2_sparse_classes_36k_train_033639
4,539
permissive
[ { "docstring": "Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary", "name": "__init__", "signature": "def __init__(self, event: dict)" }, { "docstring": "Convenience method to construct the 'errors' response to send directly back to...
2
stack_v2_sparse_classes_30k_train_003282
Implement the Python class `DialogInteractiveEvent` described below. Class description: Implement the DialogInteractiveEvent class. Method signatures and docstrings: - def __init__(self, event: dict): Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary - d...
Implement the Python class `DialogInteractiveEvent` described below. Class description: Implement the DialogInteractiveEvent class. Method signatures and docstrings: - def __init__(self, event: dict): Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary - d...
4b026da33695b25033c7667679f3cf552c4bf3b5
<|skeleton|> class DialogInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary""" <|body_0|> def require_any(self, requirements: List[str]) -> dict: """Convenience method t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DialogInteractiveEvent: def __init__(self, event: dict): """Convenience class to parse a dialog interaction payload from the events API Args: event: the raw event dictionary""" super().__init__(event) self.user = IDNamePair(event['user']['id'], event['user']['name']) self.team ...
the_stack_v2_python_sparse
terraform/stacks/bot/lambdas/python/slack_automation_bot/slack/web/classes/interactions.py
cloud-sniper/cloud-sniper
train
184
0e92e566cc1c946207b087acc0d50ae5ab978d1a
[ "self.lambtha = float(lambtha)\nif data is None:\n if self.lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\nelif type(data) is not list:\n raise TypeError('data must be a list')\nelif len(data) < 2:\n raise ValueError('data must contain multiple values')\nelse:\n self.data = ...
<|body_start_0|> self.lambtha = float(lambtha) if data is None: if self.lambtha <= 0: raise ValueError('lambtha must be a positive value') elif type(data) is not list: raise TypeError('data must be a list') elif len(data) < 2: raise Val...
Exponential represents an exponential distribution
Exponential
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exponential: """Exponential represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_033640
1,723
no_license
[ { "docstring": "Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "pdf - Calculates the value of the PDF f...
3
null
Implement the Python class `Exponential` described below. Class description: Exponential represents an exponential distribution Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of oc...
Implement the Python class `Exponential` described below. Class description: Exponential represents an exponential distribution Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of oc...
8cd5e0f837a5c0facbf73647dcc9c6a3b1b1b9e0
<|skeleton|> class Exponential: """Exponential represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exponential: """Exponential represents an exponential distribution""" def __init__(self, data=None, lambtha=1.0): """Args: data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame.""" self.lambtha = float(lambth...
the_stack_v2_python_sparse
math/0x03-probability/exponential.py
giovannyortegon/holbertonschool-machine_learning
train
1
e6ec4b41a2c3f75bf2f8ba82bd0b3c51f62fda2e
[ "schools_urls_xpath = '//*[@id=\"table10\"]/tr/td/table[2]/tr/td/font/a/@href'\nschools_urls = response.xpath(schools_urls_xpath).extract()\nfor url in schools_urls:\n yield scrapy.Request(response.urljoin(url), callback=self.parse_school)", "school_name_xpath = '//*[@id=\"table1\"]/tr[1]/td/table/tr/td[1]/fon...
<|body_start_0|> schools_urls_xpath = '//*[@id="table10"]/tr/td/table[2]/tr/td/font/a/@href' schools_urls = response.xpath(schools_urls_xpath).extract() for url in schools_urls: yield scrapy.Request(response.urljoin(url), callback=self.parse_school) <|end_body_0|> <|body_start_1|> ...
a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
MontrealLbpsbSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MontrealLbpsbSpider: """a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found""" def parse(self, response): """get all s...
stack_v2_sparse_classes_36k_train_033641
3,493
no_license
[ { "docstring": "get all schools urls then yield a Request for each one.", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "get required information for each school this method is called once for each school", "name": "parse_school", "signature": "def parse_sch...
2
stack_v2_sparse_classes_30k_train_017309
Implement the Python class `MontrealLbpsbSpider` described below. Class description: a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found Method signatur...
Implement the Python class `MontrealLbpsbSpider` described below. Class description: a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found Method signatur...
350264cf6da323692c2838d8cb235ef61085851b
<|skeleton|> class MontrealLbpsbSpider: """a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found""" def parse(self, response): """get all s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MontrealLbpsbSpider: """a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found""" def parse(self, response): """get all schools urls t...
the_stack_v2_python_sparse
school_scraping/spiders/montreal_lbpsb.py
ramadanmostafa/canada_school_scraping
train
0
3e0d7201af7abd4cca6f95287cfe8a3b581eda87
[ "self._model = model\nself._labels = labels\nself._settings = settings\nself._cond_prob = cond_prob\nself._misc = MiscNN(settings)\nself.loss = self._get_loss()", "with tf.variable_scope('LossHelper/get_loss'):\n self._labels = tf.cast(self._labels, dtype=tf.int32)\n if self._settings.identifier is None:\n ...
<|body_start_0|> self._model = model self._labels = labels self._settings = settings self._cond_prob = cond_prob self._misc = MiscNN(settings) self.loss = self._get_loss() <|end_body_0|> <|body_start_1|> with tf.variable_scope('LossHelper/get_loss'): ...
Loss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Loss: def __init__(self, model, labels, settings, cond_prob=None): """Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for calculating the loss :param cond_prob: P(s_k|m_j) probability for calculating the loss :param ...
stack_v2_sparse_classes_36k_train_033642
6,159
no_license
[ { "docstring": "Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for calculating the loss :param cond_prob: P(s_k|m_j) probability for calculating the loss :param identifier: define which loss is used", "name": "__init__", "signature...
2
stack_v2_sparse_classes_30k_train_019400
Implement the Python class `Loss` described below. Class description: Implement the Loss class. Method signatures and docstrings: - def __init__(self, model, labels, settings, cond_prob=None): Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for c...
Implement the Python class `Loss` described below. Class description: Implement the Loss class. Method signatures and docstrings: - def __init__(self, model, labels, settings, cond_prob=None): Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for c...
7187b12844e99374ee252b0d19034300af08b56d
<|skeleton|> class Loss: def __init__(self, model, labels, settings, cond_prob=None): """Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for calculating the loss :param cond_prob: P(s_k|m_j) probability for calculating the loss :param ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Loss: def __init__(self, model, labels, settings, cond_prob=None): """Create your individual loss for your model :param logits: logits from the model (without softmax) :param labels: labels for calculating the loss :param cond_prob: P(s_k|m_j) probability for calculating the loss :param identifier: de...
the_stack_v2_python_sparse
NeuralNetHelper/LossHelper.py
Lujun111/nnvq-framework
train
0
3e3b31ae6538ad60007d7159a3da0c0efd05f594
[ "driver = self.base_driver\ndriver.sleep(3)\ndriver.drag_js('x,/html/body/div[4]/div[3]/div/ul/li[2]/div')\ndriver.sleep(3)\ndriver.open_new_window('x,/html/body/div[4]/div[3]/div/ul/li[2]/div/p[1]/a/img')\ndriver.drag_js('x,//*[@id=\"buy_area\"]/a[1]/em')\ndriver.click('x,/html/body/div[6]/div[1]/div[2]/div[1]/a[1...
<|body_start_0|> driver = self.base_driver driver.sleep(3) driver.drag_js('x,/html/body/div[4]/div[3]/div/ul/li[2]/div') driver.sleep(3) driver.open_new_window('x,/html/body/div[4]/div[3]/div/ul/li[2]/div/p[1]/a/img') driver.drag_js('x,//*[@id="buy_area"]/a[1]/em') ...
HomeShopPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HomeShopPage: def shop_floor_page(self): """首页楼层购买手机""" <|body_0|> def shop_list_page(self): """首页表单购买手机""" <|body_1|> <|end_skeleton|> <|body_start_0|> driver = self.base_driver driver.sleep(3) driver.drag_js('x,/html/body/div[4]/di...
stack_v2_sparse_classes_36k_train_033643
1,419
no_license
[ { "docstring": "首页楼层购买手机", "name": "shop_floor_page", "signature": "def shop_floor_page(self)" }, { "docstring": "首页表单购买手机", "name": "shop_list_page", "signature": "def shop_list_page(self)" } ]
2
null
Implement the Python class `HomeShopPage` described below. Class description: Implement the HomeShopPage class. Method signatures and docstrings: - def shop_floor_page(self): 首页楼层购买手机 - def shop_list_page(self): 首页表单购买手机
Implement the Python class `HomeShopPage` described below. Class description: Implement the HomeShopPage class. Method signatures and docstrings: - def shop_floor_page(self): 首页楼层购买手机 - def shop_list_page(self): 首页表单购买手机 <|skeleton|> class HomeShopPage: def shop_floor_page(self): """首页楼层购买手机""" ...
b75bf1bdbf4ee14f0485d552ff2f382c7991821e
<|skeleton|> class HomeShopPage: def shop_floor_page(self): """首页楼层购买手机""" <|body_0|> def shop_list_page(self): """首页表单购买手机""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HomeShopPage: def shop_floor_page(self): """首页楼层购买手机""" driver = self.base_driver driver.sleep(3) driver.drag_js('x,/html/body/div[4]/div[3]/div/ul/li[2]/div') driver.sleep(3) driver.open_new_window('x,/html/body/div[4]/div[3]/div/ul/li[2]/div/p[1]/a/img') ...
the_stack_v2_python_sparse
nengkaiShop_1/page/shop_page.py
caixinshu/api
train
0
692b526d309f5dc65e96b4fa97641b156035f350
[ "if criteria is None:\n criteria = {}\nself.trials = get_trials(base_dir, criteria=criteria)\nassert len(self.trials) > 0, 'Nothing loaded.'\nself.label = 'AverageReturn'", "if criteria is None:\n criteria = {}\nreturn [trial for trial in self.trials if matches_dict(criteria, trial.variant)]" ]
<|body_start_0|> if criteria is None: criteria = {} self.trials = get_trials(base_dir, criteria=criteria) assert len(self.trials) > 0, 'Nothing loaded.' self.label = 'AverageReturn' <|end_body_0|> <|body_start_1|> if criteria is None: criteria = {} ...
Represents an experiment, which consists of many Trials.
Experiment
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Experiment: """Represents an experiment, which consists of many Trials.""" def __init__(self, base_dir, criteria=None): """:param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtrarily_deep/ trial_one/ variant.json progress.csv trial_two/ v...
stack_v2_sparse_classes_36k_train_033644
5,929
permissive
[ { "docstring": ":param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtrarily_deep/ trial_one/ variant.json progress.csv trial_two/ variant.json progress.csv trial_three/ variant.json progress.csv ... variant.json # <-- base_dir/foo/bar has its own Trial progress.csv ...
2
stack_v2_sparse_classes_30k_train_015149
Implement the Python class `Experiment` described below. Class description: Represents an experiment, which consists of many Trials. Method signatures and docstrings: - def __init__(self, base_dir, criteria=None): :param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtraril...
Implement the Python class `Experiment` described below. Class description: Represents an experiment, which consists of many Trials. Method signatures and docstrings: - def __init__(self, base_dir, criteria=None): :param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtraril...
baba8ce634d32a48c7dfe4dc03b123e18e96e0a3
<|skeleton|> class Experiment: """Represents an experiment, which consists of many Trials.""" def __init__(self, base_dir, criteria=None): """:param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtrarily_deep/ trial_one/ variant.json progress.csv trial_two/ v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Experiment: """Represents an experiment, which consists of many Trials.""" def __init__(self, base_dir, criteria=None): """:param base_dir: A path. Directory structure should be something like: ``` base_dir/ foo/ bar/ arbtrarily_deep/ trial_one/ variant.json progress.csv trial_two/ variant.json p...
the_stack_v2_python_sparse
rlkit/misc/data_processing.py
Asap7772/railrl_evalsawyer
train
1
f0c452d95b64d2ff2fa1b4674747d0b0799b375b
[ "super().__init__()\nself.enc_freeze = enc_freeze\nuse_style = style_channels is not None\nself.heads = heads\nself.decoders = decoders\nself.inst_key = inst_key\nself.aux_key = aux_key\nself.add_stem_skip = add_stem_skip\nself.encoder = Encoder(enc_name, depth=depth, pretrained=enc_pretrain, checkpoint_path=kwargs...
<|body_start_0|> super().__init__() self.enc_freeze = enc_freeze use_style = style_channels is not None self.heads = heads self.decoders = decoders self.inst_key = inst_key self.aux_key = aux_key self.add_stem_skip = add_stem_skip self.encoder = En...
MultiTaskUnet
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiTaskUnet: def __init__(self, decoders: Tuple[str, ...], heads: Dict[str, Dict[str, int]], long_skips: Dict[str, Union[str, Tuple[str, ...]]], out_channels: Dict[str, Tuple[int, ...]], n_conv_layers: Dict[str, Tuple[int, ...]]=None, n_conv_blocks: Dict[str, Tuple[Tuple[int, ...], ...]]=None,...
stack_v2_sparse_classes_36k_train_033645
9,208
permissive
[ { "docstring": "Create a universal multi-task (2D) unet. NOTE: For experimental purposes. Parameters ---------- decoders : Tuple[str, ...] Names of the decoder branches of this network. E.g. (\"cellpose\", \"sem\") heads : Dict[str, Dict[str, int]] Names of the decoder branches (has to match `decoders`) mapped ...
4
stack_v2_sparse_classes_30k_train_016770
Implement the Python class `MultiTaskUnet` described below. Class description: Implement the MultiTaskUnet class. Method signatures and docstrings: - def __init__(self, decoders: Tuple[str, ...], heads: Dict[str, Dict[str, int]], long_skips: Dict[str, Union[str, Tuple[str, ...]]], out_channels: Dict[str, Tuple[int, ....
Implement the Python class `MultiTaskUnet` described below. Class description: Implement the MultiTaskUnet class. Method signatures and docstrings: - def __init__(self, decoders: Tuple[str, ...], heads: Dict[str, Dict[str, int]], long_skips: Dict[str, Union[str, Tuple[str, ...]]], out_channels: Dict[str, Tuple[int, ....
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class MultiTaskUnet: def __init__(self, decoders: Tuple[str, ...], heads: Dict[str, Dict[str, int]], long_skips: Dict[str, Union[str, Tuple[str, ...]]], out_channels: Dict[str, Tuple[int, ...]], n_conv_layers: Dict[str, Tuple[int, ...]]=None, n_conv_blocks: Dict[str, Tuple[Tuple[int, ...], ...]]=None,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiTaskUnet: def __init__(self, decoders: Tuple[str, ...], heads: Dict[str, Dict[str, int]], long_skips: Dict[str, Union[str, Tuple[str, ...]]], out_channels: Dict[str, Tuple[int, ...]], n_conv_layers: Dict[str, Tuple[int, ...]]=None, n_conv_blocks: Dict[str, Tuple[Tuple[int, ...], ...]]=None, n_transformer...
the_stack_v2_python_sparse
cellseg_models_pytorch/models/base/_multitask_unet.py
okunator/cellseg_models.pytorch
train
43
ee2983bf5be90a6d603c73cada60bb54977528dd
[ "super(StackedRNN, self).__init__()\nself.args = args\nif args.decode_type == 'LSTM':\n self.rnn1 = nn.LSTM(args.num_chan_eeg, args.rnn_num_hidden, batch_first=True)\n self.rnn2 = nn.LSTM(args.rnn_num_hidden, args.rnn_num_hidden, batch_first=True)\nelif args.decode_type == 'GRU':\n self.rnn1 = nn.GRU(args....
<|body_start_0|> super(StackedRNN, self).__init__() self.args = args if args.decode_type == 'LSTM': self.rnn1 = nn.LSTM(args.num_chan_eeg, args.rnn_num_hidden, batch_first=True) self.rnn2 = nn.LSTM(args.rnn_num_hidden, args.rnn_num_hidden, batch_first=True) elif a...
A class for stacked RNN network. Can be either LSTM or GRU
StackedRNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackedRNN: """A class for stacked RNN network. Can be either LSTM or GRU""" def __init__(self, args): """Defining a constructor and initializing the network.""" <|body_0|> def forward(self, input, hidden): """Defining a network architecture for forward pass. :pa...
stack_v2_sparse_classes_36k_train_033646
8,971
permissive
[ { "docstring": "Defining a constructor and initializing the network.", "name": "__init__", "signature": "def __init__(self, args)" }, { "docstring": "Defining a network architecture for forward pass. :param input: dimension: [num_samples x tap_size x num_features] since batch_first=True, this is...
3
stack_v2_sparse_classes_30k_train_006638
Implement the Python class `StackedRNN` described below. Class description: A class for stacked RNN network. Can be either LSTM or GRU Method signatures and docstrings: - def __init__(self, args): Defining a constructor and initializing the network. - def forward(self, input, hidden): Defining a network architecture ...
Implement the Python class `StackedRNN` described below. Class description: A class for stacked RNN network. Can be either LSTM or GRU Method signatures and docstrings: - def __init__(self, args): Defining a constructor and initializing the network. - def forward(self, input, hidden): Defining a network architecture ...
c92e43a0859850be8b32635952f3b1d70bfcf686
<|skeleton|> class StackedRNN: """A class for stacked RNN network. Can be either LSTM or GRU""" def __init__(self, args): """Defining a constructor and initializing the network.""" <|body_0|> def forward(self, input, hidden): """Defining a network architecture for forward pass. :pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StackedRNN: """A class for stacked RNN network. Can be either LSTM or GRU""" def __init__(self, args): """Defining a constructor and initializing the network.""" super(StackedRNN, self).__init__() self.args = args if args.decode_type == 'LSTM': self.rnn1 = nn.L...
the_stack_v2_python_sparse
models/deep_decoders.py
shonaka/EEG-neural-decoding
train
11
f1a00f1d2ff7bddcc62e58ab02728615524cb5e5
[ "super(DecoderLayer, self).__init__()\nself.multi_head_attention_dec = MultiHeadAttention(hidden_size, total_key_depth, total_value_depth, hidden_size, num_heads, bias_mask, attention_dropout)\nself.multi_head_attention_enc_dec = MultiHeadAttention(hidden_size, total_key_depth, total_value_depth, hidden_size, num_h...
<|body_start_0|> super(DecoderLayer, self).__init__() self.multi_head_attention_dec = MultiHeadAttention(hidden_size, total_key_depth, total_value_depth, hidden_size, num_heads, bias_mask, attention_dropout) self.multi_head_attention_enc_dec = MultiHeadAttention(hidden_size, total_key_depth, tot...
Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T
DecoderLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderLayer: """Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T""" def __init__(self, hidden_size, total_key_depth, total_value_depth, fil...
stack_v2_sparse_classes_36k_train_033647
6,006
permissive
[ { "docstring": "Parameters: hidden_size: Hidden size total_key_depth: Size of last dimension of keys. Must be divisible by num_head total_value_depth: Size of last dimension of values. Must be divisible by num_head output_depth: Size last dimension of the final output filter_size: Hidden size of the middle laye...
2
stack_v2_sparse_classes_30k_train_004918
Implement the Python class `DecoderLayer` described below. Class description: Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T Method signatures and docstrings: - def...
Implement the Python class `DecoderLayer` described below. Class description: Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T Method signatures and docstrings: - def...
99cba1030ed8c012a453bc7715830fc99fb980dc
<|skeleton|> class DecoderLayer: """Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T""" def __init__(self, hidden_size, total_key_depth, total_value_depth, fil...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoderLayer: """Represents one Decoder layer of the Transformer Decoder Refer Fig. 1 in https://arxiv.org/pdf/1706.03762.pdf NOTE: The layer normalization step has been moved to the input as per latest version of T2T""" def __init__(self, hidden_size, total_key_depth, total_value_depth, filter_size, num...
the_stack_v2_python_sparse
models/networks/transformer/layers.py
jamesoneill12/LayerFusion
train
2
aed85d8bea1d79a9d2a2a0aadf97f69a864ab50c
[ "logger.debug('SubscribeNotification--post::> %s' % request.data)\nlccn_subscription_request_serializer = LccnSubscriptionRequestSerializer(data=request.data)\nif not lccn_subscription_request_serializer.is_valid():\n raise BadRequestException(lccn_subscription_request_serializer.errors)\nsubscription = CreateSu...
<|body_start_0|> logger.debug('SubscribeNotification--post::> %s' % request.data) lccn_subscription_request_serializer = LccnSubscriptionRequestSerializer(data=request.data) if not lccn_subscription_request_serializer.is_valid(): raise BadRequestException(lccn_subscription_request_se...
This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions.
SubscriptionsView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubscriptionsView: """This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions.""" def post(self, request): """The POST method creates a new subscription. :param request: ...
stack_v2_sparse_classes_36k_train_033648
6,020
permissive
[ { "docstring": "The POST method creates a new subscription. :param request: :return:", "name": "post", "signature": "def post(self, request)" }, { "docstring": "The GET method queries the list of active subscriptions of the functional block that invokes the method. It can be used e.g. for resync...
2
null
Implement the Python class `SubscriptionsView` described below. Class description: This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions. Method signatures and docstrings: - def post(self, request): The...
Implement the Python class `SubscriptionsView` described below. Class description: This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions. Method signatures and docstrings: - def post(self, request): The...
129029584597941bb7603dd7440b7d37f823ef96
<|skeleton|> class SubscriptionsView: """This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions.""" def post(self, request): """The POST method creates a new subscription. :param request: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubscriptionsView: """This resource represents subscriptions. The client can use this resource to subscribe to notifications related to NS lifecycle management, and to query its subscriptions.""" def post(self, request): """The POST method creates a new subscription. :param request: :return:""" ...
the_stack_v2_python_sparse
lcm/ns/views/sol/subscriptions_view.py
onap/vfc-nfvo-lcm
train
5
cf80ab8c0390dcb1c01ba6d69ca95b2e605c1685
[ "super().__init__()\nself.margin = margin\nself.reduction = reduction or 'none'", "diff = embeddings_left - embeddings_right\ndistance_pred = torch.sqrt(torch.sum(torch.pow(diff, 2), 1))\nbs = len(distance_true)\nmargin_distance = self.margin - distance_pred\nmargin_distance_ = torch.clamp(margin_distance, min=0....
<|body_start_0|> super().__init__() self.margin = margin self.reduction = reduction or 'none' <|end_body_0|> <|body_start_1|> diff = embeddings_left - embeddings_right distance_pred = torch.sqrt(torch.sum(torch.pow(diff, 2), 1)) bs = len(distance_true) margin_dis...
The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
ContrastiveEmbeddingLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContrastiveEmbeddingLoss: """The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf""" def __init__(...
stack_v2_sparse_classes_36k_train_033649
4,346
permissive
[ { "docstring": "Args: margin: margin parameter reduction: criterion reduction type", "name": "__init__", "signature": "def __init__(self, margin=1.0, reduction='mean')" }, { "docstring": "Forward propagation method for the contrastive loss. Args: embeddings_left (torch.Tensor): left objects embe...
2
stack_v2_sparse_classes_30k_train_005903
Implement the Python class `ContrastiveEmbeddingLoss` described below. Class description: The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-ch...
Implement the Python class `ContrastiveEmbeddingLoss` described below. Class description: The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-ch...
a35297ecab8d1a6c2f00b6435ea1d6d37ec9f441
<|skeleton|> class ContrastiveEmbeddingLoss: """The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf""" def __init__(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContrastiveEmbeddingLoss: """The Contrastive embedding loss. It has been proposed in `Dimensionality Reduction by Learning an Invariant Mapping`_. .. _Dimensionality Reduction by Learning an Invariant Mapping: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf""" def __init__(self, margin=...
the_stack_v2_python_sparse
catalyst/contrib/nn/criterion/contrastive.py
saswat0/catalyst
train
2
9ff6fa0689df07d762130982cb388ce431bd6447
[ "def get_class_arguments(class_):\n \"\"\"\n :param class_: the class to check\n :return: a list containing the arguments from `class_`\n \"\"\"\n signature = inspect.signature(class_.__init__)\n class_arguments = [p.name for p in signature.parameters.values()]\n return ...
<|body_start_0|> def get_class_arguments(class_): """ :param class_: the class to check :return: a list containing the arguments from `class_` """ signature = inspect.signature(class_.__init__) class_arguments = [p.n...
Legacy parser for executor.
LegacyParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LegacyParser: """Legacy parser for executor.""" def _get_all_arguments(class_): """:param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits""" <|body_0|> def parse(self, cls: Type['Bas...
stack_v2_sparse_classes_36k_train_033650
5,038
permissive
[ { "docstring": ":param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits", "name": "_get_all_arguments", "signature": "def _get_all_arguments(class_)" }, { "docstring": ":param cls: target class type to parse ...
4
stack_v2_sparse_classes_30k_train_009774
Implement the Python class `LegacyParser` described below. Class description: Legacy parser for executor. Method signatures and docstrings: - def _get_all_arguments(class_): :param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits ...
Implement the Python class `LegacyParser` described below. Class description: Legacy parser for executor. Method signatures and docstrings: - def _get_all_arguments(class_): :param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits ...
4265163fafe499f80dc52be4a437087bf3c1799f
<|skeleton|> class LegacyParser: """Legacy parser for executor.""" def _get_all_arguments(class_): """:param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits""" <|body_0|> def parse(self, cls: Type['Bas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LegacyParser: """Legacy parser for executor.""" def _get_all_arguments(class_): """:param class_: target class from which we want to retrieve arguments :return: all the arguments of all the classes from which `class_` inherits""" def get_class_arguments(class_): """ ...
the_stack_v2_python_sparse
jina/jaml/parsers/executor/legacy.py
VenusTokyo/jina
train
1
824298a29e4d1a8a99a242b3fed418152ee0cb87
[ "if root is None:\n return False\nif root.left is None and root.right is None:\n return root.val is sum_value\nreturn self.hasPathSum2(root.left, sum_value - root.val) or self.hasPathSum2(root.right, sum_value - root.val)", "if root is None:\n return False\nlast_poped = False\njourney = [(root, root.val)...
<|body_start_0|> if root is None: return False if root.left is None and root.right is None: return root.val is sum_value return self.hasPathSum2(root.left, sum_value - root.val) or self.hasPathSum2(root.right, sum_value - root.val) <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasPathSum2(self, root, sum_value): """:type root: TreeNode :type sum: int :rtype: bool recursion""" <|body_0|> def hasPathSum(self, root, sum_value): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_033651
3,972
no_license
[ { "docstring": ":type root: TreeNode :type sum: int :rtype: bool recursion", "name": "hasPathSum2", "signature": "def hasPathSum2(self, root, sum_value)" }, { "docstring": ":type root: TreeNode :type sum: int :rtype: bool", "name": "hasPathSum", "signature": "def hasPathSum(self, root, s...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum2(self, root, sum_value): :type root: TreeNode :type sum: int :rtype: bool recursion - def hasPathSum(self, root, sum_value): :type root: TreeNode :type sum: int :r...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasPathSum2(self, root, sum_value): :type root: TreeNode :type sum: int :rtype: bool recursion - def hasPathSum(self, root, sum_value): :type root: TreeNode :type sum: int :r...
d2e8b2dca40fc955045eb62e576c776bad8ee5f1
<|skeleton|> class Solution: def hasPathSum2(self, root, sum_value): """:type root: TreeNode :type sum: int :rtype: bool recursion""" <|body_0|> def hasPathSum(self, root, sum_value): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasPathSum2(self, root, sum_value): """:type root: TreeNode :type sum: int :rtype: bool recursion""" if root is None: return False if root.left is None and root.right is None: return root.val is sum_value return self.hasPathSum2(root.left, ...
the_stack_v2_python_sparse
path-sum/solution.py
childe/leetcode
train
2
aff02d4421deb6518184ae189d1198bf8ce7bf12
[ "result = bfs.setup()\nvertices = result[0]\nnode_edges = result[1]\nself.assertEqual(vertices[-1], 200, 'The vertices list has not imported correctly.')\nexpected = [149, 155, 52, 87, 120, 39, 160, 137, 27, 79, 131, 100, 25, 55, 23, 126, 84, 166, 150, 62, 67, 1, 69, 35]\nself.assertEqual(node_edges[200], expected)...
<|body_start_0|> result = bfs.setup() vertices = result[0] node_edges = result[1] self.assertEqual(vertices[-1], 200, 'The vertices list has not imported correctly.') expected = [149, 155, 52, 87, 120, 39, 160, 137, 27, 79, 131, 100, 25, 55, 23, 126, 84, 166, 150, 62, 67, 1, 69, ...
TestBFS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestBFS: def test_setup(self): """Test to ensure lists are set up correctly for the problem.""" <|body_0|> def test_breadth_first_search(self): """Tests the three possible outcomes of a breadth first search: 1) A path exists between two seperate nodes. 2) A node is a...
stack_v2_sparse_classes_36k_train_033652
3,240
permissive
[ { "docstring": "Test to ensure lists are set up correctly for the problem.", "name": "test_setup", "signature": "def test_setup(self)" }, { "docstring": "Tests the three possible outcomes of a breadth first search: 1) A path exists between two seperate nodes. 2) A node is a path unto itself, dis...
3
stack_v2_sparse_classes_30k_train_007237
Implement the Python class `TestBFS` described below. Class description: Implement the TestBFS class. Method signatures and docstrings: - def test_setup(self): Test to ensure lists are set up correctly for the problem. - def test_breadth_first_search(self): Tests the three possible outcomes of a breadth first search:...
Implement the Python class `TestBFS` described below. Class description: Implement the TestBFS class. Method signatures and docstrings: - def test_setup(self): Test to ensure lists are set up correctly for the problem. - def test_breadth_first_search(self): Tests the three possible outcomes of a breadth first search:...
82605a1dea4e52480f006956645e812fe2cb02dc
<|skeleton|> class TestBFS: def test_setup(self): """Test to ensure lists are set up correctly for the problem.""" <|body_0|> def test_breadth_first_search(self): """Tests the three possible outcomes of a breadth first search: 1) A path exists between two seperate nodes. 2) A node is a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestBFS: def test_setup(self): """Test to ensure lists are set up correctly for the problem.""" result = bfs.setup() vertices = result[0] node_edges = result[1] self.assertEqual(vertices[-1], 200, 'The vertices list has not imported correctly.') expected = [149,...
the_stack_v2_python_sparse
Stanford/08_GraphSearch/BreadthFirstSearch/test_breadth_first_search.py
jeffvswanson/DataStructuresAndAlgorithms
train
4
2d1ea1eff797452c5a80b9025b86c44a117995d8
[ "ans = []\ncur = ''\n\ndef dfs(l, r, cur, ans):\n if r == 0 and l == 0:\n ans.append(cur)\n return\n if l > 0:\n dfs(l - 1, r, cur + '(', ans)\n if r > l:\n dfs(l, r - 1, cur + ')', ans)\ndfs(n, n, cur, ans)\nreturn ans", "ans = []\ncur = []\n\ndef dfs(l, r, cur, ans):\n if...
<|body_start_0|> ans = [] cur = '' def dfs(l, r, cur, ans): if r == 0 and l == 0: ans.append(cur) return if l > 0: dfs(l - 1, r, cur + '(', ans) if r > l: dfs(l, r - 1, cur + ')', ans) df...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" <|body_0|> def generateParenthesis2(self, n): """:type n: int :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ans = [] cur = '' def d...
stack_v2_sparse_classes_36k_train_033653
1,751
no_license
[ { "docstring": ":type n: int :rtype: List[str]", "name": "generateParenthesis", "signature": "def generateParenthesis(self, n)" }, { "docstring": ":type n: int :rtype: List[str]", "name": "generateParenthesis2", "signature": "def generateParenthesis2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_005832
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateParenthesis(self, n): :type n: int :rtype: List[str] - def generateParenthesis2(self, n): :type n: int :rtype: List[str]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateParenthesis(self, n): :type n: int :rtype: List[str] - def generateParenthesis2(self, n): :type n: int :rtype: List[str] <|skeleton|> class Solution: def genera...
4d7e675c795c841f99ca95b8b60c4995bcb632fb
<|skeleton|> class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" <|body_0|> def generateParenthesis2(self, n): """:type n: int :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" ans = [] cur = '' def dfs(l, r, cur, ans): if r == 0 and l == 0: ans.append(cur) return if l > 0: dfs(l - 1, r, cur + '(', a...
the_stack_v2_python_sparse
22_Generate Parentheses.py
stephenchenxj/myLeetCode
train
0
7b8536b5c1cc104cbaa84c457546908475149060
[ "self.cap = capacity\nself.dic = {}\nself.cacahe = []", "if key in self.dic:\n self.set(key, self.dic[key])\n return self.dic[key]\nelse:\n return -1", "if key in self.dic:\n self.cacahe.remove(key)\nelif len(self.cacahe) >= self.cap:\n self.dic.pop(self.cacahe.pop(-1))\nself.dic[key] = value\nse...
<|body_start_0|> self.cap = capacity self.dic = {} self.cacahe = [] <|end_body_0|> <|body_start_1|> if key in self.dic: self.set(key, self.dic[key]) return self.dic[key] else: return -1 <|end_body_1|> <|body_start_2|> if key in self.d...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_033654
1,350
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_000835
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
cb70fc9ddc410923cc1dae6015a821d4e52c1c14
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.cap = capacity self.dic = {} self.cacahe = [] def get(self, key): """:rtype: int""" if key in self.dic: self.set(key, self.dic[key]) return self.dic[key] ...
the_stack_v2_python_sparse
146LRU Cache.py
zingzheng/LeetCode_py
train
0
3bfe2d2ac4caf5850c7559dc813b4619e24842a2
[ "self.__sqlSys = sqlSys\nself.__sql = sql\nself.__dboid = {}\nself.__log = Core.Log.File(debug=1, module='1[dmerce].Processor.DBOID')", "db = self.__sql.GetName()\ndbOid = DMS.SQL.DBOID(self.__sqlSys, self.__sql)\nif not self.__dboid.has_key(table):\n newId = self.__dboid[table] = dbOid[table]\n return newI...
<|body_start_0|> self.__sqlSys = sqlSys self.__sql = sql self.__dboid = {} self.__log = Core.Log.File(debug=1, module='1[dmerce].Processor.DBOID') <|end_body_0|> <|body_start_1|> db = self.__sql.GetName() dbOid = DMS.SQL.DBOID(self.__sqlSys, self.__sql) if not se...
manages retrival of (new) db oids from dmerce system database
DBOID
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBOID: """manages retrival of (new) db oids from dmerce system database""" def __init__(self, sqlSys, sql): """takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument""" <|body_0|> def __getitem__(self, table): ...
stack_v2_sparse_classes_36k_train_033655
24,090
no_license
[ { "docstring": "takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument", "name": "__init__", "signature": "def __init__(self, sqlSys, sql)" }, { "docstring": "try to look up DBOID for table in dictionary if we found one return it otherwise get...
2
stack_v2_sparse_classes_30k_train_000179
Implement the Python class `DBOID` described below. Class description: manages retrival of (new) db oids from dmerce system database Method signatures and docstrings: - def __init__(self, sqlSys, sql): takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument - def __...
Implement the Python class `DBOID` described below. Class description: manages retrival of (new) db oids from dmerce system database Method signatures and docstrings: - def __init__(self, sqlSys, sql): takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument - def __...
3cfcae894c165189cc3ff61e27ca284f09e87871
<|skeleton|> class DBOID: """manages retrival of (new) db oids from dmerce system database""" def __init__(self, sqlSys, sql): """takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument""" <|body_0|> def __getitem__(self, table): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBOID: """manages retrival of (new) db oids from dmerce system database""" def __init__(self, sqlSys, sql): """takes an instance of DMS.SQL.DBAPI to dmerce system database and the database we should work on as argument""" self.__sqlSys = sqlSys self.__sql = sql self.__dboi...
the_stack_v2_python_sparse
dmerce2/DTL/Processor.py
rbe/dmerce
train
0
4fd20b1408c0bab70cef4d26f58b1ca77e91bfe5
[ "Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage", "item = Inventory.return_as_dictionary(self)\nitem['Brand'] = self.brand\nitem['Voltage'] = self.voltage\nreturn item" ]
<|body_start_0|> Inventory.__init__(self, product_code, description, market_price, rental_price) self.brand = brand self.voltage = voltage <|end_body_0|> <|body_start_1|> item = Inventory.return_as_dictionary(self) item['Brand'] = self.brand item['Voltage'] = self.voltag...
The ElectricAppliances class
ElectricAppliances
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElectricAppliances: """The ElectricAppliances class""" def __init__(self, product_code, description, market_price, rental_price, brand, voltage): """Creates common instance variables from the parent class""" <|body_0|> def return_as_dictionary(self): """Function ...
stack_v2_sparse_classes_36k_train_033656
774
no_license
[ { "docstring": "Creates common instance variables from the parent class", "name": "__init__", "signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)" }, { "docstring": "Function to return appliance as a dictionary", "name": "return_as_dictiona...
2
stack_v2_sparse_classes_30k_train_015368
Implement the Python class `ElectricAppliances` described below. Class description: The ElectricAppliances class Method signatures and docstrings: - def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class - def return_as_dictio...
Implement the Python class `ElectricAppliances` described below. Class description: The ElectricAppliances class Method signatures and docstrings: - def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class - def return_as_dictio...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class ElectricAppliances: """The ElectricAppliances class""" def __init__(self, product_code, description, market_price, rental_price, brand, voltage): """Creates common instance variables from the parent class""" <|body_0|> def return_as_dictionary(self): """Function ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ElectricAppliances: """The ElectricAppliances class""" def __init__(self, product_code, description, market_price, rental_price, brand, voltage): """Creates common instance variables from the parent class""" Inventory.__init__(self, product_code, description, market_price, rental_price) ...
the_stack_v2_python_sparse
students/JoeNunnelley/lesson01/assignment/inventory_management/electric_appliances.py
JavaRod/SP_Python220B_2019
train
1
f8a4ff1c2a0a60d7076176ad48ccf853a5306034
[ "Action.__init__(self, p_game_state)\nassert isinstance(p_player_id, int)\nassert PLAYER_PER_TEAM >= p_player_id >= 0\nself.player_id = p_player_id", "ball_position = self.game_state.get_ball_position()\ndestination_orientation = get_angle(self.game_state.get_player_pose(self.player_id).position, ball_position)\n...
<|body_start_0|> Action.__init__(self, p_game_state) assert isinstance(p_player_id, int) assert PLAYER_PER_TEAM >= p_player_id >= 0 self.player_id = p_player_id <|end_body_0|> <|body_start_1|> ball_position = self.game_state.get_ball_position() destination_orientation = ...
Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur
GetBall
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetBall: """Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur""" def __init__(self, p_game_state, p_player_id): """:param p_game_stat...
stack_v2_sparse_classes_36k_train_033657
1,563
permissive
[ { "docstring": ":param p_game_state: L'état courant du jeu. :param p_player_id: Identifiant du joueur qui prend le contrôle de la balle", "name": "__init__", "signature": "def __init__(self, p_game_state, p_player_id)" }, { "docstring": "Place le robot afin qu'il prenne le contrôle de la balle :...
2
stack_v2_sparse_classes_30k_train_021666
Implement the Python class `GetBall` described below. Class description: Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur Method signatures and docstrings: - def __in...
Implement the Python class `GetBall` described below. Class description: Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur Method signatures and docstrings: - def __in...
7e20de8b2213d9b9b46be16d6b4800d767da1b00
<|skeleton|> class GetBall: """Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur""" def __init__(self, p_game_state, p_player_id): """:param p_game_stat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetBall: """Action GrabBall: Déplace le robot afin qu'il prenne contrôle de la balle Méthodes : exec(self): Retourne la pose où se rendre Attributs (en plus de ceux de Action): player_id : L'identifiant du joueur""" def __init__(self, p_game_state, p_player_id): """:param p_game_state: L'état cou...
the_stack_v2_python_sparse
ai/STA/Action/GetBall.py
etibuteau/StrategyIA
train
0
9e577d550f656c13397e58033de2cb5837c2b135
[ "wordset = set()\nabbr2cnt = {}\nfor word in dictionary:\n if len(word) > 2:\n abbr = word[0] + str(len(word) - 2) + word[-1]\n else:\n abbr = word\n if word not in wordset:\n abbr2cnt[abbr] = abbr2cnt.get(abbr, 0) + 1\n wordset.add(word)\nself.wordset = wordset\nself.abbr2cnt = abb...
<|body_start_0|> wordset = set() abbr2cnt = {} for word in dictionary: if len(word) > 2: abbr = word[0] + str(len(word) - 2) + word[-1] else: abbr = word if word not in wordset: abbr2cnt[abbr] = abbr2cnt.get(abbr...
ValidWordAbbr
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> wordset = set() abbr2cnt = {} for w...
stack_v2_sparse_classes_36k_train_033658
1,085
permissive
[ { "docstring": ":type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": ":type word: str :rtype: bool", "name": "isUnique", "signature": "def isUnique(self, word)" } ]
2
null
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool <|skeleton|> class ValidWordAbbr: def __init_...
bc0b01e44e121ea68724da16f25f7e24386c53de
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" wordset = set() abbr2cnt = {} for word in dictionary: if len(word) > 2: abbr = word[0] + str(len(word) - 2) + word[-1] else: abbr = word ...
the_stack_v2_python_sparse
leetcode/288-Unique-Word-Abbreviation/UniqueWordAbbr_001.py
cc13ny/all-in
train
2
14388c43e0808f12454f282c0f52bea3563b8e96
[ "log.info('Setup Section verifyProcessorDetails')\nhost_ip = classparam['host_ip']\nboot_order_obj = classparam['boot_order_obj']\nself.host_serial_handle = classparam['host_serial_handle']\nself.host_serial_handle.connect_to_host_serial()\nlog.info('Create boot device from CIMC config and boot from it')\nif boot_o...
<|body_start_0|> log.info('Setup Section verifyProcessorDetails') host_ip = classparam['host_ip'] boot_order_obj = classparam['boot_order_obj'] self.host_serial_handle = classparam['host_serial_handle'] self.host_serial_handle.connect_to_host_serial() log.info('Create boo...
Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it
CimcConfigIPMICmdPersistentBootDevice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CimcConfigIPMICmdPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" <|body_0|> def test(self, cimc_util_...
stack_v2_sparse_classes_36k_train_033659
19,363
no_license
[ { "docstring": "Test Case Setup", "name": "setup", "signature": "def setup(self, cimc_util_obj)" }, { "docstring": "ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode when cimc config set and booted from it", "name": "test", "signature": "def test(...
3
stack_v2_sparse_classes_30k_train_013611
Implement the Python class `CimcConfigIPMICmdPersistentBootDevice` described below. Class description: Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it Method signatures and docstrings: - def setup(self, cimc_util_obj): Test Case S...
Implement the Python class `CimcConfigIPMICmdPersistentBootDevice` described below. Class description: Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it Method signatures and docstrings: - def setup(self, cimc_util_obj): Test Case S...
c255e045a4950a0d8868a10012d5ce6e5c6a9c23
<|skeleton|> class CimcConfigIPMICmdPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" <|body_0|> def test(self, cimc_util_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CimcConfigIPMICmdPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy in persistent mode when boot device created using cimc config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" log.info('Setup Section verifyProcessorDetails') ...
the_stack_v2_python_sparse
ipmi_cmnd_bootorder.py
jrchanda/MyRepo
train
0
74a23e374f8cadac54c6258e7c91e3266f397841
[ "multipliers1 = standard_ops.constant([-0.1, -0.6, -0.3])\nexpected_projected_multipliers1 = np.array([0.0, 0.0, 0.0])\nmultipliers2 = standard_ops.constant([-0.1, 0.6, 0.3])\nexpected_projected_multipliers2 = np.array([0.0, 0.6, 0.3])\nmultipliers3 = standard_ops.constant([0.4, 0.7, -0.2, 0.5, 0.1])\nexpected_proj...
<|body_start_0|> multipliers1 = standard_ops.constant([-0.1, -0.6, -0.3]) expected_projected_multipliers1 = np.array([0.0, 0.0, 0.0]) multipliers2 = standard_ops.constant([-0.1, 0.6, 0.3]) expected_projected_multipliers2 = np.array([0.0, 0.6, 0.3]) multipliers3 = standard_ops.con...
ExternalRegretOptimizerTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExternalRegretOptimizerTest: def test_project_multipliers_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" <|body_0|> def test_additive_external_regret_optimizer(self): """Tests that the Lagrange multipliers update as expected....
stack_v2_sparse_classes_36k_train_033660
5,162
permissive
[ { "docstring": "Tests Euclidean projection routine on some known values.", "name": "test_project_multipliers_wrt_euclidean_norm", "signature": "def test_project_multipliers_wrt_euclidean_norm(self)" }, { "docstring": "Tests that the Lagrange multipliers update as expected.", "name": "test_ad...
2
null
Implement the Python class `ExternalRegretOptimizerTest` described below. Class description: Implement the ExternalRegretOptimizerTest class. Method signatures and docstrings: - def test_project_multipliers_wrt_euclidean_norm(self): Tests Euclidean projection routine on some known values. - def test_additive_external...
Implement the Python class `ExternalRegretOptimizerTest` described below. Class description: Implement the ExternalRegretOptimizerTest class. Method signatures and docstrings: - def test_project_multipliers_wrt_euclidean_norm(self): Tests Euclidean projection routine on some known values. - def test_additive_external...
181bc2b37aa8a3eeb11a942d8f330b04abc804b3
<|skeleton|> class ExternalRegretOptimizerTest: def test_project_multipliers_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" <|body_0|> def test_additive_external_regret_optimizer(self): """Tests that the Lagrange multipliers update as expected....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExternalRegretOptimizerTest: def test_project_multipliers_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" multipliers1 = standard_ops.constant([-0.1, -0.6, -0.3]) expected_projected_multipliers1 = np.array([0.0, 0.0, 0.0]) multipliers2 =...
the_stack_v2_python_sparse
tensorflow/tensorflow/contrib/constrained_optimization/python/external_regret_optimizer_test.py
zylo117/tensorflow-gpu-macosx
train
116
841410261ea7c210a8f8ff63fa62aafa172f3b8d
[ "if not height:\n return 0\nmax_right = [height[-1]]\nrheight = reversed(height)\nnext(rheight)\nfor i, h in enumerate(rheight):\n max_right.append(max(max_right[i], h))\nmax_right.reverse()\nmax_left = [height[0]]\nfor i, h in enumerate(height[1:]):\n max_left.append(max(max_left[i], h))\ns = 0\nfor h, l,...
<|body_start_0|> if not height: return 0 max_right = [height[-1]] rheight = reversed(height) next(rheight) for i, h in enumerate(rheight): max_right.append(max(max_right[i], h)) max_right.reverse() max_left = [height[0]] for i, h in...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def trap(self, height): """08/06/2018 02:27""" <|body_0|> def trap(self, height: List[int]) -> int: """Time complexity: O(n) Space complexity: O(n)""" <|body_1|> def trap(self, height: List[int]) -> int: """Time complexity: O(n) Space c...
stack_v2_sparse_classes_36k_train_033661
3,861
no_license
[ { "docstring": "08/06/2018 02:27", "name": "trap", "signature": "def trap(self, height)" }, { "docstring": "Time complexity: O(n) Space complexity: O(n)", "name": "trap", "signature": "def trap(self, height: List[int]) -> int" }, { "docstring": "Time complexity: O(n) Space comple...
4
stack_v2_sparse_classes_30k_train_002582
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): 08/06/2018 02:27 - def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(n) - def trap(self, height: List[int]) -> int: Time...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): 08/06/2018 02:27 - def trap(self, height: List[int]) -> int: Time complexity: O(n) Space complexity: O(n) - def trap(self, height: List[int]) -> int: Time...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def trap(self, height): """08/06/2018 02:27""" <|body_0|> def trap(self, height: List[int]) -> int: """Time complexity: O(n) Space complexity: O(n)""" <|body_1|> def trap(self, height: List[int]) -> int: """Time complexity: O(n) Space c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def trap(self, height): """08/06/2018 02:27""" if not height: return 0 max_right = [height[-1]] rheight = reversed(height) next(rheight) for i, h in enumerate(rheight): max_right.append(max(max_right[i], h)) max_right.re...
the_stack_v2_python_sparse
leetcode/solved/42_Trapping_Rain_Water/solution.py
sungminoh/algorithms
train
0
4c308c06c751e5f143037c31c71b45ff8c37d022
[ "array = self.format_and_eval_string(self.target_array)\nif self.column_name:\n array = array[self.column_name]\nif self.mode == 'Max' or self.mode == 'Max & min':\n ind = np.argmax(array)\n val = array[ind]\n self.write_in_database('max_ind', ind)\n self.write_in_database('max_value', val)\nif self....
<|body_start_0|> array = self.format_and_eval_string(self.target_array) if self.column_name: array = array[self.column_name] if self.mode == 'Max' or self.mode == 'Max & min': ind = np.argmax(array) val = array[ind] self.write_in_database('max_ind'...
Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.
ArrayExtremaTask
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArrayExtremaTask: """Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.""" def perform(self): """Find extrema of database array and store index/value pairs.""" <|body_0|> def check(self, *args, **kwargs): ...
stack_v2_sparse_classes_36k_train_033662
6,289
permissive
[ { "docstring": "Find extrema of database array and store index/value pairs.", "name": "perform", "signature": "def perform(self)" }, { "docstring": "Check the target array can be found and has the right column.", "name": "check", "signature": "def check(self, *args, **kwargs)" }, { ...
3
stack_v2_sparse_classes_30k_train_010510
Implement the Python class `ArrayExtremaTask` described below. Class description: Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution. Method signatures and docstrings: - def perform(self): Find extrema of database array and store index/value pairs. - def ...
Implement the Python class `ArrayExtremaTask` described below. Class description: Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution. Method signatures and docstrings: - def perform(self): Find extrema of database array and store index/value pairs. - def ...
b6f1f5b236c7a4e28d9a3bc8da9820c52d789309
<|skeleton|> class ArrayExtremaTask: """Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.""" def perform(self): """Find extrema of database array and store index/value pairs.""" <|body_0|> def check(self, *args, **kwargs): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArrayExtremaTask: """Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before execution.""" def perform(self): """Find extrema of database array and store index/value pairs.""" array = self.format_and_eval_string(self.target_array) if...
the_stack_v2_python_sparse
exopy_hqc_legacy/tasks/tasks/util/array_tasks.py
Exopy/exopy_hqc_legacy
train
0
c20cf7df1dd74892db6cac5698b0ac339e9c016d
[ "self.height = height\nself.width = width\nself.channels = channels\nself.discount = discount\nself.actions = actions\nself.env = env\nself.loss = loss\nself.epoch_num = 0\nself.model_dir = model_dir\nself.max_reward = 0\nself.cur_reward = 0\nself.reward_tensor = K.variable(value=0)\nif model_dir is not None:\n ...
<|body_start_0|> self.height = height self.width = width self.channels = channels self.discount = discount self.actions = actions self.env = env self.loss = loss self.epoch_num = 0 self.model_dir = model_dir self.max_reward = 0 self...
Agent object which initalizes and trains the keras model.
Agent
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Agent: """Agent object which initalizes and trains the keras model.""" def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): """Initializes the parameters of the model. Args: height: Height of the image width: Wi...
stack_v2_sparse_classes_36k_train_033663
7,927
permissive
[ { "docstring": "Initializes the parameters of the model. Args: height: Height of the image width: Width of the image channels: Number of channels, history of past frame discount: Discount_Factor for Q Learning update", "name": "__init__", "signature": "def __init__(self, actions, height=80, width=80, ch...
5
stack_v2_sparse_classes_30k_train_019356
Implement the Python class `Agent` described below. Class description: Agent object which initalizes and trains the keras model. Method signatures and docstrings: - def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): Initializes the parameters ...
Implement the Python class `Agent` described below. Class description: Agent object which initalizes and trains the keras model. Method signatures and docstrings: - def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): Initializes the parameters ...
975a95032ce5b7012d1772c7f1f5cfe606eae839
<|skeleton|> class Agent: """Agent object which initalizes and trains the keras model.""" def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): """Initializes the parameters of the model. Args: height: Height of the image width: Wi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Agent: """Agent object which initalizes and trains the keras model.""" def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): """Initializes the parameters of the model. Args: height: Height of the image width: Width of the im...
the_stack_v2_python_sparse
blogs/rl-on-gcp/DQN_Breakout/rl_on_gcp/trainer/model.py
GoogleCloudPlatform/training-data-analyst
train
7,311
c7392549187a3a036e0deb565569e3ba1db82d07
[ "vals = []\n\ndef write(node):\n nonlocal vals\n if node:\n vals += [str(node.val)]\n write(node.left)\n write(node.right)\n else:\n vals += ['#']\nwrite(root)\nreturn ' '.join(vals)", "vals = iter(data.split())\n\ndef read():\n val = next(vals)\n if val == '#':\n ...
<|body_start_0|> vals = [] def write(node): nonlocal vals if node: vals += [str(node.val)] write(node.left) write(node.right) else: vals += ['#'] write(root) return ' '.join(vals) <|end_b...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: 'TreeNode') -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> vals = [] ...
stack_v2_sparse_classes_36k_train_033664
1,148
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: 'TreeNode') -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'TreeNode') -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'TreeNode') -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class ...
9164c21ab011c90944f844e3c359093ce6180223
<|skeleton|> class Codec: def serialize(self, root: 'TreeNode') -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: 'TreeNode') -> str: """Encodes a tree to a single string.""" vals = [] def write(node): nonlocal vals if node: vals += [str(node.val)] write(node.left) write(node.right) ...
the_stack_v2_python_sparse
Serialize and Deserialize Binary Tree/Leetode_297.py
arw2019/AlgorithmsDataStructures
train
0
1986a0baa827cb90f99620b9715fd632a0cddc1a
[ "self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]", "while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n y_distance = choice([0, 1, 2, 3, 4])\n ...
<|body_start_0|> self.num_points = num_points self.x_values = [0] self.y_values = [0] <|end_body_0|> <|body_start_1|> while len(self.x_values) < self.num_points: x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction *...
" 生成随机漫步数据的属性
RandomWalk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomWalk: """" 生成随机漫步数据的属性""" def __init__(self, num_points=10000): """初始化随机漫步的属性""" <|body_0|> def fill_walk(self): """"计算随机漫步所要经过的所有点""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.num_points = num_points self.x_values = [0] ...
stack_v2_sparse_classes_36k_train_033665
1,301
no_license
[ { "docstring": "初始化随机漫步的属性", "name": "__init__", "signature": "def __init__(self, num_points=10000)" }, { "docstring": "\"计算随机漫步所要经过的所有点", "name": "fill_walk", "signature": "def fill_walk(self)" } ]
2
stack_v2_sparse_classes_30k_test_000562
Implement the Python class `RandomWalk` described below. Class description: " 生成随机漫步数据的属性 Method signatures and docstrings: - def __init__(self, num_points=10000): 初始化随机漫步的属性 - def fill_walk(self): "计算随机漫步所要经过的所有点
Implement the Python class `RandomWalk` described below. Class description: " 生成随机漫步数据的属性 Method signatures and docstrings: - def __init__(self, num_points=10000): 初始化随机漫步的属性 - def fill_walk(self): "计算随机漫步所要经过的所有点 <|skeleton|> class RandomWalk: """" 生成随机漫步数据的属性""" def __init__(self, num_points=10000): ...
cdf5622f1ac6dc8e6b206b13aa3ef4cd3a6654b0
<|skeleton|> class RandomWalk: """" 生成随机漫步数据的属性""" def __init__(self, num_points=10000): """初始化随机漫步的属性""" <|body_0|> def fill_walk(self): """"计算随机漫步所要经过的所有点""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomWalk: """" 生成随机漫步数据的属性""" def __init__(self, num_points=10000): """初始化随机漫步的属性""" self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): """"计算随机漫步所要经过的所有点""" while len(self.x_values) < self.num_points: ...
the_stack_v2_python_sparse
s_可视化/matplotlib_test/random_walk.py
qiuyunzhao/python_basis
train
1
6544b630174ec46621b87b7fff5e3fddeef21266
[ "url = self.trimUrlPrefix(urlTrait.url)\nif url and self.isTnsStyle(url):\n EMPTY = OracleTnsRecordParser.EMPTY\n obj = OracleTnsRecordParser().parse(url)\n uniqueHostCount = self._countUniqueHosts(obj)\n description = self._getDescription(obj)\n serviceName = description.connect_data.service_name\n ...
<|body_start_0|> url = self.trimUrlPrefix(urlTrait.url) if url and self.isTnsStyle(url): EMPTY = OracleTnsRecordParser.EMPTY obj = OracleTnsRecordParser().parse(url) uniqueHostCount = self._countUniqueHosts(obj) description = self._getDescription(obj) ...
OracleThinHasSidCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OracleThinHasSidCase: def isApplicableUrlTrait(self, urlTrait): """@types: jdbc_url_parser.Trait -> bool""" <|body_0|> def parse(self, url): """@types: str -> tuple[db.DatabaseServer]""" <|body_1|> <|end_skeleton|> <|body_start_0|> url = self.trimUr...
stack_v2_sparse_classes_36k_train_033666
40,819
no_license
[ { "docstring": "@types: jdbc_url_parser.Trait -> bool", "name": "isApplicableUrlTrait", "signature": "def isApplicableUrlTrait(self, urlTrait)" }, { "docstring": "@types: str -> tuple[db.DatabaseServer]", "name": "parse", "signature": "def parse(self, url)" } ]
2
stack_v2_sparse_classes_30k_train_013216
Implement the Python class `OracleThinHasSidCase` described below. Class description: Implement the OracleThinHasSidCase class. Method signatures and docstrings: - def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool - def parse(self, url): @types: str -> tuple[db.DatabaseServer]
Implement the Python class `OracleThinHasSidCase` described below. Class description: Implement the OracleThinHasSidCase class. Method signatures and docstrings: - def isApplicableUrlTrait(self, urlTrait): @types: jdbc_url_parser.Trait -> bool - def parse(self, url): @types: str -> tuple[db.DatabaseServer] <|skeleto...
c431e809e8d0f82e1bca7e3429dd0245560b5680
<|skeleton|> class OracleThinHasSidCase: def isApplicableUrlTrait(self, urlTrait): """@types: jdbc_url_parser.Trait -> bool""" <|body_0|> def parse(self, url): """@types: str -> tuple[db.DatabaseServer]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OracleThinHasSidCase: def isApplicableUrlTrait(self, urlTrait): """@types: jdbc_url_parser.Trait -> bool""" url = self.trimUrlPrefix(urlTrait.url) if url and self.isTnsStyle(url): EMPTY = OracleTnsRecordParser.EMPTY obj = OracleTnsRecordParser().parse(url) ...
the_stack_v2_python_sparse
reference/ucmdb/discovery/jdbc_url_parser.py
madmonkyang/cda-record
train
0
44d0c477bd158ce335ad3b76288a4cbeaf895e71
[ "super().__init__()\nself.data_set_loc = conf.config_section_mapper('filePath').get('data_set_loc')\nself.data_extractor = DataExtractor(self.data_set_loc)\nactor_actor_matrix_obj.fetchActorActorSimilarityMatrix()", "actor_movie_table = self.data_extractor.get_movie_actor_data()\nmovieid = util.get_movie_id(movie...
<|body_start_0|> super().__init__() self.data_set_loc = conf.config_section_mapper('filePath').get('data_set_loc') self.data_extractor = DataExtractor(self.data_set_loc) actor_actor_matrix_obj.fetchActorActorSimilarityMatrix() <|end_body_0|> <|body_start_1|> actor_movie_table = ...
SimilarActorsFromDiffMovies
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimilarActorsFromDiffMovies: def __init__(self): """Initialiazing the data extractor object to get data from the csv files""" <|body_0|> def get_actors_of_movie(self, moviename): """Function to return the actors of a given movie :param moviename: :return: list(actori...
stack_v2_sparse_classes_36k_train_033667
13,912
no_license
[ { "docstring": "Initialiazing the data extractor object to get data from the csv files", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Function to return the actors of a given movie :param moviename: :return: list(actorids)", "name": "get_actors_of_movie", "sig...
5
stack_v2_sparse_classes_30k_train_017235
Implement the Python class `SimilarActorsFromDiffMovies` described below. Class description: Implement the SimilarActorsFromDiffMovies class. Method signatures and docstrings: - def __init__(self): Initialiazing the data extractor object to get data from the csv files - def get_actors_of_movie(self, moviename): Funct...
Implement the Python class `SimilarActorsFromDiffMovies` described below. Class description: Implement the SimilarActorsFromDiffMovies class. Method signatures and docstrings: - def __init__(self): Initialiazing the data extractor object to get data from the csv files - def get_actors_of_movie(self, moviename): Funct...
58c4e8fe6674a03d470b3dcada9255f137cbbf0c
<|skeleton|> class SimilarActorsFromDiffMovies: def __init__(self): """Initialiazing the data extractor object to get data from the csv files""" <|body_0|> def get_actors_of_movie(self, moviename): """Function to return the actors of a given movie :param moviename: :return: list(actori...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimilarActorsFromDiffMovies: def __init__(self): """Initialiazing the data extractor object to get data from the csv files""" super().__init__() self.data_set_loc = conf.config_section_mapper('filePath').get('data_set_loc') self.data_extractor = DataExtractor(self.data_set_loc)...
the_stack_v2_python_sparse
phase_2/scripts/phase_2_task_1d.py
abhijithshreesh/MovieRecommenderSystem
train
0
eb5a3d1ef291a7fb31526610ba6d5a92dc0d3f84
[ "self.np_shape = params['shape'][::-1]\nself.np_dtype = params['dtype']\nself.seed = params['seed']\nself.rng = np.random.default_rng(self.seed)", "probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY]\nrandom_flips = self.rng.choice([0, 1], p=probabilities, size=self.np_shape)\nrandom_flip...
<|body_start_0|> self.np_shape = params['shape'][::-1] self.np_dtype = params['dtype'] self.seed = params['seed'] self.rng = np.random.default_rng(self.seed) <|end_body_0|> <|body_start_1|> probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY] rand...
Class to randomly generate input for RandomFlip media node.
RandomFlipFunction
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomFlipFunction: """Class to randomly generate input for RandomFlip media node.""" def __init__(self, params): """:params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used""" <|body_0|> def __call__(self): ...
stack_v2_sparse_classes_36k_train_033668
7,309
permissive
[ { "docstring": ":params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used", "name": "__init__", "signature": "def __init__(self, params)" }, { "docstring": ":returns : randomly generated binary output per image.", "name": "__call__", ...
2
stack_v2_sparse_classes_30k_train_013090
Implement the Python class `RandomFlipFunction` described below. Class description: Class to randomly generate input for RandomFlip media node. Method signatures and docstrings: - def __init__(self, params): :params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be...
Implement the Python class `RandomFlipFunction` described below. Class description: Class to randomly generate input for RandomFlip media node. Method signatures and docstrings: - def __init__(self, params): :params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be...
3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212
<|skeleton|> class RandomFlipFunction: """Class to randomly generate input for RandomFlip media node.""" def __init__(self, params): """:params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used""" <|body_0|> def __call__(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomFlipFunction: """Class to randomly generate input for RandomFlip media node.""" def __init__(self, params): """:params params: random_flip_func specific params. shape: output shape dtype: output data type seed: seed to be used""" self.np_shape = params['shape'][::-1] self.np...
the_stack_v2_python_sparse
PyTorch/computer_vision/classification/torchvision/resnet_media_pipe.py
HabanaAI/Model-References
train
108
7576878efced270a4ccd33431e7197a34cd2a522
[ "self.finalized = finalized\nself.paused = paused\nself.previous_view_name = previous_view_name", "if dictionary is None:\n return None\nfinalized = dictionary.get('finalized')\npaused = dictionary.get('paused')\nprevious_view_name = dictionary.get('previousViewName')\nreturn cls(finalized, paused, previous_vi...
<|body_start_0|> self.finalized = finalized self.paused = paused self.previous_view_name = previous_view_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None finalized = dictionary.get('finalized') paused = dictionary.get('paused') ...
Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.
MirrorParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MirrorParams: """Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.""" def __init__(self, finalized=None, paused...
stack_v2_sparse_classes_36k_train_033669
1,797
permissive
[ { "docstring": "Constructor for the MirrorParams class", "name": "__init__", "signature": "def __init__(self, finalized=None, paused=None, previous_view_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o...
2
stack_v2_sparse_classes_30k_train_013018
Implement the Python class `MirrorParams` described below. Class description: Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view. Method si...
Implement the Python class `MirrorParams` described below. Class description: Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view. Method si...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class MirrorParams: """Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.""" def __init__(self, finalized=None, paused...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MirrorParams: """Implementation of the 'MirrorParams' model. TODO: type description here. Attributes: finalized (bool): TODO: Type description here. paused (bool): Is mirroring paused. previous_view_name (string): View to be used as previous view.""" def __init__(self, finalized=None, paused=None, previo...
the_stack_v2_python_sparse
cohesity_management_sdk/models/mirror_params.py
cohesity/management-sdk-python
train
24
dfb96c3c07017a42aea7473cc2d32707d624d33b
[ "num = number\nif num == 2:\n return 1\nelif num == 3:\n return 2\nmod = num % 3\nzhen = num // 3\nif mod == 0:\n return pow(3, zhen)\nelif mod == 1:\n return 2 * 2 * pow(3, zhen - 1)\nelse:\n return 2 * pow(3, zhen)", "if number < 2:\n return 0\nelif number == 2:\n return 1\nelif number == 3...
<|body_start_0|> num = number if num == 2: return 1 elif num == 3: return 2 mod = num % 3 zhen = num // 3 if mod == 0: return pow(3, zhen) elif mod == 1: return 2 * 2 * pow(3, zhen - 1) else: retu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def cutRope(self, number): """贪心解法""" <|body_0|> def cutRope1(self, number): """动态规划解法""" <|body_1|> <|end_skeleton|> <|body_start_0|> num = number if num == 2: return 1 elif num == 3: return 2 ...
stack_v2_sparse_classes_36k_train_033670
984
no_license
[ { "docstring": "贪心解法", "name": "cutRope", "signature": "def cutRope(self, number)" }, { "docstring": "动态规划解法", "name": "cutRope1", "signature": "def cutRope1(self, number)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def cutRope(self, number): 贪心解法 - def cutRope1(self, number): 动态规划解法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def cutRope(self, number): 贪心解法 - def cutRope1(self, number): 动态规划解法 <|skeleton|> class Solution: def cutRope(self, number): """贪心解法""" <|body_0|> def ...
199f2b62101480b963e776c07c275b789c20a413
<|skeleton|> class Solution: def cutRope(self, number): """贪心解法""" <|body_0|> def cutRope1(self, number): """动态规划解法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def cutRope(self, number): """贪心解法""" num = number if num == 2: return 1 elif num == 3: return 2 mod = num % 3 zhen = num // 3 if mod == 0: return pow(3, zhen) elif mod == 1: return 2 * 2 ...
the_stack_v2_python_sparse
niuke/剪绳子.py
w5802021/leet_niuke
train
2
befb436057ad16c36ba0877c52f027d797c0dbaa
[ "user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(creator=username, updated_by=username)", "user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(updated_by=username)" ]
<|body_start_0|> user = serializer.context.get('request').user username = getattr(user, 'username', 'guest') serializer.save(creator=username, updated_by=username) <|end_body_0|> <|body_start_1|> user = serializer.context.get('request').user username = getattr(user, 'username', ...
按需改造DRF默认的ModelViewSet类
ModelViewSet
[ "MIT", "LGPL-2.1-or-later", "LGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelViewSet: """按需改造DRF默认的ModelViewSet类""" def perform_create(self, serializer): """创建时补充基础Model中的字段""" <|body_0|> def perform_update(self, serializer): """更新时补充基础Model中的字段""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = serializer.conte...
stack_v2_sparse_classes_36k_train_033671
9,093
permissive
[ { "docstring": "创建时补充基础Model中的字段", "name": "perform_create", "signature": "def perform_create(self, serializer)" }, { "docstring": "更新时补充基础Model中的字段", "name": "perform_update", "signature": "def perform_update(self, serializer)" } ]
2
stack_v2_sparse_classes_30k_train_006964
Implement the Python class `ModelViewSet` described below. Class description: 按需改造DRF默认的ModelViewSet类 Method signatures and docstrings: - def perform_create(self, serializer): 创建时补充基础Model中的字段 - def perform_update(self, serializer): 更新时补充基础Model中的字段
Implement the Python class `ModelViewSet` described below. Class description: 按需改造DRF默认的ModelViewSet类 Method signatures and docstrings: - def perform_create(self, serializer): 创建时补充基础Model中的字段 - def perform_update(self, serializer): 更新时补充基础Model中的字段 <|skeleton|> class ModelViewSet: """按需改造DRF默认的ModelViewSet类""" ...
2d708bd0d869d391456e0fb8d644af3b9f031acf
<|skeleton|> class ModelViewSet: """按需改造DRF默认的ModelViewSet类""" def perform_create(self, serializer): """创建时补充基础Model中的字段""" <|body_0|> def perform_update(self, serializer): """更新时补充基础Model中的字段""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelViewSet: """按需改造DRF默认的ModelViewSet类""" def perform_create(self, serializer): """创建时补充基础Model中的字段""" user = serializer.context.get('request').user username = getattr(user, 'username', 'guest') serializer.save(creator=username, updated_by=username) def perform_upda...
the_stack_v2_python_sparse
itsm/iadmin/views.py
TencentBlueKing/bk-itsm
train
100
e4aac5a626b90c096618d91e89663a6019c9bc4c
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SecurityResource()", "from .security_resource_type import SecurityResourceType\nfrom .security_resource_type import SecurityResourceType\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return SecurityResource() <|end_body_0|> <|body_start_1|> from .security_resource_type import SecurityResourceType from .security_resource_type import SecurityResourceType fields: Dict[...
SecurityResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R...
stack_v2_sparse_classes_36k_train_033672
3,039
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SecurityResource", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_va...
3
stack_v2_sparse_classes_30k_train_007471
Implement the Python class `SecurityResource` described below. Class description: Implement the SecurityResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: Creates a new instance of the appropriate class based on discrimina...
Implement the Python class `SecurityResource` described below. Class description: Implement the SecurityResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: Creates a new instance of the appropriate class based on discrimina...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Securi...
the_stack_v2_python_sparse
msgraph/generated/models/security_resource.py
microsoftgraph/msgraph-sdk-python
train
135
c6ede396fad99534e4d0a7f6161c53c2b2640c5d
[ "super(Actor, self).__init__()\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.action_lim = action_lim\nself.hidden = 128\nself.usecuda = usecuda\nself.rnn = nn.LSTMCell(self.state_dim, self.hidden, bias=True)\nself.fc1 = nn.Linear(self.hidden, action_dim)\nself.fc1.weight.data.uniform_(-EPS, EPS)\n...
<|body_start_0|> super(Actor, self).__init__() self.state_dim = state_dim self.action_dim = action_dim self.action_lim = action_lim self.hidden = 128 self.usecuda = usecuda self.rnn = nn.LSTMCell(self.state_dim, self.hidden, bias=True) self.fc1 = nn.Linear...
Actor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Actor: def __init__(self, state_dim, action_dim, action_lim, usecuda=False): """Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of output action. :type action_dim: int. :param action_lim: Used to limi...
stack_v2_sparse_classes_36k_train_033673
3,704
permissive
[ { "docstring": "Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of output action. :type action_dim: int. :param action_lim: Used to limit action. :type action_lim: float. :return:", "name": "__init__", "signature": "...
3
stack_v2_sparse_classes_30k_train_018527
Implement the Python class `Actor` described below. Class description: Implement the Actor class. Method signatures and docstrings: - def __init__(self, state_dim, action_dim, action_lim, usecuda=False): Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param ...
Implement the Python class `Actor` described below. Class description: Implement the Actor class. Method signatures and docstrings: - def __init__(self, state_dim, action_dim, action_lim, usecuda=False): Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param ...
a02bdb1754e9bae1c2448e4bccec795c739b3e6f
<|skeleton|> class Actor: def __init__(self, state_dim, action_dim, action_lim, usecuda=False): """Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of output action. :type action_dim: int. :param action_lim: Used to limi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Actor: def __init__(self, state_dim, action_dim, action_lim, usecuda=False): """Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of output action. :type action_dim: int. :param action_lim: Used to limit action. :typ...
the_stack_v2_python_sparse
notebook/njord-ddpg/model.py
LUOFENGZHOU/njord
train
0
442b6cfa1a9cf18acc2f172b4e8b762538b00071
[ "assert len(ids) == 1, 'This option should only be used for a single id at a time.'\nir_model_data = self.pool.get('ir.model.data')\nres = {}\npicking = self.browse(cr, uid, ids[0])\ntry:\n template_id = ir_model_data.get_object_reference(cr, uid, 'openforce_sale', 'openforce_ddt_email_template')[1]\nexcept Valu...
<|body_start_0|> assert len(ids) == 1, 'This option should only be used for a single id at a time.' ir_model_data = self.pool.get('ir.model.data') res = {} picking = self.browse(cr, uid, ids[0]) try: template_id = ir_model_data.get_object_reference(cr, uid, 'openforce...
stock_picking_out
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class stock_picking_out: def action_ddt_sent(self, cr, uid, ids, context=None): """This function opens a window to compose an email, with the edi invoice template message loaded by default""" <|body_0|> def _total_amount(self, cr, uid, ids, name, args, context=None): """Co...
stack_v2_sparse_classes_36k_train_033674
10,203
no_license
[ { "docstring": "This function opens a window to compose an email, with the edi invoice template message loaded by default", "name": "action_ddt_sent", "signature": "def action_ddt_sent(self, cr, uid, ids, context=None)" }, { "docstring": "Compute the attendances, analytic lines timesheets and di...
2
stack_v2_sparse_classes_30k_train_007715
Implement the Python class `stock_picking_out` described below. Class description: Implement the stock_picking_out class. Method signatures and docstrings: - def action_ddt_sent(self, cr, uid, ids, context=None): This function opens a window to compose an email, with the edi invoice template message loaded by default...
Implement the Python class `stock_picking_out` described below. Class description: Implement the stock_picking_out class. Method signatures and docstrings: - def action_ddt_sent(self, cr, uid, ids, context=None): This function opens a window to compose an email, with the edi invoice template message loaded by default...
78fc164679b690bcf84866987266838de134bc2f
<|skeleton|> class stock_picking_out: def action_ddt_sent(self, cr, uid, ids, context=None): """This function opens a window to compose an email, with the edi invoice template message loaded by default""" <|body_0|> def _total_amount(self, cr, uid, ids, name, args, context=None): """Co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class stock_picking_out: def action_ddt_sent(self, cr, uid, ids, context=None): """This function opens a window to compose an email, with the edi invoice template message loaded by default""" assert len(ids) == 1, 'This option should only be used for a single id at a time.' ir_model_data = s...
the_stack_v2_python_sparse
openforce_sale/stock/picking.py
alessandrocamilli/7-openforce-addons
train
1
04cb792a5a691680b51aade12fc785ce14ba477b
[ "ObjectManager.__init__(self)\nself.getters.update({'instructor_managers': 'get_many_to_many', 'instructors': 'get_many_to_many', 'managers': 'get_many_to_many', 'name': 'get_general'})\nself.setters.update({'instructor_managers': 'set_many', 'instructors': 'set_many', 'managers': 'set_many', 'name': 'set_general'}...
<|body_start_0|> ObjectManager.__init__(self) self.getters.update({'instructor_managers': 'get_many_to_many', 'instructors': 'get_many_to_many', 'managers': 'get_many_to_many', 'name': 'get_general'}) self.setters.update({'instructor_managers': 'set_many', 'instructors': 'set_many', 'managers': ...
Manage ProductLines in the Power Reg system
ProductLineManager
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductLineManager: """Manage ProductLines in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, name): """Create a new ProductLine @param name name of the ProductLine @return a reference to the newly created Pro...
stack_v2_sparse_classes_36k_train_033675
1,395
permissive
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Create a new ProductLine @param name name of the ProductLine @return a reference to the newly created ProductLine", "name": "create", "signature": "def create(self, auth_token, name)" ...
2
null
Implement the Python class `ProductLineManager` described below. Class description: Manage ProductLines in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, name): Create a new ProductLine @param name name of the ProductLine @return a reference to ...
Implement the Python class `ProductLineManager` described below. Class description: Manage ProductLines in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, name): Create a new ProductLine @param name name of the ProductLine @return a reference to ...
a59457bc37f0501aea1f54d006a6de94ff80511c
<|skeleton|> class ProductLineManager: """Manage ProductLines in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, name): """Create a new ProductLine @param name name of the ProductLine @return a reference to the newly created Pro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductLineManager: """Manage ProductLines in the Power Reg system""" def __init__(self): """constructor""" ObjectManager.__init__(self) self.getters.update({'instructor_managers': 'get_many_to_many', 'instructors': 'get_many_to_many', 'managers': 'get_many_to_many', 'name': 'get_...
the_stack_v2_python_sparse
pr_services/product_system/product_line_manager.py
ninemoreminutes/openassign-server
train
0
f463be88b853bbd18d79428e0b26cc2b489eba14
[ "self.k = k\nself.arr = nums\nself.arr.sort()\nwhile len(self.arr) > self.k:\n self.arr.pop(0)", "self.arr.append(val)\nself.arr.sort()\nif len(self.arr) > self.k:\n self.arr.pop(0)\nreturn self.arr[0]" ]
<|body_start_0|> self.k = k self.arr = nums self.arr.sort() while len(self.arr) > self.k: self.arr.pop(0) <|end_body_0|> <|body_start_1|> self.arr.append(val) self.arr.sort() if len(self.arr) > self.k: self.arr.pop(0) return self.a...
KthLargest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.k = k self.arr = nums self.arr.sort()...
stack_v2_sparse_classes_36k_train_033676
630
no_license
[ { "docstring": ":type k: int :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, k, nums)" }, { "docstring": ":type val: int :rtype: int", "name": "add", "signature": "def add(self, val)" } ]
2
stack_v2_sparse_classes_30k_train_006875
Implement the Python class `KthLargest` described below. Class description: Implement the KthLargest class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int
Implement the Python class `KthLargest` described below. Class description: Implement the KthLargest class. Method signatures and docstrings: - def __init__(self, k, nums): :type k: int :type nums: List[int] - def add(self, val): :type val: int :rtype: int <|skeleton|> class KthLargest: def __init__(self, k, nu...
920b65db80031fad45d495431eda8d3fb4ef06e5
<|skeleton|> class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" <|body_0|> def add(self, val): """:type val: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KthLargest: def __init__(self, k, nums): """:type k: int :type nums: List[int]""" self.k = k self.arr = nums self.arr.sort() while len(self.arr) > self.k: self.arr.pop(0) def add(self, val): """:type val: int :rtype: int""" self.arr.appe...
the_stack_v2_python_sparse
easy/ex703.py
ziyuan-shen/leetcode_algorithm_python_solution
train
2
7c1e707daaacaa43e592c2c8d1d2a0b64e6401e0
[ "for pin in self.pins:\n for dot in self.dots:\n distance = pin - dot\n if dot.distance == math.inf:\n dot.distance = distance\n else:\n dot.distance += distance", "total = 0\nself.calc_sum_distances()\nfor dot in self.dots:\n if dot.distance < limit:\n tota...
<|body_start_0|> for pin in self.pins: for dot in self.dots: distance = pin - dot if dot.distance == math.inf: dot.distance = distance else: dot.distance += distance <|end_body_0|> <|body_start_1|> total...
A gird of time dots with pins.
Grid
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Grid: """A gird of time dots with pins.""" def calc_sum_distances(self) -> None: """Get sum of pin distances for each dot.""" <|body_0|> def closest_region_size(self, limit: int=10000) -> int: """Get number of dots with distance less than limit.""" <|body...
stack_v2_sparse_classes_36k_train_033677
1,033
permissive
[ { "docstring": "Get sum of pin distances for each dot.", "name": "calc_sum_distances", "signature": "def calc_sum_distances(self) -> None" }, { "docstring": "Get number of dots with distance less than limit.", "name": "closest_region_size", "signature": "def closest_region_size(self, lim...
2
null
Implement the Python class `Grid` described below. Class description: A gird of time dots with pins. Method signatures and docstrings: - def calc_sum_distances(self) -> None: Get sum of pin distances for each dot. - def closest_region_size(self, limit: int=10000) -> int: Get number of dots with distance less than lim...
Implement the Python class `Grid` described below. Class description: A gird of time dots with pins. Method signatures and docstrings: - def calc_sum_distances(self) -> None: Get sum of pin distances for each dot. - def closest_region_size(self, limit: int=10000) -> int: Get number of dots with distance less than lim...
4b8ac6a97859b1320f77ba0ee91168b58db28cdb
<|skeleton|> class Grid: """A gird of time dots with pins.""" def calc_sum_distances(self) -> None: """Get sum of pin distances for each dot.""" <|body_0|> def closest_region_size(self, limit: int=10000) -> int: """Get number of dots with distance less than limit.""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Grid: """A gird of time dots with pins.""" def calc_sum_distances(self) -> None: """Get sum of pin distances for each dot.""" for pin in self.pins: for dot in self.dots: distance = pin - dot if dot.distance == math.inf: dot.d...
the_stack_v2_python_sparse
src/year2018/day06b.py
lancelote/advent_of_code
train
11
b8085e32ad98e118385c84c815237af2ff92b8e1
[ "if not root:\n return None\nbinary = TreeNode(root.val)\nif not root.children:\n return binary\nbinary.left = self.encode(root.children[0])\nnode = binary.left\nfor child in root.children[1:]:\n node.right = self.encode(child)\n node = node.right\nreturn binary", "if not data:\n return None\nnary ...
<|body_start_0|> if not root: return None binary = TreeNode(root.val) if not root.children: return binary binary.left = self.encode(root.children[0]) node = binary.left for child in root.children[1:]: node.right = self.encode(child) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, root): """Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode""" <|body_0|> def decode(self, data): """Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_033678
2,322
no_license
[ { "docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode", "name": "encode", "signature": "def encode(self, root)" }, { "docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node", "name": "decode", "signature": "def decode...
2
stack_v2_sparse_classes_30k_train_008989
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode - def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode - def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN...
05e0beff0047f0ad399d0b46d625bb8d3459814e
<|skeleton|> class Codec: def encode(self, root): """Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode""" <|body_0|> def decode(self, data): """Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, root): """Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode""" if not root: return None binary = TreeNode(root.val) if not root.children: return binary binary.left = self.encode(root.children[0]) ...
the_stack_v2_python_sparse
python_1_to_1000/431_Encode_N-ary_Tree_to_Binary_Tree.py
jakehoare/leetcode
train
58
2b7a2762a9201f72d07436b272fe3070d6afc522
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MailClusterEvidence()", "from .alert_evidence import AlertEvidence\nfrom .alert_evidence import AlertEvidence\nfields: Dict[str, Callable[[Any], None]] = {'clusterBy': lambda n: setattr(self, 'cluster_by', n.get_str_value()), 'clusterB...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return MailClusterEvidence() <|end_body_0|> <|body_start_1|> from .alert_evidence import AlertEvidence from .alert_evidence import AlertEvidence fields: Dict[str, Callable[[Any], None]]...
MailClusterEvidence
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MailClusterEvidence: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MailClusterEvidence: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob...
stack_v2_sparse_classes_36k_train_033679
3,430
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: MailClusterEvidence", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator...
3
stack_v2_sparse_classes_30k_train_017693
Implement the Python class `MailClusterEvidence` described below. Class description: Implement the MailClusterEvidence class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MailClusterEvidence: Creates a new instance of the appropriate class based on d...
Implement the Python class `MailClusterEvidence` described below. Class description: Implement the MailClusterEvidence class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MailClusterEvidence: Creates a new instance of the appropriate class based on d...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class MailClusterEvidence: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MailClusterEvidence: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MailClusterEvidence: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MailClusterEvidence: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ...
the_stack_v2_python_sparse
msgraph/generated/models/security/mail_cluster_evidence.py
microsoftgraph/msgraph-sdk-python
train
135
de8125a43f3d135161ff6a7e28b2eb143a7ad1a5
[ "self.state_size = state_size\nself.action_size = action_size\nself.build_model()", "states = layers.Input(shape=(self.state_size,), name='states')\nactions = layers.Input(shape=(self.action_size,), name='actions')\nnet_states = layers.Dense(units=16, kernel_regularizer=layers.regularizers.l2(1e-06))(states)\nnet...
<|body_start_0|> self.state_size = state_size self.action_size = action_size self.build_model() <|end_body_0|> <|body_start_1|> states = layers.Input(shape=(self.state_size,), name='states') actions = layers.Input(shape=(self.action_size,), name='actions') net_states = l...
Critic (Value) Model.
Critic
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Critic: """Critic (Value) Model.""" def __init__(self, state_size, action_size): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action""" <|body_0|> def build_model(self): """...
stack_v2_sparse_classes_36k_train_033680
1,841
permissive
[ { "docstring": "Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action", "name": "__init__", "signature": "def __init__(self, state_size, action_size)" }, { "docstring": "Build a critic (value) network that maps ...
2
stack_v2_sparse_classes_30k_train_006617
Implement the Python class `Critic` described below. Class description: Critic (Value) Model. Method signatures and docstrings: - def __init__(self, state_size, action_size): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action - de...
Implement the Python class `Critic` described below. Class description: Critic (Value) Model. Method signatures and docstrings: - def __init__(self, state_size, action_size): Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action - de...
9c52fc77b298f34b7bc126b988262ce4a9826c6e
<|skeleton|> class Critic: """Critic (Value) Model.""" def __init__(self, state_size, action_size): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action""" <|body_0|> def build_model(self): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Critic: """Critic (Value) Model.""" def __init__(self, state_size, action_size): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action""" self.state_size = state_size self.action_size = action_...
the_stack_v2_python_sparse
Chapter09/critic.py
PacktPublishing/Python-Reinforcement-Learning-Projects
train
145
c0613287ae0f9aa3d656b1f8e85ded037a4d7cb7
[ "if n <= 0:\n return 0\nreturn int(math.sqrt(n))", "a = [0] * (n + 1)\na = numpy.array(a)\nfor i in xrange(1, n + 1):\n a[::i] = 1 - a[::i]\nreturn sum(a[1:])" ]
<|body_start_0|> if n <= 0: return 0 return int(math.sqrt(n)) <|end_body_0|> <|body_start_1|> a = [0] * (n + 1) a = numpy.array(a) for i in xrange(1, n + 1): a[::i] = 1 - a[::i] return sum(a[1:]) <|end_body_1|>
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def bulbSwitch(self, n): """:type n: int :rtype: int""" <|body_0|> def bulbSwitch2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n <= 0: return 0 return int(math.sqrt(n)) <|end...
stack_v2_sparse_classes_36k_train_033681
677
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "bulbSwitch", "signature": "def bulbSwitch(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "bulbSwitch2", "signature": "def bulbSwitch2(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bulbSwitch(self, n): :type n: int :rtype: int - def bulbSwitch2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bulbSwitch(self, n): :type n: int :rtype: int - def bulbSwitch2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def bulbSwitch(self, n): """:typ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def bulbSwitch(self, n): """:type n: int :rtype: int""" <|body_0|> def bulbSwitch2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def bulbSwitch(self, n): """:type n: int :rtype: int""" if n <= 0: return 0 return int(math.sqrt(n)) def bulbSwitch2(self, n): """:type n: int :rtype: int""" a = [0] * (n + 1) a = numpy.array(a) for i in xrange(1, n + 1): ...
the_stack_v2_python_sparse
319. Bulb Switcher/bulbSwitch.py
Macielyoung/LeetCode
train
1
23050faaaaca4daad88eb1029b3ac34fd2f90920
[ "plot_key = metrics_for_slice_pb2.PlotKey()\nif self.name:\n plot_key.name = self.name\nif self.model_name:\n plot_key.model_name = self.model_name\nif self.output_name:\n plot_key.output_name = self.output_name\nif self.sub_key:\n plot_key.sub_key.CopyFrom(self.sub_key.to_proto())\nif self.example_weig...
<|body_start_0|> plot_key = metrics_for_slice_pb2.PlotKey() if self.name: plot_key.name = self.name if self.model_name: plot_key.model_name = self.model_name if self.output_name: plot_key.output_name = self.output_name if self.sub_key: ...
A PlotKey is a metric key that uniquely identifies a plot.
PlotKey
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlotKey: """A PlotKey is a metric key that uniquely identifies a plot.""" def to_proto(self) -> metrics_for_slice_pb2.PlotKey: """Converts key to proto.""" <|body_0|> def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': """Configures class from proto."...
stack_v2_sparse_classes_36k_train_033682
44,385
permissive
[ { "docstring": "Converts key to proto.", "name": "to_proto", "signature": "def to_proto(self) -> metrics_for_slice_pb2.PlotKey" }, { "docstring": "Configures class from proto.", "name": "from_proto", "signature": "def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey'" } ]
2
stack_v2_sparse_classes_30k_train_019733
Implement the Python class `PlotKey` described below. Class description: A PlotKey is a metric key that uniquely identifies a plot. Method signatures and docstrings: - def to_proto(self) -> metrics_for_slice_pb2.PlotKey: Converts key to proto. - def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': Configur...
Implement the Python class `PlotKey` described below. Class description: A PlotKey is a metric key that uniquely identifies a plot. Method signatures and docstrings: - def to_proto(self) -> metrics_for_slice_pb2.PlotKey: Converts key to proto. - def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': Configur...
ee0d8eff562bfe068a3ffdc4da0472cc90adaf41
<|skeleton|> class PlotKey: """A PlotKey is a metric key that uniquely identifies a plot.""" def to_proto(self) -> metrics_for_slice_pb2.PlotKey: """Converts key to proto.""" <|body_0|> def from_proto(pb: metrics_for_slice_pb2.PlotKey) -> 'PlotKey': """Configures class from proto."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlotKey: """A PlotKey is a metric key that uniquely identifies a plot.""" def to_proto(self) -> metrics_for_slice_pb2.PlotKey: """Converts key to proto.""" plot_key = metrics_for_slice_pb2.PlotKey() if self.name: plot_key.name = self.name if self.model_name: ...
the_stack_v2_python_sparse
tensorflow_model_analysis/metrics/metric_types.py
tensorflow/model-analysis
train
1,200
e59a8db10ff05797345353182cb7d141482091ec
[ "self.explanation_type = explanation_type\nself._internal_obj = internal_obj\nself.feature_names = feature_names\nself.feature_types = feature_types\nself.name = name\nself.selector = selector", "if key is None:\n return self._internal_obj['overall']\nreturn None", "from ..visual.plot import plot_performance...
<|body_start_0|> self.explanation_type = explanation_type self._internal_obj = internal_obj self.feature_names = feature_names self.feature_types = feature_types self.name = name self.selector = selector <|end_body_0|> <|body_start_1|> if key is None: ...
Explanation object specific to PR explainer.
PRExplanation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PRExplanation: """Explanation object specific to PR explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object t...
stack_v2_sparse_classes_36k_train_033683
10,362
permissive
[ { "docstring": "Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs the explanation. feature_names: List of feature names. feature_types: List of feature types. name: User-defined name of explanation. selector: A dataframe whose indices correspond to explan...
3
stack_v2_sparse_classes_30k_train_000609
Implement the Python class `PRExplanation` described below. Class description: Explanation object specific to PR explainer. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args: explanation_typ...
Implement the Python class `PRExplanation` described below. Class description: Explanation object specific to PR explainer. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args: explanation_typ...
e6f38ea195aecbbd9d28c7183a83c65ada16e1ae
<|skeleton|> class PRExplanation: """Explanation object specific to PR explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PRExplanation: """Explanation object specific to PR explainer.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs the...
the_stack_v2_python_sparse
python/interpret-core/interpret/perf/_curve.py
interpretml/interpret
train
3,731
e7d2f9012327c1c672276c1d1a029975a36b1f19
[ "if self.attr_def.editable:\n self.make_edited(edited_state)\ncurrent_value = self.attribute.getvalue(acm_portfolio_swap)\nif self.attr_def.data_type == AttributeDefinition.BOOL_TYPE:\n bool_value = get_bool_value(str(current_value))\n set_checked_state(self.w_input, bool_value)\nelif is_choice_list(self.a...
<|body_start_0|> if self.attr_def.editable: self.make_edited(edited_state) current_value = self.attribute.getvalue(acm_portfolio_swap) if self.attr_def.data_type == AttributeDefinition.BOOL_TYPE: bool_value = get_bool_value(str(current_value)) set_checked_stat...
A GUI representation of the portfolio-swap-based quirk attribute.
GUIPortfolioSwapQuirkAttribute
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GUIPortfolioSwapQuirkAttribute: """A GUI representation of the portfolio-swap-based quirk attribute.""" def load_attribute(self, acm_portfolio_swap, edited_state=False): """Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap....
stack_v2_sparse_classes_36k_train_033684
21,608
no_license
[ { "docstring": "Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap.", "name": "load_attribute", "signature": "def load_attribute(self, acm_portfolio_swap, edited_state=False)" }, { "docstring": "Make the portfolio-swap-based quirk's val...
3
stack_v2_sparse_classes_30k_train_013467
Implement the Python class `GUIPortfolioSwapQuirkAttribute` described below. Class description: A GUI representation of the portfolio-swap-based quirk attribute. Method signatures and docstrings: - def load_attribute(self, acm_portfolio_swap, edited_state=False): Load the current value of the underlying portfolio-swa...
Implement the Python class `GUIPortfolioSwapQuirkAttribute` described below. Class description: A GUI representation of the portfolio-swap-based quirk attribute. Method signatures and docstrings: - def load_attribute(self, acm_portfolio_swap, edited_state=False): Load the current value of the underlying portfolio-swa...
5e7cc7de3495145501ca53deb9efee2233ab7e1c
<|skeleton|> class GUIPortfolioSwapQuirkAttribute: """A GUI representation of the portfolio-swap-based quirk attribute.""" def load_attribute(self, acm_portfolio_swap, edited_state=False): """Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GUIPortfolioSwapQuirkAttribute: """A GUI representation of the portfolio-swap-based quirk attribute.""" def load_attribute(self, acm_portfolio_swap, edited_state=False): """Load the current value of the underlying portfolio-swap-based quirk from the currently selected portfolio swap.""" i...
the_stack_v2_python_sparse
Python modules/pb_gui_attribute.py
webclinic017/fa-absa-py3
train
0
57d7da873a49ce2fbb00ab4bccd391c34373647b
[ "sign = -1 if x < 0 else 1\nx *= sign\nres = 0\nwhile x:\n t = x % 10\n x //= 10\n res = res * 10 + t\nif not -2 ** 31 <= res <= 2 ** 31 - 1:\n return 0\nreturn res * sign", "sign = -1 if x < 0 else 1\nx *= sign\ns = str(x)\nres = 0\nfor i in s[::-1]:\n res = res * 10 + (ord(i) - ord('0'))\nres *= ...
<|body_start_0|> sign = -1 if x < 0 else 1 x *= sign res = 0 while x: t = x % 10 x //= 10 res = res * 10 + t if not -2 ** 31 <= res <= 2 ** 31 - 1: return 0 return res * sign <|end_body_0|> <|body_start_1|> sign = -...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse(self, x: int) -> int: """反转整型变量的数字""" <|body_0|> def reverse2(self, x): """反转整型变量的数字, 通过转换为字符串再反转实现""" <|body_1|> <|end_skeleton|> <|body_start_0|> sign = -1 if x < 0 else 1 x *= sign res = 0 while x: ...
stack_v2_sparse_classes_36k_train_033685
2,009
no_license
[ { "docstring": "反转整型变量的数字", "name": "reverse", "signature": "def reverse(self, x: int) -> int" }, { "docstring": "反转整型变量的数字, 通过转换为字符串再反转实现", "name": "reverse2", "signature": "def reverse2(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_010035
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x: int) -> int: 反转整型变量的数字 - def reverse2(self, x): 反转整型变量的数字, 通过转换为字符串再反转实现
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse(self, x: int) -> int: 反转整型变量的数字 - def reverse2(self, x): 反转整型变量的数字, 通过转换为字符串再反转实现 <|skeleton|> class Solution: def reverse(self, x: int) -> int: """反转整型...
7f8145f0c7ffdf18c557f01d221087b10443156e
<|skeleton|> class Solution: def reverse(self, x: int) -> int: """反转整型变量的数字""" <|body_0|> def reverse2(self, x): """反转整型变量的数字, 通过转换为字符串再反转实现""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse(self, x: int) -> int: """反转整型变量的数字""" sign = -1 if x < 0 else 1 x *= sign res = 0 while x: t = x % 10 x //= 10 res = res * 10 + t if not -2 ** 31 <= res <= 2 ** 31 - 1: return 0 return...
the_stack_v2_python_sparse
math/007 Reverse Integer.py
mofei952/leetcode_python
train
0
49adab789db6b95758d131dc3f6b2f3a89286142
[ "count = 0\nfor i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 1:\n count += 4\n if i > 0 and grid[i - 1][j] == 1:\n count -= 2\n if j > 0 and grid[i][j - 1] == 1:\n count -= 2\nreturn count", "count = 0\noverlappe...
<|body_start_0|> count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: count += 4 if i > 0 and grid[i - 1][j] == 1: count -= 2 if j > 0 and grid[i][j - 1] == 1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def islandPerimeter(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def islandPerimeter_verbose(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> count = 0 ...
stack_v2_sparse_classes_36k_train_033686
2,575
no_license
[ { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "islandPerimeter", "signature": "def islandPerimeter(self, grid)" }, { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "islandPerimeter_verbose", "signature": "def islandPerimeter_verbose(self, grid)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def islandPerimeter(self, grid): :type grid: List[List[int]] :rtype: int - def islandPerimeter_verbose(self, grid): :type grid: List[List[int]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def islandPerimeter(self, grid): :type grid: List[List[int]] :rtype: int - def islandPerimeter_verbose(self, grid): :type grid: List[List[int]] :rtype: int <|skeleton|> class So...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def islandPerimeter(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def islandPerimeter_verbose(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def islandPerimeter(self, grid): """:type grid: List[List[int]] :rtype: int""" count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: count += 4 if i > 0 and grid[i - 1][j] == ...
the_stack_v2_python_sparse
src/lt_463.py
oxhead/CodingYourWay
train
0
fd3c807ef0ff222581fdbf60df0262fdd147b303
[ "if not os.path.isfile(YPBIND_CONF_FILE):\n return False\nwith open(YPBIND_CONF_FILE) as f:\n lines = [line.strip() for line in f.readlines() if line.strip()]\nfor line in lines:\n if not line.startswith('#'):\n return True\nreturn False", "if not os.path.isdir(YPSERV_DIR_PATH):\n return False\...
<|body_start_0|> if not os.path.isfile(YPBIND_CONF_FILE): return False with open(YPBIND_CONF_FILE) as f: lines = [line.strip() for line in f.readlines() if line.strip()] for line in lines: if not line.startswith('#'): return True return...
Helper library for NISScan actor.
NISScanLibrary
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NISScanLibrary: """Helper library for NISScan actor.""" def client_has_non_default_configuration(self): """Check for any significant ypbind configuration lines in .conf file.""" <|body_0|> def server_has_non_default_configuration(self): """Check for any additiona...
stack_v2_sparse_classes_36k_train_033687
1,641
permissive
[ { "docstring": "Check for any significant ypbind configuration lines in .conf file.", "name": "client_has_non_default_configuration", "signature": "def client_has_non_default_configuration(self)" }, { "docstring": "Check for any additional (not default) files in ypserv DIR.", "name": "server...
3
stack_v2_sparse_classes_30k_train_016563
Implement the Python class `NISScanLibrary` described below. Class description: Helper library for NISScan actor. Method signatures and docstrings: - def client_has_non_default_configuration(self): Check for any significant ypbind configuration lines in .conf file. - def server_has_non_default_configuration(self): Ch...
Implement the Python class `NISScanLibrary` described below. Class description: Helper library for NISScan actor. Method signatures and docstrings: - def client_has_non_default_configuration(self): Check for any significant ypbind configuration lines in .conf file. - def server_has_non_default_configuration(self): Ch...
93c6fd4f150229a01ba43ce74214043cffaf7dce
<|skeleton|> class NISScanLibrary: """Helper library for NISScan actor.""" def client_has_non_default_configuration(self): """Check for any significant ypbind configuration lines in .conf file.""" <|body_0|> def server_has_non_default_configuration(self): """Check for any additiona...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NISScanLibrary: """Helper library for NISScan actor.""" def client_has_non_default_configuration(self): """Check for any significant ypbind configuration lines in .conf file.""" if not os.path.isfile(YPBIND_CONF_FILE): return False with open(YPBIND_CONF_FILE) as f: ...
the_stack_v2_python_sparse
repos/system_upgrade/el8toel9/actors/nisscanner/libraries/nisscan.py
oamg/leapp-repository
train
40
cc4782762849a91bb1f1b1e12ae57d5356776dde
[ "super().__init__()\nself.url = url\nself.iterations = iterations\nself.kwargs = kwargs", "import requests\nfrom requests import exceptions\nlogging.getLogger('requests').setLevel(logging.WARNING)\nlogging.getLogger('urllib3').setLevel(logging.WARNING)\nerror_counter = 0\nfor i in range(self.iterations):\n try...
<|body_start_0|> super().__init__() self.url = url self.iterations = iterations self.kwargs = kwargs <|end_body_0|> <|body_start_1|> import requests from requests import exceptions logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger(...
A Helper that fetches a http address in loop
UrlFetcherHelper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UrlFetcherHelper: """A Helper that fetches a http address in loop""" def __init__(self, url: str, iterations: int=1, **kwargs) -> None: """Sets up the threading pool and assigns the values to be able to use them later :param url: the url to fetch :param iterations: how many time to f...
stack_v2_sparse_classes_36k_train_033688
2,124
no_license
[ { "docstring": "Sets up the threading pool and assigns the values to be able to use them later :param url: the url to fetch :param iterations: how many time to fetch it :param kwargs: others arguments to pass. Will be added in formatting the url", "name": "__init__", "signature": "def __init__(self, url...
2
null
Implement the Python class `UrlFetcherHelper` described below. Class description: A Helper that fetches a http address in loop Method signatures and docstrings: - def __init__(self, url: str, iterations: int=1, **kwargs) -> None: Sets up the threading pool and assigns the values to be able to use them later :param ur...
Implement the Python class `UrlFetcherHelper` described below. Class description: A Helper that fetches a http address in loop Method signatures and docstrings: - def __init__(self, url: str, iterations: int=1, **kwargs) -> None: Sets up the threading pool and assigns the values to be able to use them later :param ur...
e9f914fb6c4eb1bc97f7dfc665e8dd6c7e7ad068
<|skeleton|> class UrlFetcherHelper: """A Helper that fetches a http address in loop""" def __init__(self, url: str, iterations: int=1, **kwargs) -> None: """Sets up the threading pool and assigns the values to be able to use them later :param url: the url to fetch :param iterations: how many time to f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UrlFetcherHelper: """A Helper that fetches a http address in loop""" def __init__(self, url: str, iterations: int=1, **kwargs) -> None: """Sets up the threading pool and assigns the values to be able to use them later :param url: the url to fetch :param iterations: how many time to fetch it :para...
the_stack_v2_python_sparse
lib/trigger/helper.py
holaymzhang/bugbase
train
0
9ec129cdc61b0f747b366a3a741d8be78dfd8622
[ "vds_mor = client_object.vds_mor\nfor portgroup in vds_mor.portgroup:\n if portgroup.name == network:\n return constants.Result.SUCCESS\nreturn constants.Result.FAILURE", "pg = []\nvds_mor = client_object.vds_mor\nfor portgroup in vds_mor.portgroup:\n pg.append(portgroup.name)\nreturn pg" ]
<|body_start_0|> vds_mor = client_object.vds_mor for portgroup in vds_mor.portgroup: if portgroup.name == network: return constants.Result.SUCCESS return constants.Result.FAILURE <|end_body_0|> <|body_start_1|> pg = [] vds_mor = client_object.vds_mor ...
VC55NetworkImpl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VC55NetworkImpl: def check_network_exists(cls, client_object, network=None): """Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_object: VDSwitchAPIClient instance @type network: str @param network: Name of the network @rtype: str @r...
stack_v2_sparse_classes_36k_train_033689
1,420
no_license
[ { "docstring": "Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_object: VDSwitchAPIClient instance @type network: str @param network: Name of the network @rtype: str @return: Success or Failure", "name": "check_network_exists", "signature": "def ch...
2
null
Implement the Python class `VC55NetworkImpl` described below. Class description: Implement the VC55NetworkImpl class. Method signatures and docstrings: - def check_network_exists(cls, client_object, network=None): Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_...
Implement the Python class `VC55NetworkImpl` described below. Class description: Implement the VC55NetworkImpl class. Method signatures and docstrings: - def check_network_exists(cls, client_object, network=None): Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_...
5b55817c050b637e2747084290f6206d2e622938
<|skeleton|> class VC55NetworkImpl: def check_network_exists(cls, client_object, network=None): """Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_object: VDSwitchAPIClient instance @type network: str @param network: Name of the network @rtype: str @r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VC55NetworkImpl: def check_network_exists(cls, client_object, network=None): """Checks if a network exists on the switch. @type client_object: VDSwitchAPIClient instance @param client_object: VDSwitchAPIClient instance @type network: str @param network: Name of the network @rtype: str @return: Success...
the_stack_v2_python_sparse
SystemTesting/pylib/vmware/vsphere/vc/vdswitch/api/vc55_network_impl.py
Cloudxtreme/MyProject
train
0
91097cf3aa24574bcd34b139a7db3ca7b8861025
[ "super().__init__(coordinator, zone, unique_id=f'{zone.zone_id}_{sensor_call}')\nself._call = sensor_call\nself._modifier = modifier\nself._attr_device_class = sensor_class\nself._attr_native_unit_of_measurement = sensor_unit\nself._attr_state_class = state_class\nif translation_key is not None:\n self._attr_tra...
<|body_start_0|> super().__init__(coordinator, zone, unique_id=f'{zone.zone_id}_{sensor_call}') self._call = sensor_call self._modifier = modifier self._attr_device_class = sensor_class self._attr_native_unit_of_measurement = sensor_unit self._attr_state_class = state_cla...
Nexia Zone Sensor Support.
NexiaThermostatZoneSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NexiaThermostatZoneSensor: """Nexia Zone Sensor Support.""" def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): """Create a zone sensor.""" <|body_0|> def native_value(self): """Return the st...
stack_v2_sparse_classes_36k_train_033690
7,364
permissive
[ { "docstring": "Create a zone sensor.", "name": "__init__", "signature": "def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None)" }, { "docstring": "Return the state of the sensor.", "name": "native_value", "signature": ...
2
null
Implement the Python class `NexiaThermostatZoneSensor` described below. Class description: Nexia Zone Sensor Support. Method signatures and docstrings: - def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): Create a zone sensor. - def native_value...
Implement the Python class `NexiaThermostatZoneSensor` described below. Class description: Nexia Zone Sensor Support. Method signatures and docstrings: - def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): Create a zone sensor. - def native_value...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class NexiaThermostatZoneSensor: """Nexia Zone Sensor Support.""" def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): """Create a zone sensor.""" <|body_0|> def native_value(self): """Return the st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NexiaThermostatZoneSensor: """Nexia Zone Sensor Support.""" def __init__(self, coordinator, zone, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): """Create a zone sensor.""" super().__init__(coordinator, zone, unique_id=f'{zone.zone_id}_{sensor_call}'...
the_stack_v2_python_sparse
homeassistant/components/nexia/sensor.py
home-assistant/core
train
35,501
9572d1bb8698eafcc37464730971fbd83ea420ca
[ "self.done_agents = set((agent.id for agent in self.agents.values() if not (isinstance(agent, ActingAgent) and isinstance(agent, ObservingAgent))))\nself.sim.reset(**kwargs)\nreturn {agent.id: self.sim.get_obs(agent.id) for agent in self.agents.values() if agent.id not in self.done_agents}", "for agent_id in acti...
<|body_start_0|> self.done_agents = set((agent.id for agent in self.agents.values() if not (isinstance(agent, ActingAgent) and isinstance(agent, ObservingAgent)))) self.sim.reset(**kwargs) return {agent.id: self.sim.get_obs(agent.id) for agent in self.agents.values() if agent.id not in self.done...
The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done.
AllStepManager
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllStepManager: """The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done.""" def reset(self, **kwargs): """Reset the simulation and return the ...
stack_v2_sparse_classes_36k_train_033691
2,549
permissive
[ { "docstring": "Reset the simulation and return the observation of all the agents.", "name": "reset", "signature": "def reset(self, **kwargs)" }, { "docstring": "Assert that the incoming action does not come from an agent who is recorded as done. Step the simulation forward and return the observ...
2
null
Implement the Python class `AllStepManager` described below. Class description: The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done. Method signatures and docstrings: - def re...
Implement the Python class `AllStepManager` described below. Class description: The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done. Method signatures and docstrings: - def re...
9fada5447b09174c6a70b6032b4a8d08b66c4589
<|skeleton|> class AllStepManager: """The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done.""" def reset(self, **kwargs): """Reset the simulation and return the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllStepManager: """The AllStepManager gets the observations of all agents at reset. At step, it gets the observations of all the agents that are not done. Once all the agents are done, the manager returns all done.""" def reset(self, **kwargs): """Reset the simulation and return the observation o...
the_stack_v2_python_sparse
abmarl/managers/all_step_manager.py
Leonardo767/Abmarl
train
0
3562555a32f6907ea9f058a3752838950a6f1c9b
[ "self.normalize = False\nself.absolute = False\nself.scales = scales\nself.dirs = dirs\nself.kernel_ = np.zeros((scales, dirs), dtype=object)\nself.kernel_shape = (0, 0)", "h, w = shape\nh2, w2 = (h // 2, w // 2)\ngy, gx = np.ogrid[-h2:h - h2, -w2:w - w2]\nk = scale * np.asarray([cos(rot), sin(rot)])\nk2 = k[0] *...
<|body_start_0|> self.normalize = False self.absolute = False self.scales = scales self.dirs = dirs self.kernel_ = np.zeros((scales, dirs), dtype=object) self.kernel_shape = (0, 0) <|end_body_0|> <|body_start_1|> h, w = shape h2, w2 = (h // 2, w // 2) ...
This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature components or only absolute values (Boolean, default False) .. attribute:: Ga...
GaborFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaborFilter: """This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature components or only absolute values (Bo...
stack_v2_sparse_classes_36k_train_033692
4,215
no_license
[ { "docstring": "Initialize a gabor filterbank.", "name": "__init__", "signature": "def __init__(self, scales=5, dirs=8)" }, { "docstring": "Generate gabor wavelet with given parameters. The last argument (shape) specifies the shape of the matrix onto this wavelet will be drawn. Example: gabor_ke...
4
stack_v2_sparse_classes_30k_train_007588
Implement the Python class `GaborFilter` described below. Class description: This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature...
Implement the Python class `GaborFilter` described below. Class description: This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature...
e6092f6c7539564f68826d689c4170633956f5dc
<|skeleton|> class GaborFilter: """This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature components or only absolute values (Bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GaborFilter: """This class encapsulates a gabor transform and provides functions to extract jets at arbitrary points from images. Instances of :class:`GaborFilter` have some public member attributes: .. attribute:: GaborFilter.absolute Return complex feature components or only absolute values (Boolean, defaul...
the_stack_v2_python_sparse
LearningBornschein/mca-genmodel-test/pulp/preproc/gaborfilter.py
haefnerlab/LIF_Sampling_Project
train
0
468dd4cb11c17d3ef96177b58fca869d529f9b33
[ "self.graph = graph\nself.bound = set()\nself.known_namespaces = {'adms': namespace.Namespace('http://www.w3.org/ns/adms#'), 'aiiso': namespace.Namespace('http://purl.org/vocab/aiiso/schema#'), 'cc': namespace.Namespace('http://creativecommons.org/ns#'), 'dc': namespace.DCTERMS, 'dcat': namespace.Namespace('http://...
<|body_start_0|> self.graph = graph self.bound = set() self.known_namespaces = {'adms': namespace.Namespace('http://www.w3.org/ns/adms#'), 'aiiso': namespace.Namespace('http://purl.org/vocab/aiiso/schema#'), 'cc': namespace.Namespace('http://creativecommons.org/ns#'), 'dc': namespace.DCTERMS, 'd...
Class representing the namespaces available to an RDF graph.
Namespaces
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Namespaces: """Class representing the namespaces available to an RDF graph.""" def __init__(self, graph): """:param graph: the graph object to bind the used namespaces to""" <|body_0|> def __getattr__(self, prefix): """Returns the namespace associated with the gi...
stack_v2_sparse_classes_36k_train_033693
3,814
permissive
[ { "docstring": ":param graph: the graph object to bind the used namespaces to", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Returns the namespace associated with the given prefix and ensures it is bound to the graph if it hasn't been already. :param prefix: th...
2
stack_v2_sparse_classes_30k_train_003161
Implement the Python class `Namespaces` described below. Class description: Class representing the namespaces available to an RDF graph. Method signatures and docstrings: - def __init__(self, graph): :param graph: the graph object to bind the used namespaces to - def __getattr__(self, prefix): Returns the namespace a...
Implement the Python class `Namespaces` described below. Class description: Class representing the namespaces available to an RDF graph. Method signatures and docstrings: - def __init__(self, graph): :param graph: the graph object to bind the used namespaces to - def __getattr__(self, prefix): Returns the namespace a...
8b01a0294a809fde491094cb6928b57fee90a9a6
<|skeleton|> class Namespaces: """Class representing the namespaces available to an RDF graph.""" def __init__(self, graph): """:param graph: the graph object to bind the used namespaces to""" <|body_0|> def __getattr__(self, prefix): """Returns the namespace associated with the gi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Namespaces: """Class representing the namespaces available to an RDF graph.""" def __init__(self, graph): """:param graph: the graph object to bind the used namespaces to""" self.graph = graph self.bound = set() self.known_namespaces = {'adms': namespace.Namespace('http://...
the_stack_v2_python_sparse
ckanext/nhm/dcat/utils.py
pribadihcr/ckanext-nhm
train
0
006e1088e72201fab7eebd1409c025b5dba69403
[ "if not root:\n return 'X'\nelse:\n return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])", "self.data = data\nif data[0] == 'X':\n return None\nelse:\n t = TreeNode(int(self.data[:self.data.find(',')]))\n t.left = self.deserialize(self.data[self.data.find(',') + 1...
<|body_start_0|> if not root: return 'X' else: return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)]) <|end_body_0|> <|body_start_1|> self.data = data if data[0] == 'X': return None else: t = TreeNo...
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_033694
3,261
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_001293
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:...
43a14e90b42ce1febb515e02cdd9d93781929173
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return 'X' else: return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)]) def deserialize(self, data): ...
the_stack_v2_python_sparse
297.py
sp-shaopeng/leetcode-practice
train
0
e864889e20640f682be9fa1cf881b3638c699afa
[ "super().__init__(surface_name)\nself._logger = LoggingService.get_logger(__name__)\nself._test_mode = test_mode\nif not self._test_mode:\n self._fix_connection_reset_error()\n self.telegram_bot = telepot.Bot(auth_token)\n self._set_webhook(webhook_url)", "if self._test_mode:\n return 'Message not rea...
<|body_start_0|> super().__init__(surface_name) self._logger = LoggingService.get_logger(__name__) self._test_mode = test_mode if not self._test_mode: self._fix_connection_reset_error() self.telegram_bot = telepot.Bot(auth_token) self._set_webhook(webh...
Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instances of YellowBot, that have their own names and configurations in Telegram, but are...
TelegramSurface
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TelegramSurface: """Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instances of YellowBot, that have their own na...
stack_v2_sparse_classes_36k_train_033695
7,623
permissive
[ { "docstring": "Create the surface and initialize the elements :param surface_name: a name that identify uniquely the Telegram bot connected with this surface instance :type surface_name: str :param auth_token: Telegram authorization token for the connected bot :type auth_token: str :param webhook_url: webhook ...
6
stack_v2_sparse_classes_30k_train_007085
Implement the Python class `TelegramSurface` described below. Class description: Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instanc...
Implement the Python class `TelegramSurface` described below. Class description: Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instanc...
1dac7d312fce78127cac45f17da526c6a66be36a
<|skeleton|> class TelegramSurface: """Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instances of YellowBot, that have their own na...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TelegramSurface: """Allow YellowBot to interact with Telegram. Each instance of this class correspond to a bot managed in Telegram Even if there are multiple bots, the logic to manage them is all centralised in one YellowBot: think bots and "limited" instances of YellowBot, that have their own names and confi...
the_stack_v2_python_sparse
bot/src/yellowbot/surfaces/telegramsurface.py
rainbowbreeze/yellowbutler
train
0
224d80417435793a02477f3a21fa2e07224bd4c7
[ "Readable.__init__(self)\nself.buffer = data_buffer\nself.ptr = 0", "data_buffer = self.buffer[self.ptr:][:length]\nself.ptr += length\nreturn data_buffer" ]
<|body_start_0|> Readable.__init__(self) self.buffer = data_buffer self.ptr = 0 <|end_body_0|> <|body_start_1|> data_buffer = self.buffer[self.ptr:][:length] self.ptr += length return data_buffer <|end_body_1|>
DataBuffer class that exposes methods to read data from a byte buffer.
DataBuffer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataBuffer: """DataBuffer class that exposes methods to read data from a byte buffer.""" def __init__(self, data_buffer): """Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read.""" <|body_0|> def read_data(self, length): ...
stack_v2_sparse_classes_36k_train_033696
24,811
permissive
[ { "docstring": "Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read.", "name": "__init__", "signature": "def __init__(self, data_buffer)" }, { "docstring": "Reads the specified number of bytes and returns them as a buffer.", "name": "read_data",...
2
stack_v2_sparse_classes_30k_train_003143
Implement the Python class `DataBuffer` described below. Class description: DataBuffer class that exposes methods to read data from a byte buffer. Method signatures and docstrings: - def __init__(self, data_buffer): Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read. - ...
Implement the Python class `DataBuffer` described below. Class description: DataBuffer class that exposes methods to read data from a byte buffer. Method signatures and docstrings: - def __init__(self, data_buffer): Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read. - ...
7cbba04a2ee16d21309eefad5be6585183a2d5a9
<|skeleton|> class DataBuffer: """DataBuffer class that exposes methods to read data from a byte buffer.""" def __init__(self, data_buffer): """Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read.""" <|body_0|> def read_data(self, length): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataBuffer: """DataBuffer class that exposes methods to read data from a byte buffer.""" def __init__(self, data_buffer): """Constructs a new instance based on the specified byte buffer. Args: data_buffer: Buffer to be read.""" Readable.__init__(self) self.buffer = data_buffer ...
the_stack_v2_python_sparse
tensorflow/contrib/ignite/python/ops/ignite_dataset_ops.py
NVIDIA/tensorflow
train
763
14388c43e0808f12454f282c0f52bea3563b8e96
[ "log.info('Setup Section verifyProcessorDetails')\nself.host_serial_handle = classparam['host_serial_handle']\nself.host_serial_handle.connect_to_host_serial()", "expected_out = classparam['expected_out']\nvalidation_string = classparam['validation_string']\nbootdev = parameter\noptions = 'persistent'\ncmd_out = ...
<|body_start_0|> log.info('Setup Section verifyProcessorDetails') self.host_serial_handle = classparam['host_serial_handle'] self.host_serial_handle.connect_to_host_serial() <|end_body_0|> <|body_start_1|> expected_out = classparam['expected_out'] validation_string = classparam[...
Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI
PersistentBootDevice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersistentBootDevice: """Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI""" def setup(self): """Test Case Setup""" <|body_0|> def test(self, cimc_util_obj, config, parameter): """ipmi command to set boot ...
stack_v2_sparse_classes_36k_train_033697
19,363
no_license
[ { "docstring": "Test Case Setup", "name": "setup", "signature": "def setup(self)" }, { "docstring": "ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode", "name": "test", "signature": "def test(self, cimc_util_obj, config, parameter)" }, { "...
3
stack_v2_sparse_classes_30k_train_003184
Implement the Python class `PersistentBootDevice` described below. Class description: Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI Method signatures and docstrings: - def setup(self): Test Case Setup - def test(self, cimc_util_obj, config, parameter): ipmi...
Implement the Python class `PersistentBootDevice` described below. Class description: Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI Method signatures and docstrings: - def setup(self): Test Case Setup - def test(self, cimc_util_obj, config, parameter): ipmi...
c255e045a4950a0d8868a10012d5ce6e5c6a9c23
<|skeleton|> class PersistentBootDevice: """Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI""" def setup(self): """Test Case Setup""" <|body_0|> def test(self, cimc_util_obj, config, parameter): """ipmi command to set boot ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PersistentBootDevice: """Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI""" def setup(self): """Test Case Setup""" log.info('Setup Section verifyProcessorDetails') self.host_serial_handle = classparam['host_serial_handle']...
the_stack_v2_python_sparse
ipmi_cmnd_bootorder.py
jrchanda/MyRepo
train
0
ae37d435670305c2cc3de0c4ccbc889376378c04
[ "try:\n natController = NatController()\n json_data = json.dumps(natController.get_arp_table_mac_address(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept Exception as err:\n return Response(json.dumps(str(err)), status=500, mimetype='application/json')"...
<|body_start_0|> try: natController = NatController() json_data = json.dumps(natController.get_arp_table_mac_address(id)) resp = Response(json_data, status=200, mimetype='application/json') return resp except Exception as err: return Response(j...
Arp_Table_MacAddress
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Arp_Table_MacAddress: def get(self, id): """Get the mac address""" <|body_0|> def put(self, id): """Update the mac address""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: natController = NatController() json_data = json....
stack_v2_sparse_classes_36k_train_033698
3,754
no_license
[ { "docstring": "Get the mac address", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update the mac address", "name": "put", "signature": "def put(self, id)" } ]
2
stack_v2_sparse_classes_30k_train_016763
Implement the Python class `Arp_Table_MacAddress` described below. Class description: Implement the Arp_Table_MacAddress class. Method signatures and docstrings: - def get(self, id): Get the mac address - def put(self, id): Update the mac address
Implement the Python class `Arp_Table_MacAddress` described below. Class description: Implement the Arp_Table_MacAddress class. Method signatures and docstrings: - def get(self, id): Get the mac address - def put(self, id): Update the mac address <|skeleton|> class Arp_Table_MacAddress: def get(self, id): ...
6070e3cb6bf957e04f5d8267db11f3296410e18e
<|skeleton|> class Arp_Table_MacAddress: def get(self, id): """Get the mac address""" <|body_0|> def put(self, id): """Update the mac address""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Arp_Table_MacAddress: def get(self, id): """Get the mac address""" try: natController = NatController() json_data = json.dumps(natController.get_arp_table_mac_address(id)) resp = Response(json_data, status=200, mimetype='application/json') return...
the_stack_v2_python_sparse
configuration-agent/nat/rest_api/resources/arp_table.py
ReliableLion/frog4-configurable-vnf
train
0
b8358edaa9fab818df97bcd152e5f88a22bef789
[ "self.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.is_rpo_job = is_rpo_job\nself.job_id = job_id\nself.job_name = job_name\nself.last_protection_job_run_status = last_protection_job_run_status\nself.policy_id = policy_id\nself.policy_name = policy_name", "if dictionary is No...
<|body_start_0|> self.cluster_id = cluster_id self.cluster_incarnation_id = cluster_incarnation_id self.is_rpo_job = is_rpo_job self.job_id = job_id self.job_name = job_name self.last_protection_job_run_status = last_protection_job_run_status self.policy_id = poli...
Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarnation id of the cluster on which object is protected. is_rpo_job (bool): Specifies if t...
ProtectionJobSummary
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtectionJobSummary: """Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarnation id of the cluster on which object...
stack_v2_sparse_classes_36k_train_033699
3,587
permissive
[ { "docstring": "Constructor for the ProtectionJobSummary class", "name": "__init__", "signature": "def __init__(self, cluster_id=None, cluster_incarnation_id=None, is_rpo_job=None, job_id=None, job_name=None, last_protection_job_run_status=None, policy_id=None, policy_name=None)" }, { "docstring...
2
null
Implement the Python class `ProtectionJobSummary` described below. Class description: Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarn...
Implement the Python class `ProtectionJobSummary` described below. Class description: Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarn...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ProtectionJobSummary: """Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarnation id of the cluster on which object...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProtectionJobSummary: """Implementation of the 'ProtectionJobSummary' model. TODO: type description here. Attributes: cluster_id (long|int): Specifies the id of the cluster on which object is protected. cluster_incarnation_id (long|int): Specifies the incarnation id of the cluster on which object is protected...
the_stack_v2_python_sparse
cohesity_management_sdk/models/protection_job_summary.py
cohesity/management-sdk-python
train
24