blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6d4c00b2c1ef0557ac9240f8b9060687d43326c3 | [
"name = utils.get_args_raw(message)\nreply = await message.get_reply_message()\nfname = f'{name or reply.file.name}'\nawait message.client.download_media(reply, f'/var/www/html/modules/{fname}')\nawait message.edit(f'Модуль был сохранён как: <code>{fname}</code>.\\n\\nВы можете его загрузить: <code>.dlmod https://... | <|body_start_0|>
name = utils.get_args_raw(message)
reply = await message.get_reply_message()
fname = f'{name or reply.file.name}'
await message.client.download_media(reply, f'/var/www/html/modules/{fname}')
await message.edit(f'Модуль был сохранён как: <code>{fname}</code>.\n\nВ... | Загрузчик на fl1yd.ml | UploaderMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploaderMod:
"""Загрузчик на fl1yd.ml"""
async def mulcmd(self, message):
"""Загрузить модуль на сервер."""
<|body_0|>
async def fulcmd(self, message):
"""Загрузить файл на сервер."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
name = utils.get... | stack_v2_sparse_classes_75kplus_train_070100 | 1,202 | no_license | [
{
"docstring": "Загрузить модуль на сервер.",
"name": "mulcmd",
"signature": "async def mulcmd(self, message)"
},
{
"docstring": "Загрузить файл на сервер.",
"name": "fulcmd",
"signature": "async def fulcmd(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036996 | Implement the Python class `UploaderMod` described below.
Class description:
Загрузчик на fl1yd.ml
Method signatures and docstrings:
- async def mulcmd(self, message): Загрузить модуль на сервер.
- async def fulcmd(self, message): Загрузить файл на сервер. | Implement the Python class `UploaderMod` described below.
Class description:
Загрузчик на fl1yd.ml
Method signatures and docstrings:
- async def mulcmd(self, message): Загрузить модуль на сервер.
- async def fulcmd(self, message): Загрузить файл на сервер.
<|skeleton|>
class UploaderMod:
"""Загрузчик на fl1yd.ml... | a29db28872a452fcc48445279aff58e676dd0e3c | <|skeleton|>
class UploaderMod:
"""Загрузчик на fl1yd.ml"""
async def mulcmd(self, message):
"""Загрузить модуль на сервер."""
<|body_0|>
async def fulcmd(self, message):
"""Загрузить файл на сервер."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploaderMod:
"""Загрузчик на fl1yd.ml"""
async def mulcmd(self, message):
"""Загрузить модуль на сервер."""
name = utils.get_args_raw(message)
reply = await message.get_reply_message()
fname = f'{name or reply.file.name}'
await message.client.download_media(reply, ... | the_stack_v2_python_sparse | uploader.py | Fl1yd/FTG-Modules | train | 6 |
fb5d8f27cd7ebe851f0c81ee8e1e3a920d8e0eaf | [
"super(ConvLayer, self).__init__()\nself.atom_fea_len = atom_fea_len\nself.nbr_fea_len = nbr_fea_len\nself.fc_full = nn.Linear(2 * self.atom_fea_len + self.nbr_fea_len, 2 * self.atom_fea_len)\nself.sigmoid = nn.Sigmoid()\nself.softplus1 = nn.Softplus()\nself.bn1 = nn.BatchNorm1d(2 * self.atom_fea_len)\nself.bn2 = n... | <|body_start_0|>
super(ConvLayer, self).__init__()
self.atom_fea_len = atom_fea_len
self.nbr_fea_len = nbr_fea_len
self.fc_full = nn.Linear(2 * self.atom_fea_len + self.nbr_fea_len, 2 * self.atom_fea_len)
self.sigmoid = nn.Sigmoid()
self.softplus1 = nn.Softplus()
... | Convolutional operation on graphs. | ConvLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvLayer:
"""Convolutional operation on graphs."""
def __init__(self, atom_fea_len: int, nbr_fea_len: int):
"""Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond features."""
<|body_0|>
def forward(self, atom_in... | stack_v2_sparse_classes_75kplus_train_070101 | 9,607 | permissive | [
{
"docstring": "Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond features.",
"name": "__init__",
"signature": "def __init__(self, atom_fea_len: int, nbr_fea_len: int)"
},
{
"docstring": "Forward pass. N: Total number of atoms in the ba... | 2 | stack_v2_sparse_classes_30k_train_022387 | Implement the Python class `ConvLayer` described below.
Class description:
Convolutional operation on graphs.
Method signatures and docstrings:
- def __init__(self, atom_fea_len: int, nbr_fea_len: int): Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond featu... | Implement the Python class `ConvLayer` described below.
Class description:
Convolutional operation on graphs.
Method signatures and docstrings:
- def __init__(self, atom_fea_len: int, nbr_fea_len: int): Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond featu... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class ConvLayer:
"""Convolutional operation on graphs."""
def __init__(self, atom_fea_len: int, nbr_fea_len: int):
"""Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond features."""
<|body_0|>
def forward(self, atom_in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvLayer:
"""Convolutional operation on graphs."""
def __init__(self, atom_fea_len: int, nbr_fea_len: int):
"""Initialize ConvLayer. Args: atom_fea_len: int Number of atom hidden features. nbr_fea_len: int Number of bond features."""
super(ConvLayer, self).__init__()
self.atom_fe... | the_stack_v2_python_sparse | src/gt4sd/frameworks/cgcnn/model.py | GT4SD/gt4sd-core | train | 239 |
62046b8e1f0c598f943a984d63b8ff8c5b09654f | [
"self._capa = capacity\nself._map = {}\nself._key_to_freq = {}\nself._freq_to_key_list = {}",
"if self._capa == 0:\n return -1\nif key in self._map:\n cur_freq = self._key_to_freq[key]\n new_freq = cur_freq + 1\n self._key_to_freq[key] = new_freq\n self._freq_to_key_list[cur_freq].remove(key)\n ... | <|body_start_0|>
self._capa = capacity
self._map = {}
self._key_to_freq = {}
self._freq_to_key_list = {}
<|end_body_0|>
<|body_start_1|>
if self._capa == 0:
return -1
if key in self._map:
cur_freq = self._key_to_freq[key]
new_freq = cu... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_070102 | 5,388 | 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": "se... | 3 | stack_v2_sparse_classes_30k_test_002649 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 0b4f293260e5ffa52cb0434619bcbb73be7dd5a6 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self._capa = capacity
self._map = {}
self._key_to_freq = {}
self._freq_to_key_list = {}
def get(self, key):
""":type key: int :rtype: int"""
if self._capa == 0:
return -1
... | the_stack_v2_python_sparse | LeetCode/460_LFU_Cache.py | wangruowen/leetcode_practice | train | 0 | |
5064334cf154fd4a9aed5db4d54e2d91b86237b1 | [
"QuadratureSet.initialize(self, distr)\nself.rule = self.cc_roots\nself.params = []\nself.quadRule = CCQuadRule",
"n1 = o\nif o == 1:\n return np.array([np.array([0]), np.array([2])])\nelse:\n n = n1 - 1\n C = np.zeros((n1, 2))\n k = 2 * (1 + np.arange(np.floor(n / 2)))\n C[::2, 0] = 2 / np.hstack(... | <|body_start_0|>
QuadratureSet.initialize(self, distr)
self.rule = self.cc_roots
self.params = []
self.quadRule = CCQuadRule
<|end_body_0|>
<|body_start_1|>
n1 = o
if o == 1:
return np.array([np.array([0]), np.array([2])])
else:
n = n1 - 1... | ClenshawCurtis quadrature | ClenshawCurtis | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClenshawCurtis:
"""ClenshawCurtis quadrature"""
def initialize(self, distr):
"""Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None"""
<|body_0|>
def cc_roots(self, o):
"""Computes Clenshaw ... | stack_v2_sparse_classes_75kplus_train_070103 | 25,703 | permissive | [
{
"docstring": "Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None",
"name": "initialize",
"signature": "def initialize(self, distr)"
},
{
"docstring": "Computes Clenshaw Curtis nodes and weights for given order n=2^o+1 @ ... | 2 | null | Implement the Python class `ClenshawCurtis` described below.
Class description:
ClenshawCurtis quadrature
Method signatures and docstrings:
- def initialize(self, distr): Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None
- def cc_roots(self, o... | Implement the Python class `ClenshawCurtis` described below.
Class description:
ClenshawCurtis quadrature
Method signatures and docstrings:
- def initialize(self, distr): Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None
- def cc_roots(self, o... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class ClenshawCurtis:
"""ClenshawCurtis quadrature"""
def initialize(self, distr):
"""Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None"""
<|body_0|>
def cc_roots(self, o):
"""Computes Clenshaw ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClenshawCurtis:
"""ClenshawCurtis quadrature"""
def initialize(self, distr):
"""Initializes specific settings for quadratures. @ In, distr, Distribution object, distro represented by this quad @ Out, None"""
QuadratureSet.initialize(self, distr)
self.rule = self.cc_roots
s... | the_stack_v2_python_sparse | ravenframework/Quadratures.py | idaholab/raven | train | 201 |
6793dbbd0be10530ea0fd011e6b097a6813cb588 | [
"vulnerability = CVESearchVulnerabilityResult()\nvulnerability.published = data.get('Published')\nvulnerability.access = data.get('access')\nvulnerability.impact = data.get('impact')\nvulnerability.summary = data.get('summary')\nvulnerability.cwe = data.get('cwe')\nvulnerability.cvss = data.get('cvss')\nvulnerabili... | <|body_start_0|>
vulnerability = CVESearchVulnerabilityResult()
vulnerability.published = data.get('Published')
vulnerability.access = data.get('access')
vulnerability.impact = data.get('impact')
vulnerability.summary = data.get('summary')
vulnerability.cwe = data.get('cw... | CVE-search output parser. Supports both text and json (default) outputs. | CVESearchParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070104 | 1,731 | permissive | [
{
"docstring": "Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult",
"name": "dict_to_result",
"signature": "def dict_to_result(cls, data)"
},
{
"docstring": "Convert list of cve-search result dicts to CVESearchVulnerabi... | 2 | stack_v2_sparse_classes_30k_train_046064 | Implement the Python class `CVESearchParser` described below.
Class description:
CVE-search output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data): Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns:... | Implement the Python class `CVESearchParser` described below.
Class description:
CVE-search output parser. Supports both text and json (default) outputs.
Method signatures and docstrings:
- def dict_to_result(cls, data): Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns:... | bb21ff02965ed0cca5a55ee559eae77856d9866c | <|skeleton|>
class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CVESearchParser:
"""CVE-search output parser. Supports both text and json (default) outputs."""
def dict_to_result(cls, data):
"""Convert cve-search result dict to CVESearchVulnerabilityResult object Args: data (dict): Returns: CVESearchVulnerabilityResult"""
vulnerability = CVESearchVuln... | the_stack_v2_python_sparse | tools/cve_search/parsers.py | collectivesense/aucote | train | 0 |
7d81971b3cc33cf292b8f01c9cb50b434ffe2a20 | [
"def backtrack(pos: int, target: int) -> List[List[int]]:\n if target == 0:\n return [[]]\n if pos >= len(nums) or nums[pos] > target:\n return []\n return [[nums[pos]] + sub_sol for sub_sol in backtrack(pos, target - nums[pos])] + backtrack(pos + 1, target)\nnums.sort()\nreturn backtrack(0, ... | <|body_start_0|>
def backtrack(pos: int, target: int) -> List[List[int]]:
if target == 0:
return [[]]
if pos >= len(nums) or nums[pos] > target:
return []
return [[nums[pos]] + sub_sol for sub_sol in backtrack(pos, target - nums[pos])] + backtr... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be ove... | stack_v2_sparse_classes_75kplus_train_070105 | 2,540 | no_license | [
{
"docstring": "If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be overlapping problems (select 2 then 3, or select 5), but it might not be worth memoizing them because... | 2 | stack_v2_sparse_classes_30k_train_014796 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]: If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]: If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be ove... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combinationSum_1(self, nums: List[int], target: int) -> List[List[int]]:
"""If we select the number at 'i', then we have another sub-problem to solve at 'i+1' with 'target-nums[i]'. If we sort the numbers, we can cut the exploration when nums[i] > target. There might be overlapping probl... | the_stack_v2_python_sparse | backtrack/CombinationSum.py | QuentinDuval/PythonExperiments | train | 3 | |
ca0e13eb090a36a22f9ab3fee85589709e12fa5c | [
"super().__init__(supported_data_kinds=[], data_kinds_to_filter=[])\nif not data_kinds:\n raise ValueError('data_kinds must be non-empty')\nif not isinstance(data_kinds, list):\n raise ValueError(f'data_kinds must be a list but got {type(data_kinds)}')\nif not all((isinstance(e, str) for e in data_kinds)):\n ... | <|body_start_0|>
super().__init__(supported_data_kinds=[], data_kinds_to_filter=[])
if not data_kinds:
raise ValueError('data_kinds must be non-empty')
if not isinstance(data_kinds, list):
raise ValueError(f'data_kinds must be a list but got {type(data_kinds)}')
i... | DXOBlocker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DXOBlocker:
def __init__(self, data_kinds: List[str], allow_data_kinds: bool=False):
"""Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If True, block everything not in the list; If False, block everything in the configured list. data_kin... | stack_v2_sparse_classes_75kplus_train_070106 | 2,567 | permissive | [
{
"docstring": "Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If True, block everything not in the list; If False, block everything in the configured list. data_kinds: kinds of DXO object to block",
"name": "__init__",
"signature": "def __init__(self, ... | 2 | null | Implement the Python class `DXOBlocker` described below.
Class description:
Implement the DXOBlocker class.
Method signatures and docstrings:
- def __init__(self, data_kinds: List[str], allow_data_kinds: bool=False): Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If ... | Implement the Python class `DXOBlocker` described below.
Class description:
Implement the DXOBlocker class.
Method signatures and docstrings:
- def __init__(self, data_kinds: List[str], allow_data_kinds: bool=False): Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If ... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class DXOBlocker:
def __init__(self, data_kinds: List[str], allow_data_kinds: bool=False):
"""Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If True, block everything not in the list; If False, block everything in the configured list. data_kin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DXOBlocker:
def __init__(self, data_kinds: List[str], allow_data_kinds: bool=False):
"""Block certain kinds of DXO objects. Args: allow_data_kinds: allow or block configured data kinds. If True, block everything not in the list; If False, block everything in the configured list. data_kinds: kinds of D... | the_stack_v2_python_sparse | nvflare/app_common/filters/dxo_blocker.py | NVIDIA/NVFlare | train | 442 | |
f4d0c82ef7f1dbb4ebd7a1b7c646d466d90361ec | [
"for i in range(len(nums) - 1):\n if nums[i] == nums[i + 1] == 0:\n return True\nif k == 0:\n return False\nm = {}\nm[0] = -1\n_sum = 0\nfor i in range(len(nums)):\n _sum += nums[i]\n _sum %= k\n if _sum in m:\n if not (m[0] == -1 and i == 0):\n return True\n m[_sum] = i\n... | <|body_start_0|>
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1] == 0:
return True
if k == 0:
return False
m = {}
m[0] = -1
_sum = 0
for i in range(len(nums)):
_sum += nums[i]
_sum %= k
i... | ERROR: type should be string, got "https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the array, sum+=nums[i], calculate the mod = sum%k, if the same mod has appeared before when i=j, then sum(nums(j...i])==n*k 4. we put m[0]==-1 at the beginning, think nums = {1,1} and k = 2, sum(nums[0...1])%2=0, so this makes it apply the previous statement; 5. we need to do the check \"if (!( m[0]==-1 && i==0))\", in case situations like nums={1} and k=1" | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the array, sum+=nums[i], calculate the mod = su... | stack_v2_sparse_classes_75kplus_train_070107 | 1,976 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "checkSubarraySum",
"signature": "def checkSubarraySum(self, nums, k)"
},
{
"docstring": "easy to understand solution",
"name": "checkSubarraySum2",
"signature": "def checkSubarraySum2(self, nums, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008567 | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the arra... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the arra... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the array, sum+=nums[i], calculate the mod = su... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""https://leetcode.com/problems/continuous-subarray-sum/description/ 1. when there are two subsequent 0, whatever k is, we should return true, because 0*k=0; 2. when k==0 and there are no two subsequent 0, return false; 3. iterate through the array, sum+=nums[i], calculate the mod = sum%k, if the s... | the_stack_v2_python_sparse | old/Session002/DynamicProgramming/ContinuousSubarraySum.py | MaxIakovliev/algorithms | train | 0 |
f19f87ea329edbbbd02cb3704bd743639ce5a792 | [
"self.img_bytes = img_bytes\nself.img_pillow = None\nself.img_meta_data = ImgMetaData(type='N.A.', size='N.A.', height=0, width=0, exif={})\nsuper(ImagePreProcessing, self).__init__(prefix='PP', phase_name='Pre-processing', invocation_id=invocation_id)",
"if not self.__convert_image_bytes_to_pillow():\n return... | <|body_start_0|>
self.img_bytes = img_bytes
self.img_pillow = None
self.img_meta_data = ImgMetaData(type='N.A.', size='N.A.', height=0, width=0, exif={})
super(ImagePreProcessing, self).__init__(prefix='PP', phase_name='Pre-processing', invocation_id=invocation_id)
<|end_body_0|>
<|body... | Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data. | ImagePreProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePreProcessing:
"""Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data."""
def __init__(self, img_bytes: bytes, invocation_id: str):
"""Constructor of the Im... | stack_v2_sparse_classes_75kplus_train_070108 | 5,667 | no_license | [
{
"docstring": "Constructor of the Image pre-processing object, stores provided and locally generated data, runs main object procedure. :param img_bytes: validation provided image in bytes form. :param invocation_id: string containing id of current cloud function invocation to be to be used by API metrics.",
... | 5 | stack_v2_sparse_classes_30k_train_003966 | Implement the Python class `ImagePreProcessing` described below.
Class description:
Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data.
Method signatures and docstrings:
- def __init__(self, img... | Implement the Python class `ImagePreProcessing` described below.
Class description:
Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data.
Method signatures and docstrings:
- def __init__(self, img... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class ImagePreProcessing:
"""Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data."""
def __init__(self, img_bytes: bytes, invocation_id: str):
"""Constructor of the Im... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagePreProcessing:
"""Image pre-processing object, responsible for converting image to required Pillow Image format, performing any processing required, extracting and exposing resulting meta data."""
def __init__(self, img_bytes: bytes, invocation_id: str):
"""Constructor of the Image pre-proce... | the_stack_v2_python_sparse | Serverless/handlers/http_add_picture/image_pre_processing.py | RogerVFbr/MyCelebs | train | 0 |
5fc5856dc6ef3f0bdcf787333d81f546b28629f3 | [
"self.pq = []\nself.list = []\nself.id = 0\nself.pqd = {}\nself.listd = {}",
"self.list.append([self.id, x])\nheappush(self.pq, [-x, -self.id])\nself.id += 1",
"ans = self.top()\nself.pqd[self.list[-1][0]] = 1\nself.list.pop()\nreturn ans",
"while self.list[-1][0] in self.listd:\n self.listd.pop(self.list[... | <|body_start_0|>
self.pq = []
self.list = []
self.id = 0
self.pqd = {}
self.listd = {}
<|end_body_0|>
<|body_start_1|>
self.list.append([self.id, x])
heappush(self.pq, [-x, -self.id])
self.id += 1
<|end_body_1|>
<|body_start_2|>
ans = self.top()
... | MaxStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_070109 | 1,528 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type x: int :rtype: void",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def p... | 6 | null | Implement the Python class `MaxStack` described below.
Class description:
Implement the MaxStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: int
- def top(self): :rtype: int
- def peekMax(se... | Implement the Python class `MaxStack` described below.
Class description:
Implement the MaxStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :rtype: int
- def top(self): :rtype: int
- def peekMax(se... | 8fa215fb0d5b2e8f6a863756c874d0bdb2cffa04 | <|skeleton|>
class MaxStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxStack:
def __init__(self):
"""initialize your data structure here."""
self.pq = []
self.list = []
self.id = 0
self.pqd = {}
self.listd = {}
def push(self, x):
""":type x: int :rtype: void"""
self.list.append([self.id, x])
heappush... | the_stack_v2_python_sparse | Finish/H716_Max_Stack.py | Azurisky/Leetcode | train | 0 | |
3d9a4fa16551d9863e59c4f1b1e980c4b2943ae9 | [
"def recur(root, k, hashset):\n if not root:\n return False\n target = k - root.val\n if target in hashset:\n return True\n else:\n hashset.add(root.val)\n return recur(root.left, k, hashset) or recur(root.right, k, hashset)\nhashset = set()\nreturn recur(root, k, hashset)",
"i... | <|body_start_0|>
def recur(root, k, hashset):
if not root:
return False
target = k - root.val
if target in hashset:
return True
else:
hashset.add(root.val)
return recur(root.left, k, hashset) or recur(roo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
<|body_0|>
def findTarget2(self, root: TreeNode, k: int) -> bool:
"""思路:通过flag来标记是否已找到"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def recur(root, k, hashset):
... | stack_v2_sparse_classes_75kplus_train_070110 | 1,757 | no_license | [
{
"docstring": "思路:回溯+剪枝",
"name": "findTarget1",
"signature": "def findTarget1(self, root: TreeNode, k: int) -> bool"
},
{
"docstring": "思路:通过flag来标记是否已找到",
"name": "findTarget2",
"signature": "def findTarget2(self, root: TreeNode, k: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_test_001606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路:回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路:通过flag来标记是否已找到 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路:回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路:通过flag来标记是否已找到
<|skeleton|>
class Solution:
def ... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
<|body_0|>
def findTarget2(self, root: TreeNode, k: int) -> bool:
"""思路:通过flag来标记是否已找到"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTarget1(self, root: TreeNode, k: int) -> bool:
"""思路:回溯+剪枝"""
def recur(root, k, hashset):
if not root:
return False
target = k - root.val
if target in hashset:
return True
else:
h... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/653. 两数之和 IV - 输入 BST.py | yiming1012/MyLeetCode | train | 2 | |
3e33a8ffefc16aa193800135bf66d0a940abcefb | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('xcao19', 'xcao19')\nurl = 'http://data.insideairbnb.com/united-states/ma/boston/2019-01-17/visualisations/neighbourhoods.csv'\ndf = pd.read_csv(url, encoding='ISO-8859-1')\njson_df = df.to_json(orient='r... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'http://data.insideairbnb.com/united-states/ma/boston/2019-01-17/visualisations/neighbourhoods.csv'
df = pd.read_csv(url,... | AirBNB_neighborhoods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirBNB_neighborhoods:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing eve... | stack_v2_sparse_classes_75kplus_train_070111 | 3,316 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_042567 | Implement the Python class `AirBNB_neighborhoods` described below.
Class description:
Implement the AirBNB_neighborhoods class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), sta... | Implement the Python class `AirBNB_neighborhoods` described below.
Class description:
Implement the AirBNB_neighborhoods class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), sta... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class AirBNB_neighborhoods:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing eve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AirBNB_neighborhoods:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url... | the_stack_v2_python_sparse | xcao19/AirBNB_neighborhoods.py | maximega/course-2019-spr-proj | train | 2 | |
cb2eb18b04525406fc549d6afd12b83862aa869f | [
"self.name = name\nself.chords = chords\nself.tritone = tritone\nself.weight = 0",
"self.weight = int(15 - (self.tritone - curr_loop.attributes['tritone']) ** 2 * 2.5)\nif curr_loop.key['quality'] == 'major':\n if self.name == 'primary_dominant' or self.name == 'diatonic major' or self.name == 'diatonic minor'... | <|body_start_0|>
self.name = name
self.chords = chords
self.tritone = tritone
self.weight = 0
<|end_body_0|>
<|body_start_1|>
self.weight = int(15 - (self.tritone - curr_loop.attributes['tritone']) ** 2 * 2.5)
if curr_loop.key['quality'] == 'major':
if self.n... | Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int | Family | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Family:
"""Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int"""
def __init__(self, name, chords, tritone):
"""Constructs a chord family ~ @type self: Family ... | stack_v2_sparse_classes_75kplus_train_070112 | 2,555 | no_license | [
{
"docstring": "Constructs a chord family ~ @type self: Family @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @rtype: None",
"name": "__init__",
"signature": "def __init__(self, name, chords, tritone)"
},
{
"docstring": "Determines the weight of family self based on loop se... | 2 | stack_v2_sparse_classes_30k_train_043296 | Implement the Python class `Family` described below.
Class description:
Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int
Method signatures and docstrings:
- def __init__(self, name, chords, ... | Implement the Python class `Family` described below.
Class description:
Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int
Method signatures and docstrings:
- def __init__(self, name, chords, ... | 8397cbe41797ad8d0501bb6510ee1ea974a8259b | <|skeleton|>
class Family:
"""Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int"""
def __init__(self, name, chords, tritone):
"""Constructs a chord family ~ @type self: Family ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Family:
"""Represents a chord family which has a name and tension/depth ratings ~ === Attributes === @type name: str @type chords: (Chord, Chord, ...) @type tritone: int @type weight: int"""
def __init__(self, name, chords, tritone):
"""Constructs a chord family ~ @type self: Family @type name: s... | the_stack_v2_python_sparse | AMG/class_family.py | metchel/Amadeus | train | 0 |
ee20202869447bb407ad42396139f3f783b816d7 | [
"l2 = len(nums2)\nnums2_next = [-1] * l2\nfor i in range(l2 - 1):\n for j in range(i + 1, l2):\n if nums2[j] > nums2[i]:\n nums2_next[i] = nums2[j]\n break\nres = []\nfor k in nums1:\n res.append(nums2_next[nums2.index(k)])\nreturn res",
"if not nums1 or not nums2:\n return [... | <|body_start_0|>
l2 = len(nums2)
nums2_next = [-1] * l2
for i in range(l2 - 1):
for j in range(i + 1, l2):
if nums2[j] > nums2[i]:
nums2_next[i] = nums2[j]
break
res = []
for k in nums1:
res.append(nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElement2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_070113 | 1,411 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "nextGreaterElement2",
"s... | 2 | stack_v2_sparse_classes_30k_train_024032 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def nextGreaterElement2(self, nums1, nums2): :type nums1: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def nextGreaterElement2(self, nums1, nums2): :type nums1: List[int] ... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElement2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
l2 = len(nums2)
nums2_next = [-1] * l2
for i in range(l2 - 1):
for j in range(i + 1, l2):
if nums2[j] > nums2[i]:
... | the_stack_v2_python_sparse | code/496#Next Greater Element I.py | EachenKuang/LeetCode | train | 28 | |
1cff53bfd76a8a23c0f3dbeaa2af3fcff5769379 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\nelectionIds = list(repo[STATE_SENATE_ELECTIONS_NAME].find({}, {'_id': 1}))\nelectionResultsRows = []\nfor question in electionIds:\n id = question['_id']\n url = ELECTION_DOWN... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate(TEAM_NAME, TEAM_NAME)
electionIds = list(repo[STATE_SENATE_ELECTIONS_NAME].find({}, {'_id': 1}))
electionResultsRows = []
for question in e... | stateSenateElectionsResults | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stateSenateElectionsResults:
def execute(trial=False):
"""Retrieve election results data from electionstats and insert into collection ex) { "City/Town" : "Egremont", "Ward" : "-", "Pct" : "1", "Election ID" : "131526", "Adam G Hinds" : 682, "All Others" : 0, "Blanks" : 111, "Total Votes... | stack_v2_sparse_classes_75kplus_train_070114 | 6,348 | no_license | [
{
"docstring": "Retrieve election results data from electionstats and insert into collection ex) { \"City/Town\" : \"Egremont\", \"Ward\" : \"-\", \"Pct\" : \"1\", \"Election ID\" : \"131526\", \"Adam G Hinds\" : 682, \"All Others\" : 0, \"Blanks\" : 111, \"Total Votes Cast\" : 793 }",
"name": "execute",
... | 3 | stack_v2_sparse_classes_30k_train_051390 | Implement the Python class `stateSenateElectionsResults` described below.
Class description:
Implement the stateSenateElectionsResults class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve election results data from electionstats and insert into collection ex) { "City/Town" : "Egremont", "Ward... | Implement the Python class `stateSenateElectionsResults` described below.
Class description:
Implement the stateSenateElectionsResults class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve election results data from electionstats and insert into collection ex) { "City/Town" : "Egremont", "Ward... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class stateSenateElectionsResults:
def execute(trial=False):
"""Retrieve election results data from electionstats and insert into collection ex) { "City/Town" : "Egremont", "Ward" : "-", "Pct" : "1", "Election ID" : "131526", "Adam G Hinds" : 682, "All Others" : 0, "Blanks" : 111, "Total Votes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class stateSenateElectionsResults:
def execute(trial=False):
"""Retrieve election results data from electionstats and insert into collection ex) { "City/Town" : "Egremont", "Ward" : "-", "Pct" : "1", "Election ID" : "131526", "Adam G Hinds" : 682, "All Others" : 0, "Blanks" : 111, "Total Votes Cast" : 793 }... | the_stack_v2_python_sparse | ldisalvo_skeesara_vidyaap/stateSenateElectionsResults.py | maximega/course-2019-spr-proj | train | 2 | |
c21ac3c37b1a211467757c8da38df34e225f3337 | [
"self.window = tk.Tk()\nself.window.title('Meeting scheduler')\nself.window.minsize(width=1000, height=800)\nself.window.configure(bg='grey')",
"self.window.update()\nadd_person = AddPerssonPage(self.window)\nperson_controller = PersonController(add_person)\nadd_person.set_controller(person_controller)\nadd_meeti... | <|body_start_0|>
self.window = tk.Tk()
self.window.title('Meeting scheduler')
self.window.minsize(width=1000, height=800)
self.window.configure(bg='grey')
<|end_body_0|>
<|body_start_1|>
self.window.update()
add_person = AddPerssonPage(self.window)
person_control... | Main app class. Creates and pack all the others frames. | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Main app class. Creates and pack all the others frames."""
def __init__(self):
"""App constructor to initialize object."""
<|body_0|>
def run(self):
"""Creates all pages, side menu, controllers and assign controllers to pages. :return: None"""
<|b... | stack_v2_sparse_classes_75kplus_train_070115 | 1,974 | no_license | [
{
"docstring": "App constructor to initialize object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Creates all pages, side menu, controllers and assign controllers to pages. :return: None",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047638 | Implement the Python class `App` described below.
Class description:
Main app class. Creates and pack all the others frames.
Method signatures and docstrings:
- def __init__(self): App constructor to initialize object.
- def run(self): Creates all pages, side menu, controllers and assign controllers to pages. :return... | Implement the Python class `App` described below.
Class description:
Main app class. Creates and pack all the others frames.
Method signatures and docstrings:
- def __init__(self): App constructor to initialize object.
- def run(self): Creates all pages, side menu, controllers and assign controllers to pages. :return... | f1d19e88f522bc1b18cdd575202356fd243797a5 | <|skeleton|>
class App:
"""Main app class. Creates and pack all the others frames."""
def __init__(self):
"""App constructor to initialize object."""
<|body_0|>
def run(self):
"""Creates all pages, side menu, controllers and assign controllers to pages. :return: None"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
"""Main app class. Creates and pack all the others frames."""
def __init__(self):
"""App constructor to initialize object."""
self.window = tk.Tk()
self.window.title('Meeting scheduler')
self.window.minsize(width=1000, height=800)
self.window.configure(bg='gre... | the_stack_v2_python_sparse | graphics/app.py | EduardMih/meeting-scheduler | train | 0 |
dd506cf21a30be68d99debd1a23e1b47badc8084 | [
"x, y = (ganglioside[1], ganglioside[2])\nif y not in ['1', '2', '3', '4']:\n msg = 'Ganglioside: ganglioside_to_r_group: ganglioside \"{}\" not recognized, y should be 1-4'.format(ganglioside)\n raise ValueError(msg)\nif x not in ['A', 'M', 'D', 'T', 'Q', 'P', 'H', 'S', 'O']:\n msg = 'Ganglioside: ganglio... | <|body_start_0|>
x, y = (ganglioside[1], ganglioside[2])
if y not in ['1', '2', '3', '4']:
msg = 'Ganglioside: ganglioside_to_r_group: ganglioside "{}" not recognized, y should be 1-4'.format(ganglioside)
raise ValueError(msg)
if x not in ['A', 'M', 'D', 'T', 'Q', 'P', 'H... | Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1 = Galβ1-3GalNAcβ1-4Galβ1-4Glcβ1-1’Cer, 2 = lacking terminal Gal, 3 = lacking ... | Ganglioside | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ganglioside:
"""Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1 = Galβ1-3GalNAcβ1-4Galβ1-4Glcβ1-1’Cer,... | stack_v2_sparse_classes_75kplus_train_070116 | 3,688 | permissive | [
{
"docstring": "Ganglioside.ganglioside_to_r_group description: returns the R-group formula corresponding to a ganglioside name parameters: ganglioside (str) -- specify the ganglioside with standard naming convention (Gxy[z]) returns: (dict(str:int)) -- chemical formula of R-group",
"name": "ganglioside_to_... | 2 | stack_v2_sparse_classes_30k_train_033823 | Implement the Python class `Ganglioside` described below.
Class description:
Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1... | Implement the Python class `Ganglioside` described below.
Class description:
Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1... | c7c3b72d4549a1a9937f287f3b314eff8e7ed054 | <|skeleton|>
class Ganglioside:
"""Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1 = Galβ1-3GalNAcβ1-4Galβ1-4Glcβ1-1’Cer,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ganglioside:
"""Ganglioside description: lipid class covering gangliosides. Uses standard ganglioside nomenclature (Gxy[z]) where x denotes how many sialic acids are attached (A = 0, M = 1, D = 2, T = 3, Q = 4, P = 5), y denotes the nuclear core structure (1 = Galβ1-3GalNAcβ1-4Galβ1-4Glcβ1-1’Cer, 2 = lacking ... | the_stack_v2_python_sparse | lipydomics/identification/LipidMass/lipids/sphingolipids/gangliosides.py | kaitlin-rempfert/lipydomics | train | 0 |
87092e7e3671dbeaf32b3c821ba9b6ad6cc03e0b | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | [summary] Args: tf ([type]): [description] | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_75kplus_train_070117 | 2,420 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | stack_v2_sparse_classes_30k_train_018837 | Implement the Python class `DecoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `DecoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Dec... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
62070fd6e42f8506df69401c77000a1b752d4cd7 | [
"self.is_full_team_required = is_full_team_required\nself.object = object\nself.source_channel_vec = source_channel_vec",
"if dictionary is None:\n return None\nis_full_team_required = dictionary.get('isFullTeamRequired')\nobject = cohesity_management_sdk.models.restore_object.RestoreObject.from_dictionary(dic... | <|body_start_0|>
self.is_full_team_required = is_full_team_required
self.object = object
self.source_channel_vec = source_channel_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_full_team_required = dictionary.get('isFullTeamRequired')
... | Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. This will store the details of the MS team to be re... | RestoreO365TeamsParams_MSTeamInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_75kplus_train_070118 | 2,808 | permissive | [
{
"docstring": "Constructor for the RestoreO365TeamsParams_MSTeamInfo class",
"name": "__init__",
"signature": "def __init__(self, is_full_team_required=None, object=None, source_channel_vec=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionar... | 2 | stack_v2_sparse_classes_30k_train_029333 | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. Thi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_teams_params_ms_team_info.py | cohesity/management-sdk-python | train | 24 |
f73da1eb3b5565db6063dc1d94c28bebbfb65a91 | [
"plugin = SpotExtraction()\nexpected_points = self.expected_spot_aux_coord.points\nexpected_bounds = self.expected_spot_aux_coord.bounds\nx_indices, y_indices = self.coordinate_cube.data\npoints, bounds = plugin.get_coordinate_data(self.diagnostic_cube_2d_aux, x_indices, y_indices, coordinate='location')\nself.asse... | <|body_start_0|>
plugin = SpotExtraction()
expected_points = self.expected_spot_aux_coord.points
expected_bounds = self.expected_spot_aux_coord.bounds
x_indices, y_indices = self.coordinate_cube.data
points, bounds = plugin.get_coordinate_data(self.diagnostic_cube_2d_aux, x_indic... | Test the extraction of data from the provided coordinates. | Test_get_coordinate_data | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_get_coordinate_data:
"""Test the extraction of data from the provided coordinates."""
def test_coordinate_with_bounds_extraction(self):
"""Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In this case the coordinate has bounds."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070119 | 21,606 | permissive | [
{
"docstring": "Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In this case the coordinate has bounds.",
"name": "test_coordinate_with_bounds_extraction",
"signature": "def test_coordinate_with_bounds_extraction(self)"
},
{
"docstring": "Test extraction of coordinat... | 2 | stack_v2_sparse_classes_30k_train_030368 | Implement the Python class `Test_get_coordinate_data` described below.
Class description:
Test the extraction of data from the provided coordinates.
Method signatures and docstrings:
- def test_coordinate_with_bounds_extraction(self): Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In thi... | Implement the Python class `Test_get_coordinate_data` described below.
Class description:
Test the extraction of data from the provided coordinates.
Method signatures and docstrings:
- def test_coordinate_with_bounds_extraction(self): Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In thi... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_get_coordinate_data:
"""Test the extraction of data from the provided coordinates."""
def test_coordinate_with_bounds_extraction(self):
"""Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In this case the coordinate has bounds."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_get_coordinate_data:
"""Test the extraction of data from the provided coordinates."""
def test_coordinate_with_bounds_extraction(self):
"""Test extraction of coordinate data for a 2-dimensional auxiliary coordinate. In this case the coordinate has bounds."""
plugin = SpotExtraction()... | the_stack_v2_python_sparse | improver_tests/spotdata/test_SpotExtraction.py | metoppv/improver | train | 101 |
34734df296c33c6858c578e0fb8d59c173e38360 | [
"nodeid = int(node_id)\nhass = request.app['hass']\nnetwork = hass.data.get(const.DATA_NETWORK)\n\ndef _fetch_protection():\n \"\"\"Get protection data.\"\"\"\n node = network.nodes.get(nodeid)\n if node is None:\n return self.json_message('Node not found', HTTP_NOT_FOUND)\n protection_options = ... | <|body_start_0|>
nodeid = int(node_id)
hass = request.app['hass']
network = hass.data.get(const.DATA_NETWORK)
def _fetch_protection():
"""Get protection data."""
node = network.nodes.get(nodeid)
if node is None:
return self.json_messag... | View for the protection commandclass of a node. | ZWaveProtectionView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveProtectionView:
"""View for the protection commandclass of a node."""
async def get(self, request, node_id):
"""Retrieve the protection commandclass options of node."""
<|body_0|>
async def post(self, request, node_id):
"""Change the selected option in prote... | stack_v2_sparse_classes_75kplus_train_070120 | 9,288 | permissive | [
{
"docstring": "Retrieve the protection commandclass options of node.",
"name": "get",
"signature": "async def get(self, request, node_id)"
},
{
"docstring": "Change the selected option in protection commandclass.",
"name": "post",
"signature": "async def post(self, request, node_id)"
... | 2 | null | Implement the Python class `ZWaveProtectionView` described below.
Class description:
View for the protection commandclass of a node.
Method signatures and docstrings:
- async def get(self, request, node_id): Retrieve the protection commandclass options of node.
- async def post(self, request, node_id): Change the sel... | Implement the Python class `ZWaveProtectionView` described below.
Class description:
View for the protection commandclass of a node.
Method signatures and docstrings:
- async def get(self, request, node_id): Retrieve the protection commandclass options of node.
- async def post(self, request, node_id): Change the sel... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ZWaveProtectionView:
"""View for the protection commandclass of a node."""
async def get(self, request, node_id):
"""Retrieve the protection commandclass options of node."""
<|body_0|>
async def post(self, request, node_id):
"""Change the selected option in prote... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZWaveProtectionView:
"""View for the protection commandclass of a node."""
async def get(self, request, node_id):
"""Retrieve the protection commandclass options of node."""
nodeid = int(node_id)
hass = request.app['hass']
network = hass.data.get(const.DATA_NETWORK)
... | the_stack_v2_python_sparse | homeassistant/components/config/zwave.py | BenWoodford/home-assistant | train | 11 |
a605ce88d4a2568468163d1e6c1c4417fc8f0296 | [
"scorer = YahtzeeScorer()\nscorer.add_roll([1, 2, 3, 4, 5], 'r01')\nself.assertFalse(scorer.is_complete())\nscorer.add_roll([1, 2, 3, 4, 5], 'r02')\nscorer.add_roll([1, 2, 3, 4, 5], 'r03')\nscorer.add_roll([1, 2, 3, 4, 5], 'r04')\nscorer.add_roll([1, 2, 3, 4, 5], 'r05')\nscorer.add_roll([1, 2, 3, 4, 5], 'r06')\nsco... | <|body_start_0|>
scorer = YahtzeeScorer()
scorer.add_roll([1, 2, 3, 4, 5], 'r01')
self.assertFalse(scorer.is_complete())
scorer.add_roll([1, 2, 3, 4, 5], 'r02')
scorer.add_roll([1, 2, 3, 4, 5], 'r03')
scorer.add_roll([1, 2, 3, 4, 5], 'r04')
scorer.add_roll([1, 2, ... | YahtzeeScorerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YahtzeeScorerTests:
def test_000(self):
"""Should find max score for example 1 in original problem"""
<|body_0|>
def test_001(self):
"""Should find max score for example 2 in original problem"""
<|body_1|>
def test_003(self):
"""Should find max s... | stack_v2_sparse_classes_75kplus_train_070121 | 16,975 | no_license | [
{
"docstring": "Should find max score for example 1 in original problem",
"name": "test_000",
"signature": "def test_000(self)"
},
{
"docstring": "Should find max score for example 2 in original problem",
"name": "test_001",
"signature": "def test_001(self)"
},
{
"docstring": "Sh... | 3 | null | Implement the Python class `YahtzeeScorerTests` described below.
Class description:
Implement the YahtzeeScorerTests class.
Method signatures and docstrings:
- def test_000(self): Should find max score for example 1 in original problem
- def test_001(self): Should find max score for example 2 in original problem
- de... | Implement the Python class `YahtzeeScorerTests` described below.
Class description:
Implement the YahtzeeScorerTests class.
Method signatures and docstrings:
- def test_000(self): Should find max score for example 1 in original problem
- def test_001(self): Should find max score for example 2 in original problem
- de... | b38c3b7352c74ee5409f58a05274ed40c149ae73 | <|skeleton|>
class YahtzeeScorerTests:
def test_000(self):
"""Should find max score for example 1 in original problem"""
<|body_0|>
def test_001(self):
"""Should find max score for example 2 in original problem"""
<|body_1|>
def test_003(self):
"""Should find max s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YahtzeeScorerTests:
def test_000(self):
"""Should find max score for example 1 in original problem"""
scorer = YahtzeeScorer()
scorer.add_roll([1, 2, 3, 4, 5], 'r01')
self.assertFalse(scorer.is_complete())
scorer.add_roll([1, 2, 3, 4, 5], 'r02')
scorer.add_roll(... | the_stack_v2_python_sparse | src/10149_Yahtzee/yahtzee_tests.py | linus123/PythonPractice | train | 0 | |
b725e8b3cb4875e58a003c9aebb97f99233dfa64 | [
"involvedResidueslist = []\nnumberOfDrawnConstraints = 0\nfor aConstraint in selectedConstraint:\n if not aConstraint.resis[0]['number'] in involvedResidueslist:\n involvedResidueslist.append(aConstraint.resis[0]['number'])\n if not aConstraint.resis[1]['number'] in involvedResidueslist:\n invol... | <|body_start_0|>
involvedResidueslist = []
numberOfDrawnConstraints = 0
for aConstraint in selectedConstraint:
if not aConstraint.resis[0]['number'] in involvedResidueslist:
involvedResidueslist.append(aConstraint.resis[0]['number'])
if not aConstraint.res... | ConstraintDrawer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstraintDrawer:
def drC(self, selectedConstraint, radius, colors):
"""Draw an array of constraints according to the filter defined by user, using the drawConstraint function"""
<|body_0|>
def constraintsDensity(self, selectedConstraints):
"""Calculate number of con... | stack_v2_sparse_classes_75kplus_train_070122 | 4,121 | no_license | [
{
"docstring": "Draw an array of constraints according to the filter defined by user, using the drawConstraint function",
"name": "drC",
"signature": "def drC(self, selectedConstraint, radius, colors)"
},
{
"docstring": "Calculate number of constraints per residue for selected constraints by the... | 3 | stack_v2_sparse_classes_30k_train_040683 | Implement the Python class `ConstraintDrawer` described below.
Class description:
Implement the ConstraintDrawer class.
Method signatures and docstrings:
- def drC(self, selectedConstraint, radius, colors): Draw an array of constraints according to the filter defined by user, using the drawConstraint function
- def c... | Implement the Python class `ConstraintDrawer` described below.
Class description:
Implement the ConstraintDrawer class.
Method signatures and docstrings:
- def drC(self, selectedConstraint, radius, colors): Draw an array of constraints according to the filter defined by user, using the drawConstraint function
- def c... | 68dfa36518bf4689448b15e7db10410a8857e0dd | <|skeleton|>
class ConstraintDrawer:
def drC(self, selectedConstraint, radius, colors):
"""Draw an array of constraints according to the filter defined by user, using the drawConstraint function"""
<|body_0|>
def constraintsDensity(self, selectedConstraints):
"""Calculate number of con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstraintDrawer:
def drC(self, selectedConstraint, radius, colors):
"""Draw an array of constraints according to the filter defined by user, using the drawConstraint function"""
involvedResidueslist = []
numberOfDrawnConstraints = 0
for aConstraint in selectedConstraint:
... | the_stack_v2_python_sparse | Application/Core/ConstraintsDrawing.py | aurbn/PyNMR | train | 1 | |
8eca9004b8cb8ebbf846064d9063fb1a18c325e9 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.dominating_set = set()\nself.cardinality = 0\nself.source = None",
"used = set()\nif source is not None:\n self.source = source\n self.dominating_set.add(source)\n used.add(source)\n used.update(self.grap... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.dominating_set = set()
self.cardinality = 0
self.source = None
<|end_body_0|>
<|body_start_1|>
used = set()
if source is not None:
s... | Find a (unordered sequential) dominating set in O(V+E) time. | UnorderedSequentialDominatingSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_070123 | 977 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001908 | Implement the Python class `UnorderedSequentialDominatingSet` described below.
Class description:
Find a (unordered sequential) dominating set in O(V+E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `UnorderedSequentialDominatingSet` described below.
Class description:
Find a (unordered sequential) dominating set in O(V+E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.dominat... | the_stack_v2_python_sparse | graphtheory/dominatingsets/dsetus.py | kgashok/graphs-dict | train | 0 |
bd030a2455e9cb665bfd392db055bcbb775efa9a | [
"self._theta_E, self._theta_E_error = (theta_E, theta_E_error)\nself._gamma, self._gamma_error = (gamma, gamma_error)\nself._r_eff, self._r_eff_error = (r_eff, r_eff_error)",
"if no_error is True:\n return (self._theta_E, self._gamma, self._r_eff)\ntheta_E_draw = np.maximum(np.random.normal(loc=self._theta_E, ... | <|body_start_0|>
self._theta_E, self._theta_E_error = (theta_E, theta_E_error)
self._gamma, self._gamma_error = (gamma, gamma_error)
self._r_eff, self._r_eff_error = (r_eff, r_eff_error)
<|end_body_0|>
<|body_start_1|>
if no_error is True:
return (self._theta_E, self._gamma,... | class to manage lens and light model posteriors inferred from imaging data | ImageModelPosterior | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageModelPosterior:
"""class to manage lens and light model posteriors inferred from imaging data"""
def __init__(self, theta_E, theta_E_error, gamma, gamma_error, r_eff, r_eff_error):
""":param theta_E: Einstein radius (in arc seconds) :param theta_E_error: 1-sigma error on Einstei... | stack_v2_sparse_classes_75kplus_train_070124 | 1,861 | permissive | [
{
"docstring": ":param theta_E: Einstein radius (in arc seconds) :param theta_E_error: 1-sigma error on Einstein radius :param gamma: power-law slope (2 = isothermal) estimated from imaging data :param gamma_error: 1-sigma uncertainty on power-law slope :param r_eff: half-light radius of the deflector (arc seco... | 2 | stack_v2_sparse_classes_30k_train_012748 | Implement the Python class `ImageModelPosterior` described below.
Class description:
class to manage lens and light model posteriors inferred from imaging data
Method signatures and docstrings:
- def __init__(self, theta_E, theta_E_error, gamma, gamma_error, r_eff, r_eff_error): :param theta_E: Einstein radius (in ar... | Implement the Python class `ImageModelPosterior` described below.
Class description:
class to manage lens and light model posteriors inferred from imaging data
Method signatures and docstrings:
- def __init__(self, theta_E, theta_E_error, gamma, gamma_error, r_eff, r_eff_error): :param theta_E: Einstein radius (in ar... | 3f31c0ae7540387fe98f778035d415c3cff38756 | <|skeleton|>
class ImageModelPosterior:
"""class to manage lens and light model posteriors inferred from imaging data"""
def __init__(self, theta_E, theta_E_error, gamma, gamma_error, r_eff, r_eff_error):
""":param theta_E: Einstein radius (in arc seconds) :param theta_E_error: 1-sigma error on Einstei... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageModelPosterior:
"""class to manage lens and light model posteriors inferred from imaging data"""
def __init__(self, theta_E, theta_E_error, gamma, gamma_error, r_eff, r_eff_error):
""":param theta_E: Einstein radius (in arc seconds) :param theta_E_error: 1-sigma error on Einstein radius :par... | the_stack_v2_python_sparse | hierarc/LensPosterior/imaging_constraints.py | jiwoncpark/hierArc | train | 0 |
11496de7eb4ce898417e2592ff7153fd25b1a861 | [
"self.access_info_list = access_info_list\nself.lease_info = lease_info\nself.open_id = open_id\nself.others_can_delete = others_can_delete\nself.others_can_read = others_can_read\nself.others_can_write = others_can_write",
"if dictionary is None:\n return None\naccess_info_list = dictionary.get('accessInfoLis... | <|body_start_0|>
self.access_info_list = access_info_list
self.lease_info = lease_info
self.open_id = open_id
self.others_can_delete = others_can_delete
self.others_can_read = others_can_read
self.others_can_write = others_can_write
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates the right to read data from the file or named pipe. 'kFileWriteData' indicates ... | SmbActiveOpen | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmbActiveOpen:
"""Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates the right to read data from the file o... | stack_v2_sparse_classes_75kplus_train_070125 | 5,837 | permissive | [
{
"docstring": "Constructor for the SmbActiveOpen class",
"name": "__init__",
"signature": "def __init__(self, access_info_list=None, lease_info=None, open_id=None, others_can_delete=None, others_can_read=None, others_can_write=None)"
},
{
"docstring": "Creates an instance of this model from a d... | 2 | null | Implement the Python class `SmbActiveOpen` described below.
Class description:
Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates... | Implement the Python class `SmbActiveOpen` described below.
Class description:
Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SmbActiveOpen:
"""Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates the right to read data from the file o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmbActiveOpen:
"""Implementation of the 'SmbActiveOpen' model. Specifies an active open of an SMB file, its access and sharing information. Attributes: access_info_list (list of AccessInfoListEnum): Specifies the access information. 'kFileReadData' indicates the right to read data from the file or named pipe.... | the_stack_v2_python_sparse | cohesity_management_sdk/models/smb_active_open.py | cohesity/management-sdk-python | train | 24 |
28c0519ee75d7c79e482660ab3375e05d32d7c21 | [
"relations = VipPermission.objects.filter(vip_id=self.id)\nperm_id_list = [r.perm_id for r in relations]\nreturn Permission.objects.filter(id__in=perm_id_list)",
"try:\n perm = Permission.get(name=perm_name)\nexcept Permission.DoesNotExist:\n return False\nelse:\n return VipPermission.objects.filter(vip_... | <|body_start_0|>
relations = VipPermission.objects.filter(vip_id=self.id)
perm_id_list = [r.perm_id for r in relations]
return Permission.objects.filter(id__in=perm_id_list)
<|end_body_0|>
<|body_start_1|>
try:
perm = Permission.get(name=perm_name)
except Permission.... | Vip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vip:
def permission(self):
"""当前vip具有的所有权限"""
<|body_0|>
def has_perm(self, perm_name):
"""检查该等级vip是否具有某权限"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
relations = VipPermission.objects.filter(vip_id=self.id)
perm_id_list = [r.perm_id for... | stack_v2_sparse_classes_75kplus_train_070126 | 1,410 | no_license | [
{
"docstring": "当前vip具有的所有权限",
"name": "permission",
"signature": "def permission(self)"
},
{
"docstring": "检查该等级vip是否具有某权限",
"name": "has_perm",
"signature": "def has_perm(self, perm_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012178 | Implement the Python class `Vip` described below.
Class description:
Implement the Vip class.
Method signatures and docstrings:
- def permission(self): 当前vip具有的所有权限
- def has_perm(self, perm_name): 检查该等级vip是否具有某权限 | Implement the Python class `Vip` described below.
Class description:
Implement the Vip class.
Method signatures and docstrings:
- def permission(self): 当前vip具有的所有权限
- def has_perm(self, perm_name): 检查该等级vip是否具有某权限
<|skeleton|>
class Vip:
def permission(self):
"""当前vip具有的所有权限"""
<|body_0|>
d... | 8fc2f597fad912ef0bb10bed440a337e0b7b4625 | <|skeleton|>
class Vip:
def permission(self):
"""当前vip具有的所有权限"""
<|body_0|>
def has_perm(self, perm_name):
"""检查该等级vip是否具有某权限"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vip:
def permission(self):
"""当前vip具有的所有权限"""
relations = VipPermission.objects.filter(vip_id=self.id)
perm_id_list = [r.perm_id for r in relations]
return Permission.objects.filter(id__in=perm_id_list)
def has_perm(self, perm_name):
"""检查该等级vip是否具有某权限"""
t... | the_stack_v2_python_sparse | fuck/vip/models.py | Luciano0000/social | train | 3 | |
9b92dc0b379db4926a215944e524fdb08c05f14c | [
"a, b = (rand7(), rand7())\nwhile a > 6:\n a = rand7()\nwhile b > 5:\n b = rand7()\nreturn 0 + b if a & 1 else 5 + b",
"while True:\n res = (rand7() - 1) * 7 + rand7()\n if res <= 40:\n break\nreturn res % 10 + 1"
] | <|body_start_0|>
a, b = (rand7(), rand7())
while a > 6:
a = rand7()
while b > 5:
b = rand7()
return 0 + b if a & 1 else 5 + b
<|end_body_0|>
<|body_start_1|>
while True:
res = (rand7() - 1) * 7 + rand7()
if res <= 40:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rand10(self):
""":rtype: int"""
<|body_0|>
def rand10n(self):
"""拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且等概。 记住就完事了,xdm"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a, b = (rand7(), rand7())
while a > 6:
... | stack_v2_sparse_classes_75kplus_train_070127 | 835 | permissive | [
{
"docstring": ":rtype: int",
"name": "rand10",
"signature": "def rand10(self)"
},
{
"docstring": "拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且等概。 记住就完事了,xdm",
"name": "rand10n",
"signature": "def rand10n(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017274 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): :rtype: int
- def rand10n(self): 拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且等概。 记住就完事了,xdm | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): :rtype: int
- def rand10n(self): 拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且等概。 记住就完事了,xdm
<|skeleton|>
class Solution:
def rand10(self):
... | cb13caa0159f0179d3c1bacfb1801d156c7d1344 | <|skeleton|>
class Solution:
def rand10(self):
""":rtype: int"""
<|body_0|>
def rand10n(self):
"""拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且等概。 记住就完事了,xdm"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rand10(self):
""":rtype: int"""
a, b = (rand7(), rand7())
while a > 6:
a = rand7()
while b > 5:
b = rand7()
return 0 + b if a & 1 else 5 + b
def rand10n(self):
"""拒绝采样, 主要公式为 (rand(X)-1)*Y + randY() -----生成 [1,X*Y]区间,并且... | the_stack_v2_python_sparse | 力扣习题/470用 Rand7() 实现 Rand10()/implementrand10usingrand7.py | lollipopnougat/AlgorithmLearning | train | 7 | |
3086d55427065efe16993d88c85000cf1890bf2c | [
"n = len(nums)\nmaxRange = getRange(nums, isMax=True, isRightStrict=True)\nminRange = getRange(nums, isMax=False, isRightStrict=False)\nadjMap = defaultdict(lambda: defaultdict(lambda: INF))\nfor cur, (next1, next2) in enumerate(zip(maxRange, minRange)):\n next1, next2 = (next1 + 1, next2 + 1)\n adjMap[cur][n... | <|body_start_0|>
n = len(nums)
maxRange = getRange(nums, isMax=True, isRightStrict=True)
minRange = getRange(nums, isMax=False, isRightStrict=False)
adjMap = defaultdict(lambda: defaultdict(lambda: INF))
for cur, (next1, next2) in enumerate(zip(maxRange, minRange)):
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCost(self, nums: List[int], costs: List[int]) -> int:
"""dijk求最短路 1188 ms"""
<|body_0|>
def minCost2(self, nums: List[int], costs: List[int]) -> int:
"""dfs求最短路 1584 ms"""
<|body_1|>
def minCost3(self, nums: List[int], costs: List[int]) ... | stack_v2_sparse_classes_75kplus_train_070128 | 4,791 | no_license | [
{
"docstring": "dijk求最短路 1188 ms",
"name": "minCost",
"signature": "def minCost(self, nums: List[int], costs: List[int]) -> int"
},
{
"docstring": "dfs求最短路 1584 ms",
"name": "minCost2",
"signature": "def minCost2(self, nums: List[int], costs: List[int]) -> int"
},
{
"docstring": ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCost(self, nums: List[int], costs: List[int]) -> int: dijk求最短路 1188 ms
- def minCost2(self, nums: List[int], costs: List[int]) -> int: dfs求最短路 1584 ms
- def minCost3(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCost(self, nums: List[int], costs: List[int]) -> int: dijk求最短路 1188 ms
- def minCost2(self, nums: List[int], costs: List[int]) -> int: dfs求最短路 1584 ms
- def minCost3(self,... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def minCost(self, nums: List[int], costs: List[int]) -> int:
"""dijk求最短路 1188 ms"""
<|body_0|>
def minCost2(self, nums: List[int], costs: List[int]) -> int:
"""dfs求最短路 1584 ms"""
<|body_1|>
def minCost3(self, nums: List[int], costs: List[int]) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minCost(self, nums: List[int], costs: List[int]) -> int:
"""dijk求最短路 1188 ms"""
n = len(nums)
maxRange = getRange(nums, isMax=True, isRightStrict=True)
minRange = getRange(nums, isMax=False, isRightStrict=False)
adjMap = defaultdict(lambda: defaultdict(lam... | the_stack_v2_python_sparse | 7_graph/拓扑排序/拓扑序dp/2297. Jump Game IX-拓扑图最短路O(n).py | 981377660LMT/algorithm-study | train | 225 | |
9805039ed80b415f06348d2180c36158d26ca0d2 | [
"self.monoBERT_score_transform = monoBERT_Scorer_Transform(checkpoint_dir, **kwargs)\nself.doc_resolver_transform = Document_Resolver_Transform(get_doc_fn)\nself.monoBERT_numericalise_transform = MonoBERT_Numericalise_Transform(**kwargs)\nself.key_fields = key_fields",
"for sample_obj in tqdm(samples, desc='Reran... | <|body_start_0|>
self.monoBERT_score_transform = monoBERT_Scorer_Transform(checkpoint_dir, **kwargs)
self.doc_resolver_transform = Document_Resolver_Transform(get_doc_fn)
self.monoBERT_numericalise_transform = MonoBERT_Numericalise_Transform(**kwargs)
self.key_fields = key_fields
<|end_b... | MonoBERT_ReRanker_Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonoBERT_ReRanker_Transform:
def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field': 'search_results'}, **kwargs):
"""A Transform that reorders a list based on BERT query doc score checkpoint_path: str: path to only the state dict of the model, ... | stack_v2_sparse_classes_75kplus_train_070129 | 24,876 | no_license | [
{
"docstring": "A Transform that reorders a list based on BERT query doc score checkpoint_path: str: path to only the state dict of the model, loaded with load_state_dict",
"name": "__init__",
"signature": "def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field'... | 2 | stack_v2_sparse_classes_30k_train_010295 | Implement the Python class `MonoBERT_ReRanker_Transform` described below.
Class description:
Implement the MonoBERT_ReRanker_Transform class.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field': 'search_results'}, **kwargs): A Transform... | Implement the Python class `MonoBERT_ReRanker_Transform` described below.
Class description:
Implement the MonoBERT_ReRanker_Transform class.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field': 'search_results'}, **kwargs): A Transform... | 92dd4d41ad6f2be5b5c4e296e2a355bb14b9a1db | <|skeleton|>
class MonoBERT_ReRanker_Transform:
def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field': 'search_results'}, **kwargs):
"""A Transform that reorders a list based on BERT query doc score checkpoint_path: str: path to only the state dict of the model, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonoBERT_ReRanker_Transform:
def __init__(self, checkpoint_dir, get_doc_fn, key_fields={'query_field': 'query', 'target_field': 'search_results'}, **kwargs):
"""A Transform that reorders a list based on BERT query doc score checkpoint_path: str: path to only the state dict of the model, loaded with lo... | the_stack_v2_python_sparse | notebooks/src/models_and_transforms/complex_transforms.py | carlos-gemmell/Glasgow-NLP | train | 0 | |
a196d1be0fcce7aa4331ddcfc49ee640f3ef8a64 | [
"self.latlon: List[float]\nself.position: NDArrayF64\nself.roll: float\nself.pitch: float\nself.yaw: float\nself.rotation: NDArrayF64\nif fields is not None:\n self.set_oxt(fields)",
"fields = [float(f) for f in fields_str]\nself.latlon = fields[:2]\nassert utm is not None, 'KITTI conversion requires utm to be... | <|body_start_0|>
self.latlon: List[float]
self.position: NDArrayF64
self.roll: float
self.pitch: float
self.yaw: float
self.rotation: NDArrayF64
if fields is not None:
self.set_oxt(fields)
<|end_body_0|>
<|body_start_1|>
fields = [float(f) for... | Calibration matrices in KITTI. | KittiPoseParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KittiPoseParser:
"""Calibration matrices in KITTI."""
def __init__(self, fields: List[str]) -> None:
"""Init parameters and set pose with fields."""
<|body_0|>
def set_oxt(self, fields_str: List[str]) -> None:
"""Assign the pose information from corresponding fie... | stack_v2_sparse_classes_75kplus_train_070130 | 4,561 | permissive | [
{
"docstring": "Init parameters and set pose with fields.",
"name": "__init__",
"signature": "def __init__(self, fields: List[str]) -> None"
},
{
"docstring": "Assign the pose information from corresponding fields. Input: fields: list of oxts information",
"name": "set_oxt",
"signature":... | 2 | null | Implement the Python class `KittiPoseParser` described below.
Class description:
Calibration matrices in KITTI.
Method signatures and docstrings:
- def __init__(self, fields: List[str]) -> None: Init parameters and set pose with fields.
- def set_oxt(self, fields_str: List[str]) -> None: Assign the pose information f... | Implement the Python class `KittiPoseParser` described below.
Class description:
Calibration matrices in KITTI.
Method signatures and docstrings:
- def __init__(self, fields: List[str]) -> None: Init parameters and set pose with fields.
- def set_oxt(self, fields_str: List[str]) -> None: Assign the pose information f... | 96ad0fffe06a3c9bdd83453c8ec9b70cbbbde641 | <|skeleton|>
class KittiPoseParser:
"""Calibration matrices in KITTI."""
def __init__(self, fields: List[str]) -> None:
"""Init parameters and set pose with fields."""
<|body_0|>
def set_oxt(self, fields_str: List[str]) -> None:
"""Assign the pose information from corresponding fie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KittiPoseParser:
"""Calibration matrices in KITTI."""
def __init__(self, fields: List[str]) -> None:
"""Init parameters and set pose with fields."""
self.latlon: List[float]
self.position: NDArrayF64
self.roll: float
self.pitch: float
self.yaw: float
... | the_stack_v2_python_sparse | scalabel/label/kitti_utlis.py | scalabel/scalabel | train | 530 |
d1eeeef9328629e21653fd9f3130ad41dd8fc7d6 | [
"self._use_polld = use_polld\nself._server = None\nif use_polld:\n remote = 'http://%s:%s' % (host, tcp_port)\n self._server = net_utils.TimeoutXMLRPCServerProxy(remote, timeout=timeout, verbose=verbose)",
"if edge not in self.GPIO_EDGE_LIST:\n raise GpioManagerError('Invalid edge %r. Valid values: %r' %... | <|body_start_0|>
self._use_polld = use_polld
self._server = None
if use_polld:
remote = 'http://%s:%s' % (host, tcp_port)
self._server = net_utils.TimeoutXMLRPCServerProxy(remote, timeout=timeout, verbose=verbose)
<|end_body_0|>
<|body_start_1|>
if edge not in se... | GPIO monitor and control manager. | GpioManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP a... | stack_v2_sparse_classes_75kplus_train_070131 | 11,503 | permissive | [
{
"docstring": "Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP address of servo server host. tcp_port: TCP port on which servod is listening on. timeout: Timeout for HTTP connection. verbose: Enables verbose messagin... | 4 | stack_v2_sparse_classes_30k_train_025971 | Implement the Python class `GpioManager` described below.
Class description:
GPIO monitor and control manager.
Method signatures and docstrings:
- def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False): Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or Fal... | Implement the Python class `GpioManager` described below.
Class description:
GPIO monitor and control manager.
Method signatures and docstrings:
- def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False): Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or Fal... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP address of ser... | the_stack_v2_python_sparse | py/utils/gpio_utils.py | bridder/factory | train | 0 |
c7c738300ee496a769b10d440a712d3b072f78fb | [
"self.create_pre_authenticated_session('abc@163.com')\nself.browser.get(self.live_server_url)\nself.wait_for(lambda: self.assertEqual(self.browser.find_element_by_css_selector('#id_jumbotron > h1').text, '新建待办事项'))\nself.wait_for(lambda: self.assertEqual(self.browser.find_element_by_css_selector('#id_my_lists > .pa... | <|body_start_0|>
self.create_pre_authenticated_session('abc@163.com')
self.browser.get(self.live_server_url)
self.wait_for(lambda: self.assertEqual(self.browser.find_element_by_css_selector('#id_jumbotron > h1').text, '新建待办事项'))
self.wait_for(lambda: self.assertEqual(self.browser.find_el... | 我的清单测试 | MyListsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyListsTest:
"""我的清单测试"""
def test_001(self):
"""登录用户没有创建任何清单时,我的清单列表显示没有清单"""
<|body_0|>
def test_002(self):
"""登录用户可以新建清单,然后在我的清单列显示 退出登录后,将不再显示我的清单"""
<|body_1|>
def test_003(self):
"""匿名用户无法显示我的清单"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_070132 | 5,028 | no_license | [
{
"docstring": "登录用户没有创建任何清单时,我的清单列表显示没有清单",
"name": "test_001",
"signature": "def test_001(self)"
},
{
"docstring": "登录用户可以新建清单,然后在我的清单列显示 退出登录后,将不再显示我的清单",
"name": "test_002",
"signature": "def test_002(self)"
},
{
"docstring": "匿名用户无法显示我的清单",
"name": "test_003",
"signa... | 3 | stack_v2_sparse_classes_30k_train_043559 | Implement the Python class `MyListsTest` described below.
Class description:
我的清单测试
Method signatures and docstrings:
- def test_001(self): 登录用户没有创建任何清单时,我的清单列表显示没有清单
- def test_002(self): 登录用户可以新建清单,然后在我的清单列显示 退出登录后,将不再显示我的清单
- def test_003(self): 匿名用户无法显示我的清单 | Implement the Python class `MyListsTest` described below.
Class description:
我的清单测试
Method signatures and docstrings:
- def test_001(self): 登录用户没有创建任何清单时,我的清单列表显示没有清单
- def test_002(self): 登录用户可以新建清单,然后在我的清单列显示 退出登录后,将不再显示我的清单
- def test_003(self): 匿名用户无法显示我的清单
<|skeleton|>
class MyListsTest:
"""我的清单测试"""
d... | 973b3afb239db5f55cb52897e7a8a241a459349f | <|skeleton|>
class MyListsTest:
"""我的清单测试"""
def test_001(self):
"""登录用户没有创建任何清单时,我的清单列表显示没有清单"""
<|body_0|>
def test_002(self):
"""登录用户可以新建清单,然后在我的清单列显示 退出登录后,将不再显示我的清单"""
<|body_1|>
def test_003(self):
"""匿名用户无法显示我的清单"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyListsTest:
"""我的清单测试"""
def test_001(self):
"""登录用户没有创建任何清单时,我的清单列表显示没有清单"""
self.create_pre_authenticated_session('abc@163.com')
self.browser.get(self.live_server_url)
self.wait_for(lambda: self.assertEqual(self.browser.find_element_by_css_selector('#id_jumbotron > h1')... | the_stack_v2_python_sparse | functional_tests/test_lists/test_my_lists.py | aaluo001/superlists | train | 0 |
deb205ba7e0ebde9727ba76a8ae2e43aa8068d9d | [
"user = get_user_from_username(request.user, username)\nis_self = user == request.user\nif is_self:\n shelves = user.shelf_set.all()\nelse:\n shelves = models.Shelf.privacy_filter(request.user).filter(user=user).all()\nif shelf_identifier:\n shelf = get_object_or_404(user.shelf_set, identifier=shelf_identi... | <|body_start_0|>
user = get_user_from_username(request.user, username)
is_self = user == request.user
if is_self:
shelves = user.shelf_set.all()
else:
shelves = models.Shelf.privacy_filter(request.user).filter(user=user).all()
if shelf_identifier:
... | shelf page | Shelf | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shelf:
"""shelf page"""
def get(self, request, username, shelf_identifier=None):
"""display a shelf"""
<|body_0|>
def post(self, request, username, shelf_identifier):
"""edit a shelf"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = get_use... | stack_v2_sparse_classes_75kplus_train_070133 | 5,096 | no_license | [
{
"docstring": "display a shelf",
"name": "get",
"signature": "def get(self, request, username, shelf_identifier=None)"
},
{
"docstring": "edit a shelf",
"name": "post",
"signature": "def post(self, request, username, shelf_identifier)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040952 | Implement the Python class `Shelf` described below.
Class description:
shelf page
Method signatures and docstrings:
- def get(self, request, username, shelf_identifier=None): display a shelf
- def post(self, request, username, shelf_identifier): edit a shelf | Implement the Python class `Shelf` described below.
Class description:
shelf page
Method signatures and docstrings:
- def get(self, request, username, shelf_identifier=None): display a shelf
- def post(self, request, username, shelf_identifier): edit a shelf
<|skeleton|>
class Shelf:
"""shelf page"""
def ge... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Shelf:
"""shelf page"""
def get(self, request, username, shelf_identifier=None):
"""display a shelf"""
<|body_0|>
def post(self, request, username, shelf_identifier):
"""edit a shelf"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Shelf:
"""shelf page"""
def get(self, request, username, shelf_identifier=None):
"""display a shelf"""
user = get_user_from_username(request.user, username)
is_self = user == request.user
if is_self:
shelves = user.shelf_set.all()
else:
shel... | the_stack_v2_python_sparse | bookwyrm/views/shelf/shelf.py | bookwyrm-social/bookwyrm | train | 1,398 |
1f6f4b9fdbc4758ecf8b23b43f45dfea993ffcb1 | [
"from ..jobfolder.ordered_dict import OrderedDict\nsuper(RelaxExtract.IntermediateMassExtract, self).__init__(*args, **kwargs)\nself.dicttype = OrderedDict\n' Type of dictionary to use. \\n \\n Always ordered dictionary for intermediate mass extraction.\\n Makes it easier to explore ongoing c... | <|body_start_0|>
from ..jobfolder.ordered_dict import OrderedDict
super(RelaxExtract.IntermediateMassExtract, self).__init__(*args, **kwargs)
self.dicttype = OrderedDict
' Type of dictionary to use. \n \n Always ordered dictionary for intermediate mass extraction.\n ... | Focuses on intermediate steps. | IntermediateMassExtract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntermediateMassExtract:
"""Focuses on intermediate steps."""
def __init__(self, *args, **kwargs):
"""Makes sure we are using ordered dict."""
<|body_0|>
def __getitem__(self, value):
"""Gets intermediate step. Adds ability to get runs as numbers: ``self.details[... | stack_v2_sparse_classes_75kplus_train_070134 | 6,637 | no_license | [
{
"docstring": "Makes sure we are using ordered dict.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Gets intermediate step. Adds ability to get runs as numbers: ``self.details[0]`` is equivalent to ``self.details['relax/0']``",
"name": "__getitem... | 4 | stack_v2_sparse_classes_30k_train_046612 | Implement the Python class `IntermediateMassExtract` described below.
Class description:
Focuses on intermediate steps.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Makes sure we are using ordered dict.
- def __getitem__(self, value): Gets intermediate step. Adds ability to get runs as num... | Implement the Python class `IntermediateMassExtract` described below.
Class description:
Focuses on intermediate steps.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Makes sure we are using ordered dict.
- def __getitem__(self, value): Gets intermediate step. Adds ability to get runs as num... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class IntermediateMassExtract:
"""Focuses on intermediate steps."""
def __init__(self, *args, **kwargs):
"""Makes sure we are using ordered dict."""
<|body_0|>
def __getitem__(self, value):
"""Gets intermediate step. Adds ability to get runs as numbers: ``self.details[... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntermediateMassExtract:
"""Focuses on intermediate steps."""
def __init__(self, *args, **kwargs):
"""Makes sure we are using ordered dict."""
from ..jobfolder.ordered_dict import OrderedDict
super(RelaxExtract.IntermediateMassExtract, self).__init__(*args, **kwargs)
self.... | the_stack_v2_python_sparse | dftcrystal/relax.py | Shibu778/LaDa | train | 0 |
b20abfa3f5bed7c39e8bdd49ae471838bab7b6a0 | [
"def create_partition(i, j):\n return cls.frame_partition_cls(GPU_MANAGERS[i], partition_ids[i][j], length=row_lengths[i], width=column_widths[j])\nreturn np.array([[create_partition(i, j) for j in range(len(partition_ids[i]))] for i in range(len(partition_ids))])",
"partition_ids = [None] * len(splits)\nindex... | <|body_start_0|>
def create_partition(i, j):
return cls.frame_partition_cls(GPU_MANAGERS[i], partition_ids[i][j], length=row_lengths[i], width=column_widths[j])
return np.array([[create_partition(i, j) for j in range(len(partition_ids[i]))] for i in range(len(partition_ids))])
<|end_body_0|>... | The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files. | cuDFCSVDispatcher | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parame... | stack_v2_sparse_classes_75kplus_train_070135 | 3,694 | permissive | [
{
"docstring": "Build array with partitions of `cls.frame_partition_cls` class. Parameters ---------- partition_ids : list Array with references to the partitions data. row_lengths : list Partitions rows lengths. column_widths : list Number of columns in each partition. Returns ------- np.ndarray Array with sha... | 2 | stack_v2_sparse_classes_30k_test_000630 | Implement the Python class `cuDFCSVDispatcher` described below.
Class description:
The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files.
Method signatures and docstrings:
- def build_partition(cls, partition_ids, row_lengths, column_widths): Build array w... | Implement the Python class `cuDFCSVDispatcher` described below.
Class description:
The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files.
Method signatures and docstrings:
- def build_partition(cls, partition_ids, row_lengths, column_widths): Build array w... | 8f6e00378e095817deccd25f4140406c5ee6c992 | <|skeleton|>
class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class cuDFCSVDispatcher:
"""The class implements ``CSVDispatcher`` using cuDF storage format. This class handles utils for reading `.csv` files."""
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""Build array with partitions of `cls.frame_partition_cls` class. Parameters --------... | the_stack_v2_python_sparse | modin/core/execution/ray/implementations/cudf_on_ray/io/text/csv_dispatcher.py | modin-project/modin | train | 9,241 |
f15d972eebf12c71ace79742cfb238f358c6d45c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserRegistrationDetails()",
"from .entity import Entity\nfrom .sign_in_user_type import SignInUserType\nfrom .user_default_authentication_method import UserDefaultAuthenticationMethod\nfrom .entity import Entity\nfrom .sign_in_user_typ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserRegistrationDetails()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .sign_in_user_type import SignInUserType
from .user_default_authentication_method import... | UserRegistrationDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationDetails:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_75kplus_train_070136 | 9,218 | 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: UserRegistrationDetails",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_023459 | Implement the Python class `UserRegistrationDetails` described below.
Class description:
Implement the UserRegistrationDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationDetails: Creates a new instance of the appropriate clas... | Implement the Python class `UserRegistrationDetails` described below.
Class description:
Implement the UserRegistrationDetails class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationDetails: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserRegistrationDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationDetails:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRegistrationDetails:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationDetails:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/user_registration_details.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2c106e5134f644cc041c4d800963aa376c2e7672 | [
"res = self.client.command('/username bob')\nself.client.command('/exit')\nself.assertEqual(res, '/username ok')",
"other = SimpleClient(SERVER_HOST, SERVER_PORT)\nother.command('/username bob')\nres = self.client.command('/username bob')\nother.command('/exit')\nself.client.command('/exit')\nself.assertEqual(res... | <|body_start_0|>
res = self.client.command('/username bob')
self.client.command('/exit')
self.assertEqual(res, '/username ok')
<|end_body_0|>
<|body_start_1|>
other = SimpleClient(SERVER_HOST, SERVER_PORT)
other.command('/username bob')
res = self.client.command('/userna... | Tests the protocol for starting the chat. | TestChatProtocolStart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChatProtocolStart:
"""Tests the protocol for starting the chat."""
def testProvideUsername(self):
"""Clients must provide a username."""
<|body_0|>
def testUniqueUsername(self):
"""Clients must provide an unique username."""
<|body_1|>
def testMu... | stack_v2_sparse_classes_75kplus_train_070137 | 11,819 | no_license | [
{
"docstring": "Clients must provide a username.",
"name": "testProvideUsername",
"signature": "def testProvideUsername(self)"
},
{
"docstring": "Clients must provide an unique username.",
"name": "testUniqueUsername",
"signature": "def testUniqueUsername(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_051369 | Implement the Python class `TestChatProtocolStart` described below.
Class description:
Tests the protocol for starting the chat.
Method signatures and docstrings:
- def testProvideUsername(self): Clients must provide a username.
- def testUniqueUsername(self): Clients must provide an unique username.
- def testMustPr... | Implement the Python class `TestChatProtocolStart` described below.
Class description:
Tests the protocol for starting the chat.
Method signatures and docstrings:
- def testProvideUsername(self): Clients must provide a username.
- def testUniqueUsername(self): Clients must provide an unique username.
- def testMustPr... | d27b122c87131789178f77e6f693b718dd57c594 | <|skeleton|>
class TestChatProtocolStart:
"""Tests the protocol for starting the chat."""
def testProvideUsername(self):
"""Clients must provide a username."""
<|body_0|>
def testUniqueUsername(self):
"""Clients must provide an unique username."""
<|body_1|>
def testMu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestChatProtocolStart:
"""Tests the protocol for starting the chat."""
def testProvideUsername(self):
"""Clients must provide a username."""
res = self.client.command('/username bob')
self.client.command('/exit')
self.assertEqual(res, '/username ok')
def testUniqueUse... | the_stack_v2_python_sparse | 2º Ano/2º Semestre/Computação Distribuida/Projectos/tp2-team-alexandrecoelho-sergioverissimo-t2/tests.py | alexmpc98/Engenharia-Informatica-IPS | train | 4 |
c5b10117db60a7b57d69c366be998e962a58f27d | [
"super(TimeoutError, self).__init__(message=message, original_exception=original_exception)\nself.uri = uri\nself.error_code = error_code",
"if self.uri:\n msg = 'Timed out when requesting {0:s} from API'.format(self.uri)\n if self.error_code:\n msg += ' with HTTP status code {0:d}'.format(self.error... | <|body_start_0|>
super(TimeoutError, self).__init__(message=message, original_exception=original_exception)
self.uri = uri
self.error_code = error_code
<|end_body_0|>
<|body_start_1|>
if self.uri:
msg = 'Timed out when requesting {0:s} from API'.format(self.uri)
... | A requested operation timed out. | TimeoutError | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeoutError:
"""A requested operation timed out."""
def __init__(self, uri=None, error_code=None, message=None, original_exception=None):
"""Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. error_code (int): The error code that was received from th... | stack_v2_sparse_classes_75kplus_train_070138 | 8,094 | permissive | [
{
"docstring": "Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. error_code (int): The error code that was received from the server. message (str): The error message. original_exception (Exception): The exception that caused this one to be raised.",
"name": "__init__",
... | 2 | null | Implement the Python class `TimeoutError` described below.
Class description:
A requested operation timed out.
Method signatures and docstrings:
- def __init__(self, uri=None, error_code=None, message=None, original_exception=None): Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. e... | Implement the Python class `TimeoutError` described below.
Class description:
A requested operation timed out.
Method signatures and docstrings:
- def __init__(self, uri=None, error_code=None, message=None, original_exception=None): Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. e... | 32dd08d2185f7113f87834002e720db31c8c910e | <|skeleton|>
class TimeoutError:
"""A requested operation timed out."""
def __init__(self, uri=None, error_code=None, message=None, original_exception=None):
"""Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. error_code (int): The error code that was received from th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeoutError:
"""A requested operation timed out."""
def __init__(self, uri=None, error_code=None, message=None, original_exception=None):
"""Initialize the TimeoutError. Args: uri (str): The URI of the action that timed out. error_code (int): The error code that was received from the server. mes... | the_stack_v2_python_sparse | src/cbapi/errors.py | carbonblack/cbapi-python | train | 158 |
99760d35ae7cf7aa25e48dda9fdbef9324520da7 | [
"if not str1 or not str2:\n return str1 if str1 else str2\nelif len(str1) < len(str2):\n return self.gcdOfStrings(str2, str1)\nelif str1[:len(str2)] == str2:\n return self.gcdOfStrings(str1[len(str2):], str2)\nelse:\n return ''",
"def gcd(a, b):\n return b if a == 0 else gcd(b % a, a)\nd = gcd(len(... | <|body_start_0|>
if not str1 or not str2:
return str1 if str1 else str2
elif len(str1) < len(str2):
return self.gcdOfStrings(str2, str1)
elif str1[:len(str2)] == str2:
return self.gcdOfStrings(str1[len(str2):], str2)
else:
return ''
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def gcdOfStrings(self, str1, str2):
"""Recursive version :type str1: str :type str2: str :rtype: str"""
<|body_0|>
def gcdOfStrings1(self, str1, str2):
"""Iterative version :type str1: str :type str2: str :rtype: str"""
<|body_1|>
def gcdOfStri... | stack_v2_sparse_classes_75kplus_train_070139 | 1,442 | no_license | [
{
"docstring": "Recursive version :type str1: str :type str2: str :rtype: str",
"name": "gcdOfStrings",
"signature": "def gcdOfStrings(self, str1, str2)"
},
{
"docstring": "Iterative version :type str1: str :type str2: str :rtype: str",
"name": "gcdOfStrings1",
"signature": "def gcdOfStr... | 3 | stack_v2_sparse_classes_30k_train_011287 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gcdOfStrings(self, str1, str2): Recursive version :type str1: str :type str2: str :rtype: str
- def gcdOfStrings1(self, str1, str2): Iterative version :type str1: str :type s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gcdOfStrings(self, str1, str2): Recursive version :type str1: str :type str2: str :rtype: str
- def gcdOfStrings1(self, str1, str2): Iterative version :type str1: str :type s... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def gcdOfStrings(self, str1, str2):
"""Recursive version :type str1: str :type str2: str :rtype: str"""
<|body_0|>
def gcdOfStrings1(self, str1, str2):
"""Iterative version :type str1: str :type str2: str :rtype: str"""
<|body_1|>
def gcdOfStri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def gcdOfStrings(self, str1, str2):
"""Recursive version :type str1: str :type str2: str :rtype: str"""
if not str1 or not str2:
return str1 if str1 else str2
elif len(str1) < len(str2):
return self.gcdOfStrings(str2, str1)
elif str1[:len(str2)... | the_stack_v2_python_sparse | LeetCode/String/1071_greatest_common_divisor_of_strings.py | XyK0907/for_work | train | 0 | |
4340dd66bcde24d69612221e614fab24b196fbd5 | [
"category = []\ntry:\n cates = Category.objects.filter(super_category__isnull=True)\nexcept Exception as e:\n management_logger.error(e)\n return JsonResponse({'errcode': '102', 'errmsg': 'Db error'})\nfor cate in cates:\n try:\n sub_cates = Category.objects.filter(super_category__id=cate.id)\n ... | <|body_start_0|>
category = []
try:
cates = Category.objects.filter(super_category__isnull=True)
except Exception as e:
management_logger.error(e)
return JsonResponse({'errcode': '102', 'errmsg': 'Db error'})
for cate in cates:
try:
... | CategoriesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoriesView:
def get(self, request, user):
"""获取分类"""
<|body_0|>
def post(self, request, user):
"""创建分类"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
category = []
try:
cates = Category.objects.filter(super_category__isnull=... | stack_v2_sparse_classes_75kplus_train_070140 | 23,350 | no_license | [
{
"docstring": "获取分类",
"name": "get",
"signature": "def get(self, request, user)"
},
{
"docstring": "创建分类",
"name": "post",
"signature": "def post(self, request, user)"
}
] | 2 | null | Implement the Python class `CategoriesView` described below.
Class description:
Implement the CategoriesView class.
Method signatures and docstrings:
- def get(self, request, user): 获取分类
- def post(self, request, user): 创建分类 | Implement the Python class `CategoriesView` described below.
Class description:
Implement the CategoriesView class.
Method signatures and docstrings:
- def get(self, request, user): 获取分类
- def post(self, request, user): 创建分类
<|skeleton|>
class CategoriesView:
def get(self, request, user):
"""获取分类"""
... | e35f98cd7e12f151c3de408e760666f5583386e5 | <|skeleton|>
class CategoriesView:
def get(self, request, user):
"""获取分类"""
<|body_0|>
def post(self, request, user):
"""创建分类"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoriesView:
def get(self, request, user):
"""获取分类"""
category = []
try:
cates = Category.objects.filter(super_category__isnull=True)
except Exception as e:
management_logger.error(e)
return JsonResponse({'errcode': '102', 'errmsg': 'Db er... | the_stack_v2_python_sparse | management/goods/views.py | cookie-rabbit/lovefamily-django | train | 1 | |
9fd626af541d89c0687f091151f430c86ffbf94c | [
"def isPalindrome(t, start, end):\n while end < len(t) and start >= 0 and (t[start] == t[end]):\n start -= 1\n end += 1\n return end - start - 1\nc = -1\nstart = 0\nend = 1\nfor i in range(len(s)):\n l1 = isPalindrome(s, i, i)\n l2 = isPalindrome(s, i, i + 1)\n l = max(l1, l2)\n if l... | <|body_start_0|>
def isPalindrome(t, start, end):
while end < len(t) and start >= 0 and (t[start] == t[end]):
start -= 1
end += 1
return end - start - 1
c = -1
start = 0
end = 1
for i in range(len(s)):
l1 = isPal... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def isPalindrome(t, start, end):
while end ... | stack_v2_sparse_classes_75kplus_train_070141 | 1,613 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome_1",
"signature": "def longestPalindrome_1(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050279 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome_1(s... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
def isPalindrome(t, start, end):
while end < len(t) and start >= 0 and (t[start] == t[end]):
start -= 1
end += 1
return end - start - 1
c = -1
star... | the_stack_v2_python_sparse | PythonCode/src/0005_Longest_Palindromic_Substring.py | oneyuan/CodeforFun | train | 0 | |
4b86cd558773cd5032747ddd57352d0666385f65 | [
"self.static_result = static_result\nif dynamic_results is None:\n self.dynamic_results = []\nelse:\n self.dynamic_results = dynamic_results",
"if self.static_result is not None:\n spr_po = self.static_result.to_static_profile_result_po()\nelse:\n spr_po = None\nif self.dynamic_results is not None:\n ... | <|body_start_0|>
self.static_result = static_result
if dynamic_results is None:
self.dynamic_results = []
else:
self.dynamic_results = dynamic_results
<|end_body_0|>
<|body_start_1|>
if self.static_result is not None:
spr_po = self.static_result.to_st... | Profiling result business object. | ProfileResultBO | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileResultBO:
"""Profiling result business object."""
def __init__(self, static_result: StaticProfileResultBO, dynamic_results: List[DynamicProfileResultBO]=None):
"""Initializer. Args: static_result (StaticProfileResultBO): static profiling result business object. dynamic_results... | stack_v2_sparse_classes_75kplus_train_070142 | 2,253 | permissive | [
{
"docstring": "Initializer. Args: static_result (StaticProfileResultBO): static profiling result business object. dynamic_results (Optional[Iterable[DynamicProfileResultBO]]): a list of dynamic profiling result business object. Default to an empty list.",
"name": "__init__",
"signature": "def __init__(... | 3 | stack_v2_sparse_classes_30k_train_013884 | Implement the Python class `ProfileResultBO` described below.
Class description:
Profiling result business object.
Method signatures and docstrings:
- def __init__(self, static_result: StaticProfileResultBO, dynamic_results: List[DynamicProfileResultBO]=None): Initializer. Args: static_result (StaticProfileResultBO):... | Implement the Python class `ProfileResultBO` described below.
Class description:
Profiling result business object.
Method signatures and docstrings:
- def __init__(self, static_result: StaticProfileResultBO, dynamic_results: List[DynamicProfileResultBO]=None): Initializer. Args: static_result (StaticProfileResultBO):... | f77635e469477b640a5c2d9b7ad3fe13374ce59e | <|skeleton|>
class ProfileResultBO:
"""Profiling result business object."""
def __init__(self, static_result: StaticProfileResultBO, dynamic_results: List[DynamicProfileResultBO]=None):
"""Initializer. Args: static_result (StaticProfileResultBO): static profiling result business object. dynamic_results... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileResultBO:
"""Profiling result business object."""
def __init__(self, static_result: StaticProfileResultBO, dynamic_results: List[DynamicProfileResultBO]=None):
"""Initializer. Args: static_result (StaticProfileResultBO): static profiling result business object. dynamic_results (Optional[It... | the_stack_v2_python_sparse | modelci/types/bo/profile_result_bo.py | crazyCoderLi/ML-Model-CI | train | 2 |
f8bfeadbb0c34abc9530df57e608702dc8c85eec | [
"a = []\nb = []\nt = []\nfor i in A:\n if i % 2 == 0:\n a.append(i)\n else:\n b.append(i)\nfor x in range(len(A) // 2):\n t.append(a[x])\n t.append(b[x])\nreturn t",
"n = len(A)\nresult = [0] * n\neven, odd = (0, 1)\nfor i in A:\n if i % 2 == 0:\n result[even] = i\n even... | <|body_start_0|>
a = []
b = []
t = []
for i in A:
if i % 2 == 0:
a.append(i)
else:
b.append(i)
for x in range(len(A) // 2):
t.append(a[x])
t.append(b[x])
return t
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortArrayByParityII_1(self, A):
""":type A: List[int] :rtype: List[int]"""
<|body_0|>
def sortArrayByParityII_2(self, A):
""":type A: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = []
b = []
... | stack_v2_sparse_classes_75kplus_train_070143 | 857 | no_license | [
{
"docstring": ":type A: List[int] :rtype: List[int]",
"name": "sortArrayByParityII_1",
"signature": "def sortArrayByParityII_1(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: List[int]",
"name": "sortArrayByParityII_2",
"signature": "def sortArrayByParityII_2(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006613 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArrayByParityII_1(self, A): :type A: List[int] :rtype: List[int]
- def sortArrayByParityII_2(self, A): :type A: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArrayByParityII_1(self, A): :type A: List[int] :rtype: List[int]
- def sortArrayByParityII_2(self, A): :type A: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | ec641c43ee481220b3ccdac2d1b6d0826fe379a5 | <|skeleton|>
class Solution:
def sortArrayByParityII_1(self, A):
""":type A: List[int] :rtype: List[int]"""
<|body_0|>
def sortArrayByParityII_2(self, A):
""":type A: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortArrayByParityII_1(self, A):
""":type A: List[int] :rtype: List[int]"""
a = []
b = []
t = []
for i in A:
if i % 2 == 0:
a.append(i)
else:
b.append(i)
for x in range(len(A) // 2):
... | the_stack_v2_python_sparse | Leetcode/leetcode922.py | lxh1997zj/-offer_and_LeetCode | train | 0 | |
8b55c42c02210a17b39e1d2f9aed73fa5cf2b879 | [
"super().__init__()\nself.lin_enc = torch.nn.Linear(encoder_output_size, joint_space_size)\nself.lin_dec = torch.nn.Linear(decoder_output_size, joint_space_size, bias=False)\nself.lin_out = torch.nn.Linear(joint_space_size, joint_output_size)\nself.joint_activation = get_activation(joint_activation_type)",
"if is... | <|body_start_0|>
super().__init__()
self.lin_enc = torch.nn.Linear(encoder_output_size, joint_space_size)
self.lin_dec = torch.nn.Linear(decoder_output_size, joint_space_size, bias=False)
self.lin_out = torch.nn.Linear(joint_space_size, joint_output_size)
self.joint_activation = ... | Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activation_type: Type of activation for joint network. | JointNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointNetwork:
"""Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activation_type: Type of activation for joint n... | stack_v2_sparse_classes_75kplus_train_070144 | 2,306 | permissive | [
{
"docstring": "Joint network initializer.",
"name": "__init__",
"signature": "def __init__(self, joint_output_size: int, encoder_output_size: int, decoder_output_size: int, joint_space_size: int, joint_activation_type: int)"
},
{
"docstring": "Joint computation of encoder and decoder hidden sta... | 2 | null | Implement the Python class `JointNetwork` described below.
Class description:
Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activati... | Implement the Python class `JointNetwork` described below.
Class description:
Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activati... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class JointNetwork:
"""Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activation_type: Type of activation for joint n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JointNetwork:
"""Transducer joint network module. Args: joint_output_size: Joint network output dimension encoder_output_size: Encoder output dimension. decoder_output_size: Decoder output dimension. joint_space_size: Dimension of joint space. joint_activation_type: Type of activation for joint network."""
... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/joint_network.py | espnet/espnet | train | 7,242 |
e7bb4850babd0acaa756e0b8a43a7b3113cc027a | [
"lat = params['lat']\nlong = params['long']\ndist = random.random() * 0.002\nangle = random.random() * math.pi * 2\nlat += dist * math.sin(angle)\nlong += dist * math.cos(angle)\ndata = {'lat': lat, 'long': long}\ncode = 200\nreturn (code, data)",
"city_name = params['name']\nnew_coords = self.CITY_COORDS.get(cit... | <|body_start_0|>
lat = params['lat']
long = params['long']
dist = random.random() * 0.002
angle = random.random() * math.pi * 2
lat += dist * math.sin(angle)
long += dist * math.cos(angle)
data = {'lat': lat, 'long': long}
code = 200
return (code, ... | GpsWalkerComponent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GpsWalkerComponent:
def walk(self, request, input, params, method):
"""Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP request. @type request: BaseHttpRequest @param input: Any data that came in the body of the request. @type input:... | stack_v2_sparse_classes_75kplus_train_070145 | 3,550 | no_license | [
{
"docstring": "Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP request. @type request: BaseHttpRequest @param input: Any data that came in the body of the request. @type input: string @param params: Dictionary of parameter values. @type params: dict @para... | 2 | stack_v2_sparse_classes_30k_train_003800 | Implement the Python class `GpsWalkerComponent` described below.
Class description:
Implement the GpsWalkerComponent class.
Method signatures and docstrings:
- def walk(self, request, input, params, method): Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP reques... | Implement the Python class `GpsWalkerComponent` described below.
Class description:
Implement the GpsWalkerComponent class.
Method signatures and docstrings:
- def walk(self, request, input, params, method): Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP reques... | e97f6a5a07bad39403ebb0b435f8e055298839d3 | <|skeleton|>
class GpsWalkerComponent:
def walk(self, request, input, params, method):
"""Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP request. @type request: BaseHttpRequest @param input: Any data that came in the body of the request. @type input:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GpsWalkerComponent:
def walk(self, request, input, params, method):
"""Performs a random modification of passed in GPS coordinates. @param request: Information about the HTTP request. @type request: BaseHttpRequest @param input: Any data that came in the body of the request. @type input: string @param... | the_stack_v2_python_sparse | src/python/glu/components/gpswalker_component.py | rossmason/glu | train | 0 | |
2c5b120378b854c59e6aa7f15a525296597de0e4 | [
"content = '\\n\\n {% load static %}\\n Hi {{ taster_first_name }},\\n\\n {% if placed_order %}\\n Thank you so much for attending my Vinely Taste Party and ordering some wine! I hope you had a great time and you and your personality are getting along great. Don\\'t forget to rate your w... | <|body_start_0|>
content = '\n\n {% load static %}\n Hi {{ taster_first_name }},\n\n {% if placed_order %}\n Thank you so much for attending my Vinely Taste Party and ordering some wine! I hope you had a great time and you and your personality are getting along great. Don\'t forget t... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
content = '\n\n {% load static %}\n ... | stack_v2_sparse_classes_75kplus_train_070146 | 4,891 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017049 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
content = '\n\n {% load static %}\n Hi {{ taster_first_name }},\n\n {% if placed_order %}\n Thank you so much for attending my Vinely Taste Party and ordering some wine! I hope you had a gre... | the_stack_v2_python_sparse | cms/migrations/0008_add_thanks_message_section.py | RSV3/nuvine | train | 0 | |
e48ade358a74fff1e1ef01fc594dc9ce53d01508 | [
"s_size = len(s)\nt_size = len(t)\nj = 0\nfor i in range(s_size):\n while j < t_size:\n if s[i] == t[j]:\n j += 1\n break\n j += 1\n if j == t_size and i != s_size - 1:\n return False\n if j == t_size and t[j - 1] != s[s_size - 1]:\n return False\nreturn Tr... | <|body_start_0|>
s_size = len(s)
t_size = len(t)
j = 0
for i in range(s_size):
while j < t_size:
if s[i] == t[j]:
j += 1
break
j += 1
if j == t_size and i != s_size - 1:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :param t: :return:"""
<|body_0|>
def isSubsequence1(self, s: str, t: str) -> bool:
... | stack_v2_sparse_classes_75kplus_train_070147 | 4,475 | no_license | [
{
"docstring": "思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :param t: :return:",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s: str, t: str) -> bool"
},
{
"docstring": "官方实现的贪心策略的双指针,太简洁了。学习下。自己太菜,... | 3 | stack_v2_sparse_classes_30k_train_006648 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :para... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :para... | 46cfe84921a9a3e865edd1f94e7807b320b53778 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :param t: :return:"""
<|body_0|>
def isSubsequence1(self, s: str, t: str) -> bool:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""思路:使用双指针方法,但贪心算法如何体现呢? 遍历子序列,当找到第一个与s[i]相等的字符,则从t[j]的位置继续找s[i+1]字符 当子序列遍历完,则返回True;若序列t先结束,则说明未找到子序列中的字符,返回 False :param s: :param t: :return:"""
s_size = len(s)
t_size = len(t)
j = 0
for i in range(s_size):
... | the_stack_v2_python_sparse | 2020-09/Q392-is-subsequence.py | EAGLE50/LearnLeetCode | train | 0 | |
d797832e2e2bc4c45fd63d8012af6b915201ef6f | [
"args, token = (self.params.get, kwargs.get('token'))\ninstances = Instance.select()\nif args['state']:\n instances = instances.where(Instance.state == INSTANCE_STATES[args['state']])\nif not args['all']:\n instances = instances.where(Instance.token == kwargs.get('token'))\nm_instances = []\nfor instance in i... | <|body_start_0|>
args, token = (self.params.get, kwargs.get('token'))
instances = Instance.select()
if args['state']:
instances = instances.where(Instance.state == INSTANCE_STATES[args['state']])
if not args['all']:
instances = instances.where(Instance.token == kw... | InstanceResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceResource:
def get(self, *args, **kwargs):
"""List all instances"""
<|body_0|>
def delete(self, *args, **kwargs):
"""Receives a request for destroy a running/requested instance"""
<|body_1|>
def post(self, *args, **kwargs):
"""Receives a r... | stack_v2_sparse_classes_75kplus_train_070148 | 4,526 | no_license | [
{
"docstring": "List all instances",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Receives a request for destroy a running/requested instance",
"name": "delete",
"signature": "def delete(self, *args, **kwargs)"
},
{
"docstring": "Receives a requ... | 3 | stack_v2_sparse_classes_30k_test_000343 | Implement the Python class `InstanceResource` described below.
Class description:
Implement the InstanceResource class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): List all instances
- def delete(self, *args, **kwargs): Receives a request for destroy a running/requested instance
- def post(sel... | Implement the Python class `InstanceResource` described below.
Class description:
Implement the InstanceResource class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): List all instances
- def delete(self, *args, **kwargs): Receives a request for destroy a running/requested instance
- def post(sel... | 13831ff5a3dce4132fb59444ecb3caf49a6dde2c | <|skeleton|>
class InstanceResource:
def get(self, *args, **kwargs):
"""List all instances"""
<|body_0|>
def delete(self, *args, **kwargs):
"""Receives a request for destroy a running/requested instance"""
<|body_1|>
def post(self, *args, **kwargs):
"""Receives a r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceResource:
def get(self, *args, **kwargs):
"""List all instances"""
args, token = (self.params.get, kwargs.get('token'))
instances = Instance.select()
if args['state']:
instances = instances.where(Instance.state == INSTANCE_STATES[args['state']])
if n... | the_stack_v2_python_sparse | tracker/tormenta/tracker/api.py | niedbalski/tormenta | train | 0 | |
056944e23ef4a406a65a8d028260ad145efa2ddf | [
"d = {}\nfor t in tasks:\n if t in d:\n d[t] += 1\n else:\n d[t] = 1\npq = queue.PriorityQueue()\nfor k, v in d.items():\n pq.put(-v)\nans = 0\nwhile not pq.empty():\n time = 0\n tmp = []\n while time <= n and (not pq.empty()):\n v = pq.get()\n if -v > 1:\n t... | <|body_start_0|>
d = {}
for t in tasks:
if t in d:
d[t] += 1
else:
d[t] = 1
pq = queue.PriorityQueue()
for k, v in d.items():
pq.put(-v)
ans = 0
while not pq.empty():
time = 0
tmp ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
def leastInterval3(self, tasks, n):
... | stack_v2_sparse_classes_75kplus_train_070149 | 2,596 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval2",
"signature": "def leastInterval2(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval1",
"signature": "def leastInterval1(self, tasks, n)"
... | 4 | stack_v2_sparse_classes_30k_train_044399 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def le... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def le... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
def leastInterval3(self, tasks, n):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
d = {}
for t in tasks:
if t in d:
d[t] += 1
else:
d[t] = 1
pq = queue.PriorityQueue()
for k, v in d.items():
... | the_stack_v2_python_sparse | 621_task_scheduler/621.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
05b21735d94cf49184f15bd55f397d43ac34f7d5 | [
"import uuid\nres = ResponseDTO()\ntry:\n project = db.session.query(BoardDTO).filter(BoardDTO.UID == uid).first()\n if project:\n res.success = True\n res.code = 200\n res.msg = 'Success'\n res.data = project.as_dict()\n else:\n res.success = False\n res.code = 20... | <|body_start_0|>
import uuid
res = ResponseDTO()
try:
project = db.session.query(BoardDTO).filter(BoardDTO.UID == uid).first()
if project:
res.success = True
res.code = 200
res.msg = 'Success'
res.data = proj... | Project | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Project:
def get(self, uid: str):
"""get a project given its identifier"""
<|body_0|>
def put(self, uid: str):
"""update a project given its identifier"""
<|body_1|>
def delete(self, uid: str):
"""delete a project given its identifier"""
... | stack_v2_sparse_classes_75kplus_train_070150 | 5,404 | no_license | [
{
"docstring": "get a project given its identifier",
"name": "get",
"signature": "def get(self, uid: str)"
},
{
"docstring": "update a project given its identifier",
"name": "put",
"signature": "def put(self, uid: str)"
},
{
"docstring": "delete a project given its identifier",
... | 3 | stack_v2_sparse_classes_30k_train_040812 | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def get(self, uid: str): get a project given its identifier
- def put(self, uid: str): update a project given its identifier
- def delete(self, uid: str): delete a project given it... | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def get(self, uid: str): get a project given its identifier
- def put(self, uid: str): update a project given its identifier
- def delete(self, uid: str): delete a project given it... | 920d4021736fce2467e33424ccd6c0c718e19c26 | <|skeleton|>
class Project:
def get(self, uid: str):
"""get a project given its identifier"""
<|body_0|>
def put(self, uid: str):
"""update a project given its identifier"""
<|body_1|>
def delete(self, uid: str):
"""delete a project given its identifier"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Project:
def get(self, uid: str):
"""get a project given its identifier"""
import uuid
res = ResponseDTO()
try:
project = db.session.query(BoardDTO).filter(BoardDTO.UID == uid).first()
if project:
res.success = True
res.co... | the_stack_v2_python_sparse | rest-api/app/api/controllers/ProjectController.py | humkyung/TS | train | 0 | |
c28e1d49663ee6c9d12cc60d0cf18206af489f8f | [
"try:\n task_type = TaskType.objects.get(pk=pk)\n serializer = TaskTypeSerializer(task_type, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"task_types = TaskType.objects.all()\nserializer = TaskTypeSerializer(task_types... | <|body_start_0|>
try:
task_type = TaskType.objects.get(pk=pk)
serializer = TaskTypeSerializer(task_type, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_... | Task Types for codeProject | TaskTypes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskTypes:
"""Task Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for task type Returns: Response -- JSON serialized task type instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to task types resource Ret... | stack_v2_sparse_classes_75kplus_train_070151 | 1,609 | no_license | [
{
"docstring": "Handle GET requests for task type Returns: Response -- JSON serialized task type instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to task types resource Returns: Response -- JSON serialized list of task type... | 2 | stack_v2_sparse_classes_30k_train_009337 | Implement the Python class `TaskTypes` described below.
Class description:
Task Types for codeProject
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for task type Returns: Response -- JSON serialized task type instance
- def list(self, request): Handle GET requests to ta... | Implement the Python class `TaskTypes` described below.
Class description:
Task Types for codeProject
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for task type Returns: Response -- JSON serialized task type instance
- def list(self, request): Handle GET requests to ta... | edcb6749de745b57404b7fbaf31db33f8c9e0351 | <|skeleton|>
class TaskTypes:
"""Task Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for task type Returns: Response -- JSON serialized task type instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to task types resource Ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskTypes:
"""Task Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for task type Returns: Response -- JSON serialized task type instance"""
try:
task_type = TaskType.objects.get(pk=pk)
serializer = TaskTypeSerializer(task_type,... | the_stack_v2_python_sparse | codeprojectAPIapp/views/task_types.py | shanemiller89/codeProject-API | train | 1 |
c8dfbac7f6527009410d843824d92f8edbe3f389 | [
"self.name = name\nself.description = description\nself.asset_used = asset_used\nself.entry_points_filepath = entry_points_filepath",
"known_entry_points = EntryPoint.fetch_known_entry_points(self.entry_points_filepath)\nknown_entry_points[self.name] = self.description\ntry:\n with open(self.entry_points_filep... | <|body_start_0|>
self.name = name
self.description = description
self.asset_used = asset_used
self.entry_points_filepath = entry_points_filepath
<|end_body_0|>
<|body_start_1|>
known_entry_points = EntryPoint.fetch_known_entry_points(self.entry_points_filepath)
known_ent... | Represents single system interaction and possible exploitation place | EntryPoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryPoint:
"""Represents single system interaction and possible exploitation place"""
def __init__(self, name, description, asset_used, entry_points_filepath):
"""Init"""
<|body_0|>
def update_known_entry_points(self):
"""writes current entry_point value to mode... | stack_v2_sparse_classes_75kplus_train_070152 | 2,860 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self, name, description, asset_used, entry_points_filepath)"
},
{
"docstring": "writes current entry_point value to model-entry_points.yml file Raises: ModellingException",
"name": "update_known_entry_points",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_022449 | Implement the Python class `EntryPoint` described below.
Class description:
Represents single system interaction and possible exploitation place
Method signatures and docstrings:
- def __init__(self, name, description, asset_used, entry_points_filepath): Init
- def update_known_entry_points(self): writes current entr... | Implement the Python class `EntryPoint` described below.
Class description:
Represents single system interaction and possible exploitation place
Method signatures and docstrings:
- def __init__(self, name, description, asset_used, entry_points_filepath): Init
- def update_known_entry_points(self): writes current entr... | be32512d6d098a123599b2ac8f032bd003c28f63 | <|skeleton|>
class EntryPoint:
"""Represents single system interaction and possible exploitation place"""
def __init__(self, name, description, asset_used, entry_points_filepath):
"""Init"""
<|body_0|>
def update_known_entry_points(self):
"""writes current entry_point value to mode... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntryPoint:
"""Represents single system interaction and possible exploitation place"""
def __init__(self, name, description, asset_used, entry_points_filepath):
"""Init"""
self.name = name
self.description = description
self.asset_used = asset_used
self.entry_point... | the_stack_v2_python_sparse | iotpentool/entrypoint.py | sarunasil/iotPenTool | train | 0 |
285d24516f3d789727f8bb140f8e98d59935a053 | [
"self.event_id = ''\nself.timestamp = 0\nself.hostname = ''\nself.pid = 0\nself.event_type = ''\nself.authentication_method = ''\nself.authentication_result = ''\nself.source_ip = ''\nself.source_port = ''\nself.username = ''\nself.session_id = ''",
"session_id_data = f'{self.hostname}|{self.username}|{self.sourc... | <|body_start_0|>
self.event_id = ''
self.timestamp = 0
self.hostname = ''
self.pid = 0
self.event_type = ''
self.authentication_method = ''
self.authentication_result = ''
self.source_ip = ''
self.source_port = ''
self.username = ''
... | Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Process ID of the SSHD process. event_type (str): Type of authentication event. Valid... | SSHEventData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHEventData:
"""Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Process ID of the SSHD process. event_type (s... | stack_v2_sparse_classes_75kplus_train_070153 | 11,721 | permissive | [
{
"docstring": "Initialize class.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Calculates pseudo session ID for SSH authentication event.",
"name": "calculate_session_id",
"signature": "def calculate_session_id(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_032089 | Implement the Python class `SSHEventData` described below.
Class description:
Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Proces... | Implement the Python class `SSHEventData` described below.
Class description:
Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Proces... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SSHEventData:
"""Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Process ID of the SSHD process. event_type (s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSHEventData:
"""Class for storing SSH authentication data. Attributes: event_id (str): OpenSearch event ID of an authentication event. timestamp (int): Authentication event timestamp in Unix seconds. hostname (str): Hostname of the system. pid (int): Process ID of the SSHD process. event_type (str): Type of ... | the_stack_v2_python_sparse | timesketch/lib/analyzers/authentication/ssh.py | google/timesketch | train | 2,263 |
52a1c259eb56f307cf7004c9a7b9f18822e6f07c | [
"profile_words = dict()\nprofile_words['uid'] = user_profiles['uid']\nprofile_words['profile'] = dict()\nfor item in user_profiles['profile'].items():\n profile = item[1]\n word_list = jieba.analyse.extract_tags(profile, 3, allowPOS=('n', 'nv'))\n profile_words['profile'][item[0]] = word_list\nreturn profi... | <|body_start_0|>
profile_words = dict()
profile_words['uid'] = user_profiles['uid']
profile_words['profile'] = dict()
for item in user_profiles['profile'].items():
profile = item[1]
word_list = jieba.analyse.extract_tags(profile, 3, allowPOS=('n', 'nv'))
... | ProfileIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileIndex:
def addWordDict(self, user_profiles):
"""将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}"""
<|body_0|>
def addIndexDict(self, profile_words):
"""整合单个用户所有的博文-关键词关系 :param profile_... | stack_v2_sparse_classes_75kplus_train_070154 | 2,253 | no_license | [
{
"docstring": "将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}",
"name": "addWordDict",
"signature": "def addWordDict(self, user_profiles)"
},
{
"docstring": "整合单个用户所有的博文-关键词关系 :param profile_words: dict,表示用户-博文关键词列表对应关系... | 3 | null | Implement the Python class `ProfileIndex` described below.
Class description:
Implement the ProfileIndex class.
Method signatures and docstrings:
- def addWordDict(self, user_profiles): 将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}
- def add... | Implement the Python class `ProfileIndex` described below.
Class description:
Implement the ProfileIndex class.
Method signatures and docstrings:
- def addWordDict(self, user_profiles): 将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}
- def add... | 589dc3ff114fb76bb1fc7544e890058ae364227f | <|skeleton|>
class ProfileIndex:
def addWordDict(self, user_profiles):
"""将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}"""
<|body_0|>
def addIndexDict(self, profile_words):
"""整合单个用户所有的博文-关键词关系 :param profile_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileIndex:
def addWordDict(self, user_profiles):
"""将单个用户的博文进行分词,建立用户-博文-关键词列表对应关系数据 :param user_profiles: dict,表示用户-博文对应关系数据 :return: dict,数据格式:{'uid':'','profile':{cid:[]}}"""
profile_words = dict()
profile_words['uid'] = user_profiles['uid']
profile_words['profile'] = dic... | the_stack_v2_python_sparse | index/profileModule.py | Jgirl033/Vemax | train | 0 | |
7825f57cafea9d52f6ef0ab1b16afd57b7d8cc74 | [
"intervals = sorted(intervals + [newInterval], key=lambda x: x[0])\nres = []\nfor interval in intervals:\n if not res or interval[0] > res[-1][1]:\n res.append(interval)\n else:\n res[-1][1] = max(interval[1], res[-1][1])\nreturn res",
"i, n = (0, len(intervals))\nres = []\nwhile i < n and new... | <|body_start_0|>
intervals = sorted(intervals + [newInterval], key=lambda x: x[0])
res = []
for interval in intervals:
if not res or interval[0] > res[-1][1]:
res.append(interval)
else:
res[-1][1] = max(interval[1], res[-1][1])
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""将新区间添加到列表中,排序后再合并"""
<|body_0|>
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""# TODO"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_070155 | 2,230 | no_license | [
{
"docstring": "将新区间添加到列表中,排序后再合并",
"name": "insert2",
"signature": "def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]"
},
{
"docstring": "# TODO",
"name": "insert",
"signature": "def insert(self, intervals: List[List[int]], newInterval: List[int]) ... | 2 | stack_v2_sparse_classes_30k_train_018554 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 将新区间添加到列表中,排序后再合并
- def insert(self, intervals: List[List[int]], newInterval: List[int])... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 将新区间添加到列表中,排序后再合并
- def insert(self, intervals: List[List[int]], newInterval: List[int])... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""将新区间添加到列表中,排序后再合并"""
<|body_0|>
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""# TODO"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def insert2(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""将新区间添加到列表中,排序后再合并"""
intervals = sorted(intervals + [newInterval], key=lambda x: x[0])
res = []
for interval in intervals:
if not res or interval[0] > res[-1][1]:
... | the_stack_v2_python_sparse | .leetcode/57.插入区间.py | xiaoruijiang/algorithm | train | 0 | |
9eec7244706c1f78581d89a297db81d751d5d05a | [
"passwd = data['password']\npasswd_confirmation = data['password_confirmation']\nif passwd != passwd_confirmation:\n raise serializers.ValidationError('Las contraseñas no coinciden')\npassword_validation.validate_password(passwd)\nreturn data",
"validated_data.pop('password_confirmation')\nuser = User.objects.... | <|body_start_0|>
passwd = data['password']
passwd_confirmation = data['password_confirmation']
if passwd != passwd_confirmation:
raise serializers.ValidationError('Las contraseñas no coinciden')
password_validation.validate_password(passwd)
return data
<|end_body_0|>
... | Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado | UserSingupSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSingupSerializer:
"""Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado"""
def validate(self, data):
"""Validacion de campos ingresados"""
<|body_0|>
def create(self... | stack_v2_sparse_classes_75kplus_train_070156 | 3,801 | permissive | [
{
"docstring": "Validacion de campos ingresados",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Crea el usuario luego de validar los datos ingresados Y le asigna un rol solo si es pasado como dato",
"name": "create",
"signature": "def create(self, validat... | 2 | stack_v2_sparse_classes_30k_train_035527 | Implement the Python class `UserSingupSerializer` described below.
Class description:
Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado
Method signatures and docstrings:
- def validate(self, data): Validacion de cam... | Implement the Python class `UserSingupSerializer` described below.
Class description:
Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado
Method signatures and docstrings:
- def validate(self, data): Validacion de cam... | d7e5b0fae620764b3af73955f7771dcee5746dfc | <|skeleton|>
class UserSingupSerializer:
"""Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado"""
def validate(self, data):
"""Validacion de campos ingresados"""
<|body_0|>
def create(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSingupSerializer:
"""Serialiazer del registro de usuario Cuenta con validaciones de datos y creacion del usuario instanciando su rol de acuerdo al tipo de usuario registrado"""
def validate(self, data):
"""Validacion de campos ingresados"""
passwd = data['password']
passwd_con... | the_stack_v2_python_sparse | backend/apis/users/serializers/users.py | sango09/senasoft | train | 1 |
55fe386e3c7c7e20ac8a2535570acba93789768f | [
"possible_solicitudes = self.get_servicios_queryset(request).filter(pk=pk)\nsoli = possible_solicitudes[0] if len(possible_solicitudes) == 1 else None\nif soli is not None:\n context = {'form': SolicitudForm(instance=soli), 'id': soli.pk}\n return render(request, 'servicios/edit_solicitud.html', context)\nels... | <|body_start_0|>
possible_solicitudes = self.get_servicios_queryset(request).filter(pk=pk)
soli = possible_solicitudes[0] if len(possible_solicitudes) == 1 else None
if soli is not None:
context = {'form': SolicitudForm(instance=soli), 'id': soli.pk}
return render(request... | EditSolicitudView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditSolicitudView:
def get(self, request, pk):
"""Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse"""
<|body_0|>
def post(self, request, pk):
"""esto cmuestra un formulario para editar una Solicitud :param request: :return:... | stack_v2_sparse_classes_75kplus_train_070157 | 12,273 | no_license | [
{
"docstring": "Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "esto cmuestra un formulario para editar una Solicitud :param request: :return:",
"name": "post",
"sig... | 2 | stack_v2_sparse_classes_30k_train_041744 | Implement the Python class `EditSolicitudView` described below.
Class description:
Implement the EditSolicitudView class.
Method signatures and docstrings:
- def get(self, request, pk): Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse
- def post(self, request, pk): esto cmu... | Implement the Python class `EditSolicitudView` described below.
Class description:
Implement the EditSolicitudView class.
Method signatures and docstrings:
- def get(self, request, pk): Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse
- def post(self, request, pk): esto cmu... | 47e219a91e39fe35fe1573cb09dbe6cc7ff8964d | <|skeleton|>
class EditSolicitudView:
def get(self, request, pk):
"""Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse"""
<|body_0|>
def post(self, request, pk):
"""esto cmuestra un formulario para editar una Solicitud :param request: :return:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditSolicitudView:
def get(self, request, pk):
"""Carga la página de detalle de una Solicitud :param request: :param pk: :return: HttpResponse"""
possible_solicitudes = self.get_servicios_queryset(request).filter(pk=pk)
soli = possible_solicitudes[0] if len(possible_solicitudes) == 1 e... | the_stack_v2_python_sparse | servicios/views.py | franckiito/ServiceAir | train | 0 | |
cda54b88ff4ff614f42d4743efbe4a71a67b417f | [
"modules = ['lib.wrapper.integration_mw.interfaces.common', 'lib.wrapper.integration_mw.interfaces.instruction', 'lib.wrapper.integration_mw.interfaces.memory_options', 'lib.wrapper.integration_mw.interfaces.network', 'lib.wrapper.integration_mw.interfaces.plc_option', 'lib.wrapper.integration_mw.interfaces.pou', '... | <|body_start_0|>
modules = ['lib.wrapper.integration_mw.interfaces.common', 'lib.wrapper.integration_mw.interfaces.instruction', 'lib.wrapper.integration_mw.interfaces.memory_options', 'lib.wrapper.integration_mw.interfaces.network', 'lib.wrapper.integration_mw.interfaces.plc_option', 'lib.wrapper.integration_m... | Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20 | IntegrationMW | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegrationMW:
"""Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20"""
def get_public_interface(self):
"""Create a socket object. Args: ip type(str) ip address port type(str) port nu... | stack_v2_sparse_classes_75kplus_train_070158 | 2,114 | no_license | [
{
"docstring": "Create a socket object. Args: ip type(str) ip address port type(str) port number Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-26",
"name": "get_public_interface",
"signature": "def get_public_interface(self)"
},
{
"docstring": "Create a sock... | 2 | stack_v2_sparse_classes_30k_train_045916 | Implement the Python class `IntegrationMW` described below.
Class description:
Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20
Method signatures and docstrings:
- def get_public_interface(self): Create a socket obj... | Implement the Python class `IntegrationMW` described below.
Class description:
Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20
Method signatures and docstrings:
- def get_public_interface(self): Create a socket obj... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class IntegrationMW:
"""Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20"""
def get_public_interface(self):
"""Create a socket object. Args: ip type(str) ip address port type(str) port nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntegrationMW:
"""Integration test interfaces collection class of Micro WIN. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-08-20"""
def get_public_interface(self):
"""Create a socket object. Args: ip type(str) ip address port type(str) port number Example:... | the_stack_v2_python_sparse | lib/wrapper/integration_mw/integration_mw.py | Lewescaiyong/auto_test_framework | train | 1 |
583070e31135f2bc7269061557d3210c0b5b8710 | [
"from_date = '%s/%s/%s' % (TODAY.year, TODAY.month, TODAY.day)\nif 'site_id' not in options:\n self.out.write('%s\\n' % ERROR_METEAR[KEY_METEAR_NO_SITE_ID])\n self.logger.error(ERROR_METEAR[KEY_METEAR_NO_SITE_ID])\n return\nif 'from_date' in options:\n from_date = options['from_date'].strftime('%Y/%m/%d... | <|body_start_0|>
from_date = '%s/%s/%s' % (TODAY.year, TODAY.month, TODAY.day)
if 'site_id' not in options:
self.out.write('%s\n' % ERROR_METEAR[KEY_METEAR_NO_SITE_ID])
self.logger.error(ERROR_METEAR[KEY_METEAR_NO_SITE_ID])
return
if 'from_date' in options:
... | Command class | MyMETEARCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyMETEARCrawler:
"""Command class"""
def url_generator(self, *args, **options):
"""Generate METEAR url according to site_id and date"""
<|body_0|>
def clean_data(self):
"""Clean data receive form METEAR API, remove <br/> and"""
<|body_1|>
def remove_... | stack_v2_sparse_classes_75kplus_train_070159 | 6,260 | permissive | [
{
"docstring": "Generate METEAR url according to site_id and date",
"name": "url_generator",
"signature": "def url_generator(self, *args, **options)"
},
{
"docstring": "Clean data receive form METEAR API, remove <br/> and",
"name": "clean_data",
"signature": "def clean_data(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_027076 | Implement the Python class `MyMETEARCrawler` described below.
Class description:
Command class
Method signatures and docstrings:
- def url_generator(self, *args, **options): Generate METEAR url according to site_id and date
- def clean_data(self): Clean data receive form METEAR API, remove <br/> and
- def remove_html... | Implement the Python class `MyMETEARCrawler` described below.
Class description:
Command class
Method signatures and docstrings:
- def url_generator(self, *args, **options): Generate METEAR url according to site_id and date
- def clean_data(self): Clean data receive form METEAR API, remove <br/> and
- def remove_html... | 3b4323c7bc4672009f94f06ad66d447ef38fac01 | <|skeleton|>
class MyMETEARCrawler:
"""Command class"""
def url_generator(self, *args, **options):
"""Generate METEAR url according to site_id and date"""
<|body_0|>
def clean_data(self):
"""Clean data receive form METEAR API, remove <br/> and"""
<|body_1|>
def remove_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyMETEARCrawler:
"""Command class"""
def url_generator(self, *args, **options):
"""Generate METEAR url according to site_id and date"""
from_date = '%s/%s/%s' % (TODAY.year, TODAY.month, TODAY.day)
if 'site_id' not in options:
self.out.write('%s\n' % ERROR_METEAR[KEY_M... | the_stack_v2_python_sparse | weather/management/commands/retrieve_metear_data.py | timevortexproject/timevortex | train | 0 |
cec87d6f2772a3d185926f847cd20a8e0664ed83 | [
"filepath = os.path.join(downdir, filename)\nlogger.debug(filepath)\nif os.path.exists(filepath):\n result = financial.FinancialReader().to_data(filepath)\n return result\nlogger.error('文件不存在:{}'.format(filename))\nreturn None",
"history = financial.FinancialList()\nresults = history.fetch_and_parse()\nretu... | <|body_start_0|>
filepath = os.path.join(downdir, filename)
logger.debug(filepath)
if os.path.exists(filepath):
result = financial.FinancialReader().to_data(filepath)
return result
logger.error('文件不存在:{}'.format(filename))
return None
<|end_body_0|>
<|bod... | Affair | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Affair:
def parse(downdir='.', filename=None, *args, **kwargs):
"""按目录解析文件 :param downdir: :param filename: :param kwargs: :return:"""
<|body_0|>
def files():
"""财务文件列表 :return:"""
<|body_1|>
def fetch(downdir='.', filename=None, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_070160 | 2,643 | permissive | [
{
"docstring": "按目录解析文件 :param downdir: :param filename: :param kwargs: :return:",
"name": "parse",
"signature": "def parse(downdir='.', filename=None, *args, **kwargs)"
},
{
"docstring": "财务文件列表 :return:",
"name": "files",
"signature": "def files()"
},
{
"docstring": "财务数据下载 :pa... | 3 | stack_v2_sparse_classes_30k_train_013418 | Implement the Python class `Affair` described below.
Class description:
Implement the Affair class.
Method signatures and docstrings:
- def parse(downdir='.', filename=None, *args, **kwargs): 按目录解析文件 :param downdir: :param filename: :param kwargs: :return:
- def files(): 财务文件列表 :return:
- def fetch(downdir='.', filen... | Implement the Python class `Affair` described below.
Class description:
Implement the Affair class.
Method signatures and docstrings:
- def parse(downdir='.', filename=None, *args, **kwargs): 按目录解析文件 :param downdir: :param filename: :param kwargs: :return:
- def files(): 财务文件列表 :return:
- def fetch(downdir='.', filen... | dd3065f3189eacc0ba6efbd17f60e9848bbffcd4 | <|skeleton|>
class Affair:
def parse(downdir='.', filename=None, *args, **kwargs):
"""按目录解析文件 :param downdir: :param filename: :param kwargs: :return:"""
<|body_0|>
def files():
"""财务文件列表 :return:"""
<|body_1|>
def fetch(downdir='.', filename=None, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Affair:
def parse(downdir='.', filename=None, *args, **kwargs):
"""按目录解析文件 :param downdir: :param filename: :param kwargs: :return:"""
filepath = os.path.join(downdir, filename)
logger.debug(filepath)
if os.path.exists(filepath):
result = financial.FinancialReader()... | the_stack_v2_python_sparse | mootdx/affair.py | sxlxnyw/mootdx | train | 2 | |
d6ca7e292930a3ad8434e72dde9cf6ef289e2ffd | [
"self.input_stream = input_stream\nself.output_stream = output_stream\nself.summary = summary\nself.log_parser = log_parser\nself.renderer = renderer",
"log_text = self.input_stream.read()\nparser = self.log_parser(log_text)\nparser.log_lines(self.summary)\nrendered_summary = self.renderer.render(self.summary)\ns... | <|body_start_0|>
self.input_stream = input_stream
self.output_stream = output_stream
self.summary = summary
self.log_parser = log_parser
self.renderer = renderer
<|end_body_0|>
<|body_start_1|>
log_text = self.input_stream.read()
parser = self.log_parser(log_text... | Summarizes meetup2xibo logs, reporting meeting changes. | LogSummarizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogSummarizer:
"""Summarizes meetup2xibo logs, reporting meeting changes."""
def __init__(self, input_stream, output_stream, summary, log_parser, renderer):
"""Initialize with input and output streams, an empty summary, a log parser, and a renderer."""
<|body_0|>
def run... | stack_v2_sparse_classes_75kplus_train_070161 | 919 | permissive | [
{
"docstring": "Initialize with input and output streams, an empty summary, a log parser, and a renderer.",
"name": "__init__",
"signature": "def __init__(self, input_stream, output_stream, summary, log_parser, renderer)"
},
{
"docstring": "Summarize the logs.",
"name": "run",
"signature... | 2 | null | Implement the Python class `LogSummarizer` described below.
Class description:
Summarizes meetup2xibo logs, reporting meeting changes.
Method signatures and docstrings:
- def __init__(self, input_stream, output_stream, summary, log_parser, renderer): Initialize with input and output streams, an empty summary, a log p... | Implement the Python class `LogSummarizer` described below.
Class description:
Summarizes meetup2xibo logs, reporting meeting changes.
Method signatures and docstrings:
- def __init__(self, input_stream, output_stream, summary, log_parser, renderer): Initialize with input and output streams, an empty summary, a log p... | 1e4d6ab0a246f76d3fdc2f0291e9ee95e4690bc8 | <|skeleton|>
class LogSummarizer:
"""Summarizes meetup2xibo logs, reporting meeting changes."""
def __init__(self, input_stream, output_stream, summary, log_parser, renderer):
"""Initialize with input and output streams, an empty summary, a log parser, and a renderer."""
<|body_0|>
def run... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogSummarizer:
"""Summarizes meetup2xibo logs, reporting meeting changes."""
def __init__(self, input_stream, output_stream, summary, log_parser, renderer):
"""Initialize with input and output streams, an empty summary, a log parser, and a renderer."""
self.input_stream = input_stream
... | the_stack_v2_python_sparse | meetup2xibo/log_summarizer/log_summarizer.py | DanielGomeX/meetup2xibo | train | 0 |
442a35930eedc934c94527842e346d0fc92dffdb | [
"instr_form = InstrumentForm()\nresult = InstrumentFormDialog(instr_form=instr_form, mode='new').exec_()\nmanager = view.manager\nif result:\n path = os.path.abspath(manager.instr_folder)\n filename = instr_form.name + '.ini'\n fullpath = os.path.join(path, filename)\n instr_config = ConfigObj(fullpath)... | <|body_start_0|>
instr_form = InstrumentForm()
result = InstrumentFormDialog(instr_form=instr_form, mode='new').exec_()
manager = view.manager
if result:
path = os.path.abspath(manager.instr_folder)
filename = instr_form.name + '.ini'
fullpath = os.pat... | Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the edited profile object_delete_instr_changed ... | InstrumentManagerHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstrumentManagerHandler:
"""Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, ... | stack_v2_sparse_classes_75kplus_train_070162 | 9,440 | no_license | [
{
"docstring": "Open a dialog to create a new profile and save it if the user close the dialog by cicking the 'OK' button.",
"name": "add_instr_clicked",
"signature": "def add_instr_clicked(self, view)"
},
{
"docstring": "Open a dialog to edit a profile and save the modifications if the user clo... | 3 | stack_v2_sparse_classes_30k_train_001999 | Implement the Python class `InstrumentManagerHandler` described below.
Class description:
Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked th... | Implement the Python class `InstrumentManagerHandler` described below.
Class description:
Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked th... | 981c3da42495414e9b3f42348c003bd50072dbbd | <|skeleton|>
class InstrumentManagerHandler:
"""Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstrumentManagerHandler:
"""Handler for the UI of an `InstrumentManager` instance Methods ------- object_add_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the new profile object_edit_instr_changed : If the user clicked the 'OK' button of the `InstrumentForm`, save the edit... | the_stack_v2_python_sparse | hqc_meas/instruments/instrument_manager.py | pheidmann/HQCMeas | train | 0 |
26841a961821eec14490ca74ee9cdf7d4d9b0d83 | [
"random.shuffle(nums)\nmid_index = len(nums) // 2\nself.quick_select(nums, mid_index)\nmid = nums[mid_index]\ni = 0\nj = 0\nk = len(nums) - 1\nwhile j < k:\n if nums[j] > mid:\n nums[j], nums[k] = (nums[k], nums[j])\n k -= 1\n elif nums[j] < mid:\n nums[i], nums[j] = (nums[j], nums[i])\n ... | <|body_start_0|>
random.shuffle(nums)
mid_index = len(nums) // 2
self.quick_select(nums, mid_index)
mid = nums[mid_index]
i = 0
j = 0
k = len(nums) - 1
while j < k:
if nums[j] > mid:
nums[j], nums[k] = (nums[k], nums[j])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int]"""
<|body_0|>
def quick_select(self, nums, target):
"""Args: nums: list[int target: int"""
<|body_1|>
def partition(self, nums, left, rig... | stack_v2_sparse_classes_75kplus_train_070163 | 2,730 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead. Args: nums: list[int]",
"name": "wiggleSort",
"signature": "def wiggleSort(self, nums)"
},
{
"docstring": "Args: nums: list[int target: int",
"name": "quick_select",
"signature": "def quick_select(self, nums, target)"
... | 3 | stack_v2_sparse_classes_30k_train_015002 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): Do not return anything, modify nums in-place instead. Args: nums: list[int]
- def quick_select(self, nums, target): Args: nums: list[int target: int
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): Do not return anything, modify nums in-place instead. Args: nums: list[int]
- def quick_select(self, nums, target): Args: nums: list[int target: int
-... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int]"""
<|body_0|>
def quick_select(self, nums, target):
"""Args: nums: list[int target: int"""
<|body_1|>
def partition(self, nums, left, rig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wiggleSort(self, nums):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int]"""
random.shuffle(nums)
mid_index = len(nums) // 2
self.quick_select(nums, mid_index)
mid = nums[mid_index]
i = 0
j = 0
k = len(n... | the_stack_v2_python_sparse | code/324. 摆动排序 II.py | AiZhanghan/Leetcode | train | 0 | |
7aecf2ed37f23e1c46f830617a0e68824252b60a | [
"self.least = 0\nself.num_tast = [0 for i in range(26)]\nfor i in tasks:\n self.num_tast[ord(i) - ord('A')] += 1\nself.num_tast = sorted(self.num_tast, reverse=True)\nself.num = self.num_tast[0:n + 1]\nwhile 0 not in self.num:\n self.least += n + 1\n for i in range(n + 1):\n self.num_tast[i] -= 1\n ... | <|body_start_0|>
self.least = 0
self.num_tast = [0 for i in range(26)]
for i in tasks:
self.num_tast[ord(i) - ord('A')] += 1
self.num_tast = sorted(self.num_tast, reverse=True)
self.num = self.num_tast[0:n + 1]
while 0 not in self.num:
self.least +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int 195ms"""
<|body_0|>
def leastInterval_1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int 172ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_070164 | 2,381 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int 195ms",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int 172ms",
"name": "leastInterval_1",
"signature": "def leastInterval_1(self, ... | 2 | stack_v2_sparse_classes_30k_train_035866 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int 195ms
- def leastInterval_1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int 17... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int 195ms
- def leastInterval_1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int 17... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int 195ms"""
<|body_0|>
def leastInterval_1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int 172ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int 195ms"""
self.least = 0
self.num_tast = [0 for i in range(26)]
for i in tasks:
self.num_tast[ord(i) - ord('A')] += 1
self.num_tast = sorted(self.num_tast, reverse... | the_stack_v2_python_sparse | TaskScheduler_MID_621.py | 953250587/leetcode-python | train | 2 | |
661f06fc427932570463a60c2b05e72193a87513 | [
"super(Criterion, self).__init__()\nself.par = opt\nself.temperature = opt.loss_softmax_temperature\nself.class_map = torch.nn.Parameter(torch.Tensor(opt.n_classes, opt.embed_dim))\nstdv = 1.0 / np.sqrt(self.class_map.size(1))\nself.class_map.data.uniform_(-stdv, stdv)\nself.name = 'softmax'\nself.lr = opt.loss_sof... | <|body_start_0|>
super(Criterion, self).__init__()
self.par = opt
self.temperature = opt.loss_softmax_temperature
self.class_map = torch.nn.Parameter(torch.Tensor(opt.n_classes, opt.embed_dim))
stdv = 1.0 / np.sqrt(self.class_map.size(1))
self.class_map.data.uniform_(-std... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_75kplus_train_070165 | 1,391 | permissive | [
{
"docstring": "Args: margin: Triplet Margin.",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [0,...,C-1], shape: (BS x 1)",
... | 2 | stack_v2_sparse_classes_30k_train_020643 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin.
- def forward(self, batch, labels, **kwargs): Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels:... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
<|body_0|>
def forward(self, batch, labels, **kwargs):
"""Args: batch: torch.Tensor: Input of embeddings with size (BS x DIM) labels: nparray/list: For each element of the batch assigns a class [... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin."""
super(Criterion, self).__init__()
self.par = opt
self.temperature = opt.loss_softmax_temperature
self.class_map = torch.nn.Parameter(torch.Tensor(opt.n_classes, opt.embed_dim))
stdv = 1.0 / ... | the_stack_v2_python_sparse | criteria/softmax.py | chenyanlinzhugoushou/DCML | train | 0 | |
d28f1bd9788243583dd2f1eb0ae5c814827583d6 | [
"self.activate = False\nself.menu = menu\nself.name = name\nself.profileJoinName = profilePluginFileName + '.& /' + name\nself.profilePluginFileName = profilePluginFileName\nself.radioVar = radioVar\nmenu.add_radiobutton(label=name.replace('_', ' '), command=self.clickRadio, value=self.profileJoinName, variable=sel... | <|body_start_0|>
self.activate = False
self.menu = menu
self.name = name
self.profileJoinName = profilePluginFileName + '.& /' + name
self.profilePluginFileName = profilePluginFileName
self.radioVar = radioVar
menu.add_radiobutton(label=name.replace('_', ' '), com... | A class to display a profile menu radio button. | ProfileMenuRadio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
<|body_0|>
def clickRadio(self):
"""Workaround for Tkinter bug, invoke and set the v... | stack_v2_sparse_classes_75kplus_train_070166 | 4,695 | no_license | [
{
"docstring": "Create a profile menu radio.",
"name": "__init__",
"signature": "def __init__(self, profilePluginFileName, menu, name, radioVar, value)"
},
{
"docstring": "Workaround for Tkinter bug, invoke and set the value when clicked.",
"name": "clickRadio",
"signature": "def clickRa... | 2 | stack_v2_sparse_classes_30k_train_019571 | Implement the Python class `ProfileMenuRadio` described below.
Class description:
A class to display a profile menu radio button.
Method signatures and docstrings:
- def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio.
- def clickRadio(self): Workaround for Tkinter bug,... | Implement the Python class `ProfileMenuRadio` described below.
Class description:
A class to display a profile menu radio button.
Method signatures and docstrings:
- def __init__(self, profilePluginFileName, menu, name, radioVar, value): Create a profile menu radio.
- def clickRadio(self): Workaround for Tkinter bug,... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
<|body_0|>
def clickRadio(self):
"""Workaround for Tkinter bug, invoke and set the v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileMenuRadio:
"""A class to display a profile menu radio button."""
def __init__(self, profilePluginFileName, menu, name, radioVar, value):
"""Create a profile menu radio."""
self.activate = False
self.menu = menu
self.name = name
self.profileJoinName = profile... | the_stack_v2_python_sparse | skeinforge_application/skeinforge_plugins/profile.py | amsler/skeinforge | train | 10 |
f7fd502b26252f96f3188a2afd10bc975f75ab9b | [
"parser.add_argument('config', metavar='INSTANCE_CONFIG', completer=flags.InstanceConfigCompleter, help=\"Cloud Spanner instance configuration. The 'custom-' prefix is required to avoid name conflicts with Google-managed configurations.\")\nparser.add_argument('--display-name', help='The name of this instance confi... | <|body_start_0|>
parser.add_argument('config', metavar='INSTANCE_CONFIG', completer=flags.InstanceConfigCompleter, help="Cloud Spanner instance configuration. The 'custom-' prefix is required to avoid name conflicts with Google-managed configurations.")
parser.add_argument('--display-name', help='The na... | Create a Cloud Spanner instance configuration. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments a... | stack_v2_sparse_classes_75kplus_train_070167 | 7,591 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_035737 | Implement the Python class `Create` described below.
Class description:
Create a Cloud Spanner instance configuration.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on th... | Implement the Python class `Create` described below.
Class description:
Create a Cloud Spanner instance configuration.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on th... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Create:
"""Create a Cloud Spanner instance configuration."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.""... | the_stack_v2_python_sparse | lib/surface/spanner/instance_configs/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
4f13d081e64ede2a1cce0231f137bff549c0dfdf | [
"if model._meta.app_label == 'rcs_assets':\n return 'rcs_assets'\nreturn None",
"if model._meta.app_label == 'rcs_assets':\n return 'rcs_assets'\nreturn None",
"if obj1._meta.app_label == 'rcs_assets' or obj2._meta.app_label == 'rcs_assets':\n return True\nreturn None",
"if app_label == 'rcs_assets':... | <|body_start_0|>
if model._meta.app_label == 'rcs_assets':
return 'rcs_assets'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'rcs_assets':
return 'rcs_assets'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label =... | A read-only router to control all database operations on models in the rcs_assets application. | RCSAssetsRouter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RCSAssetsRouter:
"""A read-only router to control all database operations on models in the rcs_assets application."""
def db_for_read(self, model, **hints):
"""Attempts to read rcs_assets models go to rcs_assets."""
<|body_0|>
def db_for_write(self, model, **hints):
... | stack_v2_sparse_classes_75kplus_train_070168 | 1,057 | permissive | [
{
"docstring": "Attempts to read rcs_assets models go to rcs_assets.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "No writes.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
{
"docstring": "Allo... | 4 | stack_v2_sparse_classes_30k_train_015420 | Implement the Python class `RCSAssetsRouter` described below.
Class description:
A read-only router to control all database operations on models in the rcs_assets application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read rcs_assets models go to rcs_assets.
- def db_for_w... | Implement the Python class `RCSAssetsRouter` described below.
Class description:
A read-only router to control all database operations on models in the rcs_assets application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read rcs_assets models go to rcs_assets.
- def db_for_w... | c6e3bf2b6c79d60b9f278c4c352899f33ce02ddb | <|skeleton|>
class RCSAssetsRouter:
"""A read-only router to control all database operations on models in the rcs_assets application."""
def db_for_read(self, model, **hints):
"""Attempts to read rcs_assets models go to rcs_assets."""
<|body_0|>
def db_for_write(self, model, **hints):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RCSAssetsRouter:
"""A read-only router to control all database operations on models in the rcs_assets application."""
def db_for_read(self, model, **hints):
"""Attempts to read rcs_assets models go to rcs_assets."""
if model._meta.app_label == 'rcs_assets':
return 'rcs_assets'... | the_stack_v2_python_sparse | rcs_assets/router.py | rockychen-dpaw/oim-cms | train | 0 |
2ba0d3c9aa305dcb2478797e0136bd1f0efea585 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | MoleculeServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoleculeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def CreateMolecule(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ReadMolecule(self, request, context):
"""Missing asso... | stack_v2_sparse_classes_75kplus_train_070169 | 8,836 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "CreateMolecule",
"signature": "def CreateMolecule(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ReadMolecule",
"signature": "def ReadMolec... | 5 | stack_v2_sparse_classes_30k_test_000011 | Implement the Python class `MoleculeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def CreateMolecule(self, request, context): Missing associated documentation comment in .proto file.
- def ReadMolecule(self, request, c... | Implement the Python class `MoleculeServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def CreateMolecule(self, request, context): Missing associated documentation comment in .proto file.
- def ReadMolecule(self, request, c... | fabf8b7d753570f2404f2d9830c59786a8c78468 | <|skeleton|>
class MoleculeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def CreateMolecule(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def ReadMolecule(self, request, context):
"""Missing asso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoleculeServiceServicer:
"""Missing associated documentation comment in .proto file."""
def CreateMolecule(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implem... | the_stack_v2_python_sparse | gsoc2022/smilesdb/rpc_handler/molecule_pb2_grpc.py | apache/airavata-sandbox | train | 3 |
a27d12c4a81e6ba65fd390657ca38f2b7ee02065 | [
"url = '/api/options/?list=org_structure'\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, self.div1.name)\nr = response.json()\nself.assertTrue(isinstance(r, dict))\nself.assertTrue(isinstance(r['objects'], list))\nself.branch1.active = False\nself.branch... | <|body_start_0|>
url = '/api/options/?list=org_structure'
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.div1.name)
r = response.json()
self.assertTrue(isinstance(r, dict))
self.assertTrue(isinstance(... | OptionResourceTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionResourceTestCase:
def test_data_org_structure(self):
"""Test the data_org_structure API endpoint"""
<|body_0|>
def test_data_cost_centre(self):
"""Test the data_cost_centre API endpoint"""
<|body_1|>
def test_data_org_unit(self):
"""Test th... | stack_v2_sparse_classes_75kplus_train_070170 | 18,653 | permissive | [
{
"docstring": "Test the data_org_structure API endpoint",
"name": "test_data_org_structure",
"signature": "def test_data_org_structure(self)"
},
{
"docstring": "Test the data_cost_centre API endpoint",
"name": "test_data_cost_centre",
"signature": "def test_data_cost_centre(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_041831 | Implement the Python class `OptionResourceTestCase` described below.
Class description:
Implement the OptionResourceTestCase class.
Method signatures and docstrings:
- def test_data_org_structure(self): Test the data_org_structure API endpoint
- def test_data_cost_centre(self): Test the data_cost_centre API endpoint
... | Implement the Python class `OptionResourceTestCase` described below.
Class description:
Implement the OptionResourceTestCase class.
Method signatures and docstrings:
- def test_data_org_structure(self): Test the data_org_structure API endpoint
- def test_data_cost_centre(self): Test the data_cost_centre API endpoint
... | 4d5caceba69cac7f59b63745a0f52322004df2eb | <|skeleton|>
class OptionResourceTestCase:
def test_data_org_structure(self):
"""Test the data_org_structure API endpoint"""
<|body_0|>
def test_data_cost_centre(self):
"""Test the data_cost_centre API endpoint"""
<|body_1|>
def test_data_org_unit(self):
"""Test th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptionResourceTestCase:
def test_data_org_structure(self):
"""Test the data_org_structure API endpoint"""
url = '/api/options/?list=org_structure'
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.div1.name)
... | the_stack_v2_python_sparse | organisation/test_api.py | bryceprince0/it-assets | train | 0 | |
def8241afc73f7e548820095bd53677ce7ebe87e | [
"us = UnitSystem()\nunit = us.unit('meter')\nself.assertTrue(isinstance(unit.unit, pint.Unit))",
"us = UnitSystem()\ndimension = Dimension(unit_system=us, code='[length]')\nunit = us.unit('meter')\nself.assertIn(dimension.code, [d.code for d in unit.dimensions])",
"us = UnitSystem()\nunit = us.unit(unit_name='m... | <|body_start_0|>
us = UnitSystem()
unit = us.unit('meter')
self.assertTrue(isinstance(unit.unit, pint.Unit))
<|end_body_0|>
<|body_start_1|>
us = UnitSystem()
dimension = Dimension(unit_system=us, code='[length]')
unit = us.unit('meter')
self.assertIn(dimension.c... | Test Unit object | UnitTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTest:
"""Test Unit object"""
def test_creation(self):
"""Test creation of Unit"""
<|body_0|>
def test_dimensions(self):
"""Test unit dimensions"""
<|body_1|>
def test_readable_dimension(self):
"""Test user readable dimension for unit"""
... | stack_v2_sparse_classes_75kplus_train_070171 | 38,680 | permissive | [
{
"docstring": "Test creation of Unit",
"name": "test_creation",
"signature": "def test_creation(self)"
},
{
"docstring": "Test unit dimensions",
"name": "test_dimensions",
"signature": "def test_dimensions(self)"
},
{
"docstring": "Test user readable dimension for unit",
"na... | 3 | null | Implement the Python class `UnitTest` described below.
Class description:
Test Unit object
Method signatures and docstrings:
- def test_creation(self): Test creation of Unit
- def test_dimensions(self): Test unit dimensions
- def test_readable_dimension(self): Test user readable dimension for unit | Implement the Python class `UnitTest` described below.
Class description:
Test Unit object
Method signatures and docstrings:
- def test_creation(self): Test creation of Unit
- def test_dimensions(self): Test unit dimensions
- def test_readable_dimension(self): Test user readable dimension for unit
<|skeleton|>
class... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class UnitTest:
"""Test Unit object"""
def test_creation(self):
"""Test creation of Unit"""
<|body_0|>
def test_dimensions(self):
"""Test unit dimensions"""
<|body_1|>
def test_readable_dimension(self):
"""Test user readable dimension for unit"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnitTest:
"""Test Unit object"""
def test_creation(self):
"""Test creation of Unit"""
us = UnitSystem()
unit = us.unit('meter')
self.assertTrue(isinstance(unit.unit, pint.Unit))
def test_dimensions(self):
"""Test unit dimensions"""
us = UnitSystem()
... | the_stack_v2_python_sparse | src/geocurrency/units/tests.py | fmeurou/geocurrency | train | 5 |
1355d8e5fb49031ac6ab52459aaaa445917f45dd | [
"self.login()\nresponse = self.client.get(self.target_url)\nactual = response.resolver_match.func.__name__\nexpected = MedidaListView.as_view().__name__\nself.assertEqual(actual, expected, 'La vista de listado de medidas no es MedidaListView')",
"login_url = reverse('login')\nresponse = self.client.get(self.targe... | <|body_start_0|>
self.login()
response = self.client.get(self.target_url)
actual = response.resolver_match.func.__name__
expected = MedidaListView.as_view().__name__
self.assertEqual(actual, expected, 'La vista de listado de medidas no es MedidaListView')
<|end_body_0|>
<|body_s... | Pruebas para la vista de listado de medidas | MedidaListViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
<|body_0|>
def test_login_required(self):
"""Prueba que la vista sea solame... | stack_v2_sparse_classes_75kplus_train_070172 | 7,967 | no_license | [
{
"docstring": "Prueba que el url de listado de medidas use la vista MedidaListView",
"name": "test_url_view_correspondence",
"signature": "def test_url_view_correspondence(self)"
},
{
"docstring": "Prueba que la vista sea solamente accedible por usuarios autenticados",
"name": "test_login_r... | 4 | stack_v2_sparse_classes_30k_train_036261 | Implement the Python class `MedidaListViewTestCase` described below.
Class description:
Pruebas para la vista de listado de medidas
Method signatures and docstrings:
- def test_url_view_correspondence(self): Prueba que el url de listado de medidas use la vista MedidaListView
- def test_login_required(self): Prueba qu... | Implement the Python class `MedidaListViewTestCase` described below.
Class description:
Pruebas para la vista de listado de medidas
Method signatures and docstrings:
- def test_url_view_correspondence(self): Prueba que el url de listado de medidas use la vista MedidaListView
- def test_login_required(self): Prueba qu... | 64a8f8350f9092126864f3676f27dc690ed2a5f8 | <|skeleton|>
class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
<|body_0|>
def test_login_required(self):
"""Prueba que la vista sea solame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedidaListViewTestCase:
"""Pruebas para la vista de listado de medidas"""
def test_url_view_correspondence(self):
"""Prueba que el url de listado de medidas use la vista MedidaListView"""
self.login()
response = self.client.get(self.target_url)
actual = response.resolver_m... | the_stack_v2_python_sparse | medidas/test_views.py | german1608/EIA_CI4712 | train | 1 |
ae802e28daa648cb6f8ea92ca9b12f18eee4282d | [
"user = request.user\ntry:\n address = user.address_set.latest('create_time')\nexcept Address.DoesNotExist:\n address = None\ncontext = {'address': address}\nreturn render(request, 'user_center_site.html', context)",
"recv_name = request.POST.get('recv_name')\naddr = request.POST.get('addr')\nzip_code = req... | <|body_start_0|>
user = request.user
try:
address = user.address_set.latest('create_time')
except Address.DoesNotExist:
address = None
context = {'address': address}
return render(request, 'user_center_site.html', context)
<|end_body_0|>
<|body_start_1|>
... | 收货地址 | AddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressView:
"""收货地址"""
def get(self, request):
"""查询地址信息,并且渲染页面,响应给用户"""
<|body_0|>
def post(self, request):
"""编辑地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = request.user
try:
address = user.address_set.latest(... | stack_v2_sparse_classes_75kplus_train_070173 | 11,372 | no_license | [
{
"docstring": "查询地址信息,并且渲染页面,响应给用户",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "编辑地址",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037560 | Implement the Python class `AddressView` described below.
Class description:
收货地址
Method signatures and docstrings:
- def get(self, request): 查询地址信息,并且渲染页面,响应给用户
- def post(self, request): 编辑地址 | Implement the Python class `AddressView` described below.
Class description:
收货地址
Method signatures and docstrings:
- def get(self, request): 查询地址信息,并且渲染页面,响应给用户
- def post(self, request): 编辑地址
<|skeleton|>
class AddressView:
"""收货地址"""
def get(self, request):
"""查询地址信息,并且渲染页面,响应给用户"""
<|bod... | 40b4b4a8b412a176eaa634b9b6a38c26cdee93a9 | <|skeleton|>
class AddressView:
"""收货地址"""
def get(self, request):
"""查询地址信息,并且渲染页面,响应给用户"""
<|body_0|>
def post(self, request):
"""编辑地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressView:
"""收货地址"""
def get(self, request):
"""查询地址信息,并且渲染页面,响应给用户"""
user = request.user
try:
address = user.address_set.latest('create_time')
except Address.DoesNotExist:
address = None
context = {'address': address}
return ren... | the_stack_v2_python_sparse | dailyfresh_23/apps/users/views.py | zhuyuntao6561/Electricity-project | train | 0 |
534837d0f7bf9977c629f194c52f99eb17ae3824 | [
"C = self.COEFFS[imt]\nmagML = ghasemi_bl_mw2ml(rup.mag)\nc0 = 0.0\nR = np.sqrt(dists.rhypo ** 2 + c0 ** 2)\nmean = C['a'] * np.exp(C['b'] * magML) * R ** (-1 * C['c'])\nif isinstance(imt, PGA):\n mean = np.log(mean / g)\nelse:\n mean = np.log(mean / 10.0)\nstddevs = self._get_stddevs(C, stddev_types, dists.r... | <|body_start_0|>
C = self.COEFFS[imt]
magML = ghasemi_bl_mw2ml(rup.mag)
c0 = 0.0
R = np.sqrt(dists.rhypo ** 2 + c0 ** 2)
mean = C['a'] * np.exp(C['b'] * magML) * R ** (-1 * C['c'])
if isinstance(imt, PGA):
mean = np.log(mean / g)
else:
mean... | Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Probabilistic earthquake risk maps of Australia, Aust. J. Earth. Sci. 37, 169-187, doi... | GaullEtAL1990PGA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaullEtAL1990PGA:
"""Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Probabilistic earthquake risk maps of Aust... | stack_v2_sparse_classes_75kplus_train_070174 | 14,553 | no_license | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Return total standa... | 2 | stack_v2_sparse_classes_30k_train_025237 | Implement the Python class `GaullEtAL1990PGA` described below.
Class description:
Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Pro... | Implement the Python class `GaullEtAL1990PGA` described below.
Class description:
Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Pro... | 86a3af0b52fe51470754291700f9a985b5177e2a | <|skeleton|>
class GaullEtAL1990PGA:
"""Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Probabilistic earthquake risk maps of Aust... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaullEtAL1990PGA:
"""Implement equation used to underpin the Structural design actions, part 4: Earthquake actions in Australia, Standards Australia AS 1170.4–2007. Equation coefficients as per Gaull, B. A., M. O. Michael-Leiba, and J. M. W. Rynn (1990). Probabilistic earthquake risk maps of Australia, Aust. ... | the_stack_v2_python_sparse | ground_motion/gaull_1990.py | GeoscienceAustralia/NSHA2018 | train | 7 |
1053ed374a79e18aa796f9961319a43862d6949f | [
"super(CompetitiveDenseBlockInput, self).__init__()\npadding_h = int((params['kernel_h'] - 1) / 2)\npadding_w = int((params['kernel_w'] - 1) / 2)\nconv0_in_size = int(params['num_channels'])\nconv1_in_size = int(params['num_filters'])\nconv2_in_size = int(params['num_filters'])\nself.conv0 = nn.Conv2d(in_channels=c... | <|body_start_0|>
super(CompetitiveDenseBlockInput, self).__init__()
padding_h = int((params['kernel_h'] - 1) / 2)
padding_w = int((params['kernel_w'] - 1) / 2)
conv0_in_size = int(params['num_channels'])
conv1_in_size = int(params['num_filters'])
conv2_in_size = int(param... | Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool': 2, 'stride_pool': 2, 'num_classes': 44 'kernel_c':1 'input':True } | CompetitiveDenseBlockInput | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompetitiveDenseBlockInput:
"""Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool': 2, 'stride_pool': 2, 'num_classes': 44... | stack_v2_sparse_classes_75kplus_train_070175 | 12,544 | permissive | [
{
"docstring": "Constructor to initialize the Competitive Dense Block :param dict params: dictionary with parameters specifiying block architecture",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "CompetitiveDenseBlockInput's computational Graph in -> BN -> {Con... | 2 | stack_v2_sparse_classes_30k_train_026287 | Implement the Python class `CompetitiveDenseBlockInput` described below.
Class description:
Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool':... | Implement the Python class `CompetitiveDenseBlockInput` described below.
Class description:
Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool':... | 1f20d60d4e81332715f7e50d82ad6779963fe30a | <|skeleton|>
class CompetitiveDenseBlockInput:
"""Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool': 2, 'stride_pool': 2, 'num_classes': 44... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompetitiveDenseBlockInput:
"""Function to define a competitive dense block comprising of 3 convolutional layers, with BN/ReLU for input Inputs: -- Params params = {'num_channels': 1, 'num_filters': 64, 'kernel_h': 5, 'kernel_w': 5, 'stride_conv': 1, 'pool': 2, 'stride_pool': 2, 'num_classes': 44 'kernel_c':1... | the_stack_v2_python_sparse | FastSurferCNN/models/sub_module.py | abdullahbas/FastSurfer | train | 0 |
657ee906a8b8db64e8cd5527dbad35fe6fcbb8a0 | [
"self.name = name\nself.description = description\nif resources is not None:\n self.set_resources(resources)",
"self.resources[:] = []\nnew_resource_names = set(new_resources)\nnew_resources = ResourcePermission.query.filter(ResourcePermission.resource.in_(new_resource_names)).all() if new_resource_names else ... | <|body_start_0|>
self.name = name
self.description = description
if resources is not None:
self.set_resources(resources)
<|end_body_0|>
<|body_start_1|>
self.resources[:] = []
new_resource_names = set(new_resources)
new_resources = ResourcePermission.query.fi... | Role | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Role:
def __init__(self, name, description='', resources=None):
"""Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: name (str): The name of the Role. description (str, optional): A description of the role. resou... | stack_v2_sparse_classes_75kplus_train_070176 | 11,130 | permissive | [
{
"docstring": "Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: name (str): The name of the Role. description (str, optional): A description of the role. resources (list[str]): The list of root endpoints that a user with this Role can... | 3 | stack_v2_sparse_classes_30k_train_042058 | Implement the Python class `Role` described below.
Class description:
Implement the Role class.
Method signatures and docstrings:
- def __init__(self, name, description='', resources=None): Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: na... | Implement the Python class `Role` described below.
Class description:
Implement the Role class.
Method signatures and docstrings:
- def __init__(self, name, description='', resources=None): Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: na... | 18cd8b6d10241955bea5422947af9cf67f73aead | <|skeleton|>
class Role:
def __init__(self, name, description='', resources=None):
"""Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: name (str): The name of the Role. description (str, optional): A description of the role. resou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Role:
def __init__(self, name, description='', resources=None):
"""Initializes a Role object. Each user has one or more Roles associated with it, which determines the user's permissions. Args: name (str): The name of the Role. description (str, optional): A description of the role. resources (list[str... | the_stack_v2_python_sparse | server/database.py | JustinTervala/WALKOFF | train | 0 | |
195152f62d9a07523aca92f67455cc3524ad96c2 | [
"ret = dict()\ntem_id = request.GET.get('id')\nstatus = request.GET.get('status')\ntoday = datetime.date.today()\nif status == '1':\n record = WorkRecord()\n record.tem_id = tem_id\n record.is_submit = False\n record.is_done = True\n record.save()\nif status == '0':\n record = WorkRecord.objects.f... | <|body_start_0|>
ret = dict()
tem_id = request.GET.get('id')
status = request.GET.get('status')
today = datetime.date.today()
if status == '1':
record = WorkRecord()
record.tem_id = tem_id
record.is_submit = False
record.is_done = T... | 日志ajax | WorkRecordAjax | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkRecordAjax:
"""日志ajax"""
def get(self, request):
"""当日完成情况ajax :param request: :return:"""
<|body_0|>
def post(self, request):
"""日志提交ajax :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = dict()
tem_id =... | stack_v2_sparse_classes_75kplus_train_070177 | 19,909 | no_license | [
{
"docstring": "当日完成情况ajax :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "日志提交ajax :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `WorkRecordAjax` described below.
Class description:
日志ajax
Method signatures and docstrings:
- def get(self, request): 当日完成情况ajax :param request: :return:
- def post(self, request): 日志提交ajax :param request: :return: | Implement the Python class `WorkRecordAjax` described below.
Class description:
日志ajax
Method signatures and docstrings:
- def get(self, request): 当日完成情况ajax :param request: :return:
- def post(self, request): 日志提交ajax :param request: :return:
<|skeleton|>
class WorkRecordAjax:
"""日志ajax"""
def get(self, re... | 14ebfaefbc2ab12f8f61459d0bccd3f3420bce8b | <|skeleton|>
class WorkRecordAjax:
"""日志ajax"""
def get(self, request):
"""当日完成情况ajax :param request: :return:"""
<|body_0|>
def post(self, request):
"""日志提交ajax :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkRecordAjax:
"""日志ajax"""
def get(self, request):
"""当日完成情况ajax :param request: :return:"""
ret = dict()
tem_id = request.GET.get('id')
status = request.GET.get('status')
today = datetime.date.today()
if status == '1':
record = WorkRecord()
... | the_stack_v2_python_sparse | apps/worklog/views.py | PiKeHuPu/YunOA | train | 0 |
ae5ef2121c85f7e2848ac02c61ad1d5df8a7bd02 | [
"cls.database = KineticsDatabase()\ncls.database.load_libraries(os.path.join(settings['test_data.directory'], 'testing_database', 'kinetics', 'libraries'), libraries=None)\ncls.libraries = cls.database.libraries",
"lib_rxns = self.libraries['GRI-Mech3.0'].get_library_reactions()\nfor rxn in lib_rxns:\n self.as... | <|body_start_0|>
cls.database = KineticsDatabase()
cls.database.load_libraries(os.path.join(settings['test_data.directory'], 'testing_database', 'kinetics', 'libraries'), libraries=None)
cls.libraries = cls.database.libraries
<|end_body_0|>
<|body_start_1|>
lib_rxns = self.libraries['GR... | TestLibrary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLibrary:
def setUpClass(cls):
"""A function run ONCE before all unit tests in this class."""
<|body_0|>
def test_get_library_reactions(self):
"""test that get_library_reactions loads reactions correctly"""
<|body_1|>
def test_save_library(self):
... | stack_v2_sparse_classes_75kplus_train_070178 | 7,164 | permissive | [
{
"docstring": "A function run ONCE before all unit tests in this class.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "test that get_library_reactions loads reactions correctly",
"name": "test_get_library_reactions",
"signature": "def test_get_library_reac... | 4 | stack_v2_sparse_classes_30k_train_040913 | Implement the Python class `TestLibrary` described below.
Class description:
Implement the TestLibrary class.
Method signatures and docstrings:
- def setUpClass(cls): A function run ONCE before all unit tests in this class.
- def test_get_library_reactions(self): test that get_library_reactions loads reactions correc... | Implement the Python class `TestLibrary` described below.
Class description:
Implement the TestLibrary class.
Method signatures and docstrings:
- def setUpClass(cls): A function run ONCE before all unit tests in this class.
- def test_get_library_reactions(self): test that get_library_reactions loads reactions correc... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestLibrary:
def setUpClass(cls):
"""A function run ONCE before all unit tests in this class."""
<|body_0|>
def test_get_library_reactions(self):
"""test that get_library_reactions loads reactions correctly"""
<|body_1|>
def test_save_library(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLibrary:
def setUpClass(cls):
"""A function run ONCE before all unit tests in this class."""
cls.database = KineticsDatabase()
cls.database.load_libraries(os.path.join(settings['test_data.directory'], 'testing_database', 'kinetics', 'libraries'), libraries=None)
cls.librari... | the_stack_v2_python_sparse | rmgpy/data/kinetics/libraryTest.py | CanePan-cc/CanePanWorkshop | train | 2 | |
b6f5a597e9476892597190aedabef8077c18ef43 | [
"if isinstance(self, Empty):\n return self.valid\nelif isinstance(self, All):\n return len(self.rules) == 1 and self.rules[0].is_valid\nelif isinstance(self, Any):\n return all((rule.is_valid for rule in self.rules))\nelif isinstance(self, Branch):\n return self.rule.is_valid\nelif isinstance(self, Elem... | <|body_start_0|>
if isinstance(self, Empty):
return self.valid
elif isinstance(self, All):
return len(self.rules) == 1 and self.rules[0].is_valid
elif isinstance(self, Any):
return all((rule.is_valid for rule in self.rules))
elif isinstance(self, Branc... | HasState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
<|body_0|>
def is_error(self) -> bool:
"""Return True when a Rule is error"""
<|body_1|>
def is_terminal(self) -> bool:
"""Return True when a Rule is terminal"""
... | stack_v2_sparse_classes_75kplus_train_070179 | 16,154 | permissive | [
{
"docstring": "Return True when a Rule is valid",
"name": "is_valid",
"signature": "def is_valid(self) -> bool"
},
{
"docstring": "Return True when a Rule is error",
"name": "is_error",
"signature": "def is_error(self) -> bool"
},
{
"docstring": "Return True when a Rule is termi... | 3 | stack_v2_sparse_classes_30k_train_002946 | Implement the Python class `HasState` described below.
Class description:
Implement the HasState class.
Method signatures and docstrings:
- def is_valid(self) -> bool: Return True when a Rule is valid
- def is_error(self) -> bool: Return True when a Rule is error
- def is_terminal(self) -> bool: Return True when a Ru... | Implement the Python class `HasState` described below.
Class description:
Implement the HasState class.
Method signatures and docstrings:
- def is_valid(self) -> bool: Return True when a Rule is valid
- def is_error(self) -> bool: Return True when a Rule is error
- def is_terminal(self) -> bool: Return True when a Ru... | 39ceb323a63af35e32c4be34ae35a77e811bc973 | <|skeleton|>
class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
<|body_0|>
def is_error(self) -> bool:
"""Return True when a Rule is error"""
<|body_1|>
def is_terminal(self) -> bool:
"""Return True when a Rule is terminal"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HasState:
def is_valid(self) -> bool:
"""Return True when a Rule is valid"""
if isinstance(self, Empty):
return self.valid
elif isinstance(self, All):
return len(self.rules) == 1 and self.rules[0].is_valid
elif isinstance(self, Any):
return a... | the_stack_v2_python_sparse | item_engine/base.py | GabrielAmare/TextEngine | train | 0 | |
cb82c6fd958fd9f2a6dc5b2d445a99f30cbc4a12 | [
"if Arm64e.check_valid_pointer_format(pointer_format):\n raise NotImplementedError('Arm64e is not implemented yet')\nelif Generic64.check_valid_pointer_format(pointer_format):\n if self.generic64.bind.bind:\n return (self.generic64.bind.ordinal, self.generic64.bind.addend)\n else:\n return No... | <|body_start_0|>
if Arm64e.check_valid_pointer_format(pointer_format):
raise NotImplementedError('Arm64e is not implemented yet')
elif Generic64.check_valid_pointer_format(pointer_format):
if self.generic64.bind.bind:
return (self.generic64.bind.ordinal, self.gene... | the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141 | ChainedFixupPointerOnDisk | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_75kplus_train_070180 | 13,909 | permissive | [
{
"docstring": "Port of ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal, int64_t& addend) https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.cpp#L1098-L1147 Returns None if not a bind (so `if struct.isBind()` works), :return:",
"name": "isBind",
"signat... | 2 | stack_v2_sparse_classes_30k_train_040957 | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | Implement the Python class `ChainedFixupPointerOnDisk` described below.
Class description:
the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141
Method signatures and docstrings:
- def isBind(self, pointer_format: DyldChainedPtrFor... | 23edc1e95b0b1bace308ca80b5a8189bf8cbf8f3 | <|skeleton|>
class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupP... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChainedFixupPointerOnDisk:
"""the ChainedFixupPointerOnDisk union from dyld MachOLoaded.h https://github.com/apple-opensource/dyld/blob/852.2/dyld3/MachOLoaded.h#L87-L141"""
def isBind(self, pointer_format: DyldChainedPtrFormats) -> Optional[Tuple[int, int]]:
"""Port of ChainedFixupPointerOnDisk:... | the_stack_v2_python_sparse | cle/backends/macho/structs.py | angr/cle | train | 389 |
e3745ac7024adf65b89c7da84242cbb674809f5f | [
"setup_id = kwargs['setup']\ntest_id = kwargs['test']\nsetup = Setup.objects.get(pk=setup_id)\ntest = TestCase.objects.get(pk=test_id)\no = SetupAndTestCaseIntermediateTable.objects.create(testcase=test, setup=setup)\nserializer1 = SetupAndTestCaseIntermediateTableSerializer(instance=o)\nreturn Response(serializer1... | <|body_start_0|>
setup_id = kwargs['setup']
test_id = kwargs['test']
setup = Setup.objects.get(pk=setup_id)
test = TestCase.objects.get(pk=test_id)
o = SetupAndTestCaseIntermediateTable.objects.create(testcase=test, setup=setup)
serializer1 = SetupAndTestCaseIntermediateT... | Setup step view | SetupAndTestCaseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetupAndTestCaseView:
"""Setup step view"""
def post(self, request, *args, **kwargs):
"""Create setup step"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""Delete a setup step"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
setup_id ... | stack_v2_sparse_classes_75kplus_train_070181 | 3,259 | no_license | [
{
"docstring": "Create setup step",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Delete a setup step",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `SetupAndTestCaseView` described below.
Class description:
Setup step view
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create setup step
- def delete(self, request, *args, **kwargs): Delete a setup step | Implement the Python class `SetupAndTestCaseView` described below.
Class description:
Setup step view
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Create setup step
- def delete(self, request, *args, **kwargs): Delete a setup step
<|skeleton|>
class SetupAndTestCaseView:
"""Setup... | 2885edcf91ad887505850ae5d0ef7f65dbebef34 | <|skeleton|>
class SetupAndTestCaseView:
"""Setup step view"""
def post(self, request, *args, **kwargs):
"""Create setup step"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""Delete a setup step"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetupAndTestCaseView:
"""Setup step view"""
def post(self, request, *args, **kwargs):
"""Create setup step"""
setup_id = kwargs['setup']
test_id = kwargs['test']
setup = Setup.objects.get(pk=setup_id)
test = TestCase.objects.get(pk=test_id)
o = SetupAndTest... | the_stack_v2_python_sparse | asura/steps/views.py | EtheriousNatsu/asura-web | train | 0 |
269c9c5f8d21277d3660bbd9fd6d464a19b70b4c | [
"if self.request.method == 'GET':\n return [permissions.IsAuthenticated(), IsCasePatientOrDoctor(self.kwargs['case_id'])]\nif self.request.method == 'POST':\n return (permissions.IsAuthenticated(), IsFollowUpDoctor())\nreturn (permissions.IsAuthenticated(), IsFollowUpDoctor())",
"queryset = FollowUp.objects... | <|body_start_0|>
if self.request.method == 'GET':
return [permissions.IsAuthenticated(), IsCasePatientOrDoctor(self.kwargs['case_id'])]
if self.request.method == 'POST':
return (permissions.IsAuthenticated(), IsFollowUpDoctor())
return (permissions.IsAuthenticated(), IsFo... | Guidelines CRUD | FollowUpViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowUpViewSet:
"""Guidelines CRUD"""
def get_permissions(self):
"""Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup"""
<|body_0|>
def get_queryset(self):
"""queryset returns only case's follow up type filter status f... | stack_v2_sparse_classes_75kplus_train_070182 | 15,503 | no_license | [
{
"docstring": "Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "queryset returns only case's follow up type filter status filter",
"name": "get_queryset",
... | 3 | stack_v2_sparse_classes_30k_train_013513 | Implement the Python class `FollowUpViewSet` described below.
Class description:
Guidelines CRUD
Method signatures and docstrings:
- def get_permissions(self): Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup
- def get_queryset(self): queryset returns only case's follow up... | Implement the Python class `FollowUpViewSet` described below.
Class description:
Guidelines CRUD
Method signatures and docstrings:
- def get_permissions(self): Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup
- def get_queryset(self): queryset returns only case's follow up... | 413664d4e77020c8fcb6bf95e31e3ff9908e2b60 | <|skeleton|>
class FollowUpViewSet:
"""Guidelines CRUD"""
def get_permissions(self):
"""Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup"""
<|body_0|>
def get_queryset(self):
"""queryset returns only case's follow up type filter status f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FollowUpViewSet:
"""Guidelines CRUD"""
def get_permissions(self):
"""Patients and doctors can view followup Doctors and Surgeons can create/update/delete followup"""
if self.request.method == 'GET':
return [permissions.IsAuthenticated(), IsCasePatientOrDoctor(self.kwargs['case... | the_stack_v2_python_sparse | noccapp/views/case.py | otto-torino/nocc-server | train | 0 |
a8240cb7838e22a325f348063a80a9757ee5e98e | [
"result = 0\nfor cell in self.grid[row]:\n if cell.remove_possibility(number):\n result += 1\nreturn result",
"result = 0\nfor row in self.grid:\n if row[col].remove_possibility(number):\n result += 1\nreturn result",
"result = 0\nbox_row, box_col = self.grid.get_box_coords(cell_r, cell_c)\n... | <|body_start_0|>
result = 0
for cell in self.grid[row]:
if cell.remove_possibility(number):
result += 1
return result
<|end_body_0|>
<|body_start_1|>
result = 0
for row in self.grid:
if row[col].remove_possibility(number):
... | Solve sudokus using only beginer technique. | SimpleSudokuSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleSudokuSolver:
"""Solve sudokus using only beginer technique."""
def row_remove_possibility(self, row: int, number: int) -> int:
"""Remove known value from the possibilities of the row."""
<|body_0|>
def col_remove_possibility(self, col: int, number: int) -> int:
... | stack_v2_sparse_classes_75kplus_train_070183 | 1,934 | no_license | [
{
"docstring": "Remove known value from the possibilities of the row.",
"name": "row_remove_possibility",
"signature": "def row_remove_possibility(self, row: int, number: int) -> int"
},
{
"docstring": "Remove known value from the possibilities of the col.",
"name": "col_remove_possibility",... | 4 | stack_v2_sparse_classes_30k_train_006047 | Implement the Python class `SimpleSudokuSolver` described below.
Class description:
Solve sudokus using only beginer technique.
Method signatures and docstrings:
- def row_remove_possibility(self, row: int, number: int) -> int: Remove known value from the possibilities of the row.
- def col_remove_possibility(self, c... | Implement the Python class `SimpleSudokuSolver` described below.
Class description:
Solve sudokus using only beginer technique.
Method signatures and docstrings:
- def row_remove_possibility(self, row: int, number: int) -> int: Remove known value from the possibilities of the row.
- def col_remove_possibility(self, c... | 1968afb95bda0bec6d6ca703691569822346c7ce | <|skeleton|>
class SimpleSudokuSolver:
"""Solve sudokus using only beginer technique."""
def row_remove_possibility(self, row: int, number: int) -> int:
"""Remove known value from the possibilities of the row."""
<|body_0|>
def col_remove_possibility(self, col: int, number: int) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleSudokuSolver:
"""Solve sudokus using only beginer technique."""
def row_remove_possibility(self, row: int, number: int) -> int:
"""Remove known value from the possibilities of the row."""
result = 0
for cell in self.grid[row]:
if cell.remove_possibility(number):
... | the_stack_v2_python_sparse | src/sudoku/simple_solver.py | kevna/python-exercises | train | 0 |
be68a605cf1dc715ef32b540e86230d3da4d693a | [
"if parent_name.startswith('folders'):\n return contacts.GetMessages().EssentialcontactsFoldersContactsComputeRequest.NotificationCategoriesValueValuesEnum\nif parent_name.startswith('organizations'):\n return contacts.GetMessages().EssentialcontactsOrganizationsContactsComputeRequest.NotificationCategoriesVa... | <|body_start_0|>
if parent_name.startswith('folders'):
return contacts.GetMessages().EssentialcontactsFoldersContactsComputeRequest.NotificationCategoriesValueValuesEnum
if parent_name.startswith('organizations'):
return contacts.GetMessages().EssentialcontactsOrganizationsContac... | Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any of its ancestors. ## EXAMPLES To compute contacts subscribed to the techn... | Compute | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compute:
"""Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any of its ancestors. ## EXAMPLES To compu... | stack_v2_sparse_classes_75kplus_train_070184 | 3,417 | permissive | [
{
"docstring": "Gets the NotificationCategory enum to cast the args as based on the type of parent resource arg.",
"name": "_GetNotificationCategoryEnumByParentType",
"signature": "def _GetNotificationCategoryEnumByParentType(parent_name)"
},
{
"docstring": "Adds command-specific args.",
"na... | 3 | null | Implement the Python class `Compute` described below.
Class description:
Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any... | Implement the Python class `Compute` described below.
Class description:
Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Compute:
"""Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any of its ancestors. ## EXAMPLES To compu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Compute:
"""Compute the essential contacts that are subscribed to the specified notification categories for a resource. This command will return the contacts subscribed to any of the notification categories that have been set on the requested resource or any of its ancestors. ## EXAMPLES To compute contacts s... | the_stack_v2_python_sparse | lib/surface/essential_contacts/compute.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
7cc907ffef8895ab5cfe319fa167da9ae290a35e | [
"super(GenerateSwanFilesThread, self).__init__(parent)\nself.parent = parent\nself.update_progress_signal.connect(self.update_progress)\nself.update_tableview_signal.connect(self.parent.tableview.model.layoutChanged.emit)\nself.progress_bar = self.parent.generate_progress\nself.error_signal.connect(show_thread_erro... | <|body_start_0|>
super(GenerateSwanFilesThread, self).__init__(parent)
self.parent = parent
self.update_progress_signal.connect(self.update_progress)
self.update_tableview_signal.connect(self.parent.tableview.model.layoutChanged.emit)
self.progress_bar = self.parent.generate_prog... | Thread for generating swan input files. The run method executes the generate function in the core swan class. | GenerateSwanFilesThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateSwanFilesThread:
"""Thread for generating swan input files. The run method executes the generate function in the core swan class."""
def __init__(self, parent=None):
"""Construct"""
<|body_0|>
def update_progress(self, add_value):
"""Update progress bar""... | stack_v2_sparse_classes_75kplus_train_070185 | 12,561 | no_license | [
{
"docstring": "Construct",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Update progress bar",
"name": "update_progress",
"signature": "def update_progress(self, add_value)"
},
{
"docstring": "Run import",
"name": "run",
"signature... | 3 | null | Implement the Python class `GenerateSwanFilesThread` described below.
Class description:
Thread for generating swan input files. The run method executes the generate function in the core swan class.
Method signatures and docstrings:
- def __init__(self, parent=None): Construct
- def update_progress(self, add_value): ... | Implement the Python class `GenerateSwanFilesThread` described below.
Class description:
Thread for generating swan input files. The run method executes the generate function in the core swan class.
Method signatures and docstrings:
- def __init__(self, parent=None): Construct
- def update_progress(self, add_value): ... | 2969cc0b61dc66c1a20236188cd9d85154bda48d | <|skeleton|>
class GenerateSwanFilesThread:
"""Thread for generating swan input files. The run method executes the generate function in the core swan class."""
def __init__(self, parent=None):
"""Construct"""
<|body_0|>
def update_progress(self, add_value):
"""Update progress bar""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenerateSwanFilesThread:
"""Thread for generating swan input files. The run method executes the generate function in the core swan class."""
def __init__(self, parent=None):
"""Construct"""
super(GenerateSwanFilesThread, self).__init__(parent)
self.parent = parent
self.upd... | the_stack_v2_python_sparse | hbhavens/ui/threads.py | MPBenit/HB-Havens | train | 0 |
64b52392b4c0491e895bcdf80544162cd0bfeaa9 | [
"super(Edge, self).__init__()\nself.input_model = 'rate'\nself.output_model = 'rate'",
"inputs = self.source.get_data(args)\nfoobar = lambda x: x\noutputs = foobar(inputs)\nargs = {'inputs': outputs, 'first_neuron': self.postFirst, 'last': self.postLast}\nself.target.set_data(args)"
] | <|body_start_0|>
super(Edge, self).__init__()
self.input_model = 'rate'
self.output_model = 'rate'
<|end_body_0|>
<|body_start_1|>
inputs = self.source.get_data(args)
foobar = lambda x: x
outputs = foobar(inputs)
args = {'inputs': outputs, 'first_neuron': self.po... | This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes that this edge is linking. | BrainStudioBEClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes tha... | stack_v2_sparse_classes_75kplus_train_070186 | 1,675 | no_license | [
{
"docstring": "This method acts as a constructor and is run every time an edge of this type is instantiated.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method transfers the data from the source node to the target. The data must be fetched and delivered using... | 2 | stack_v2_sparse_classes_30k_train_011413 | Implement the Python class `BrainStudioBEClass` described below.
Class description:
This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.tar... | Implement the Python class `BrainStudioBEClass` described below.
Class description:
This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.tar... | 37f18e5d652fcea9e7891b9401d3af84abc819e6 | <|skeleton|>
class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes that this edge i... | the_stack_v2_python_sparse | backend/BrainStudioBECore/Edges/EdgeTemplate.py | brainstudio-team/BrainStudio | train | 9 |
18b9f3bb3784e1cb5953e0da9a69174ed1449819 | [
"_inv_index: InvIndex\n_tokenizer: Tokenizer\n_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)\nlogging.info('Loaded inverted index')\nself._inv_index = _inv_index\nself._tokenizer = _tokenizer",
"name: str\nversion: str\ninv_index: InvIndex\ntokenizer: Tokenizer\nif not path.exists(index_path):... | <|body_start_0|>
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Loaded inverted index')
self._inv_index = _inv_index
self._tokenizer = _tokenizer
<|end_body_0|>
<|body_start_1|>
name: st... | Engine class. | Engine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_75kplus_train_070187 | 2,559 | permissive | [
{
"docstring": "Initialize the search engine.",
"name": "__init__",
"signature": "def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None"
},
{
"docstring": "Load inverted index.",
"name": "__load_inv_index",
"signature": "def __load_inv_index(self, index_path: str, dicdi... | 3 | stack_v2_sparse_classes_30k_train_005771 | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | c0a221a8038879107a5fe07d2b9452abf51815b1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Load... | the_stack_v2_python_sparse | dzo/engine.py | moriaki3193/dzo | train | 8 |
5bada078af959ee99c93ac0f73198b15065e556f | [
"token = Token.Token().get_token()\nself.log = Log.MyLog()\nself.headers = {'X-SITE-ID': '127', 'Authonrization': token}",
"try:\n response = requests.get(url=url, headers=self.headers, params=data)\nexcept requests.RequestException as e:\n self.log.error('请求异常:' + str(e) + '请求失败url' + url)\nresponse_time =... | <|body_start_0|>
token = Token.Token().get_token()
self.log = Log.MyLog()
self.headers = {'X-SITE-ID': '127', 'Authonrization': token}
<|end_body_0|>
<|body_start_1|>
try:
response = requests.get(url=url, headers=self.headers, params=data)
except requests.RequestExce... | Request | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
def __init__(self):
"""初始化日志对象,获取登录token"""
<|body_0|>
def get(self, url, data=None):
"""get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :return:"""
<|body_1|>
def post(self, url, data=None):
"""post请求封装 :data url:接口地址 :data hea... | stack_v2_sparse_classes_75kplus_train_070188 | 2,321 | no_license | [
{
"docstring": "初始化日志对象,获取登录token",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :return:",
"name": "get",
"signature": "def get(self, url, data=None)"
},
{
"docstring": "post请求封装 :data url:接口地址 ... | 3 | null | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def __init__(self): 初始化日志对象,获取登录token
- def get(self, url, data=None): get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :return:
- def post(self, url, data=None): post请求封装 ... | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def __init__(self): 初始化日志对象,获取登录token
- def get(self, url, data=None): get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :return:
- def post(self, url, data=None): post请求封装 ... | c27b7c340f2b69c5b342e829e9cc0fa23ef8eafe | <|skeleton|>
class Request:
def __init__(self):
"""初始化日志对象,获取登录token"""
<|body_0|>
def get(self, url, data=None):
"""get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :return:"""
<|body_1|>
def post(self, url, data=None):
"""post请求封装 :data url:接口地址 :data hea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Request:
def __init__(self):
"""初始化日志对象,获取登录token"""
token = Token.Token().get_token()
self.log = Log.MyLog()
self.headers = {'X-SITE-ID': '127', 'Authonrization': token}
def get(self, url, data=None):
"""get请求封装 :data url:接口地址 :data headers:请求头 :data data:请求参数 :re... | the_stack_v2_python_sparse | auto_APItest/Utils/Requests.py | lianhuabai/auto_test | train | 0 | |
62b278e698dcc63d35fb6278c98efd01e123734b | [
"exit_flag = False\nwhile not exit_flag:\n try:\n first_name, middle_name, last_name = fake.name().split(' ')\n exit_flag = True\n except ValueError:\n continue\nreturn (first_name, middle_name, last_name)",
"result = ''\nfor _ in range(n):\n result += str(random.choice(range(10)))\n... | <|body_start_0|>
exit_flag = False
while not exit_flag:
try:
first_name, middle_name, last_name = fake.name().split(' ')
exit_flag = True
except ValueError:
continue
return (first_name, middle_name, last_name)
<|end_body_0|>... | Класс утилит с доп методами | Util | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
<|body_0|>
def get_number_range(n) -> str:
"""Отдает n рандомных цифр"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
exit_flag = False
... | stack_v2_sparse_classes_75kplus_train_070189 | 11,458 | permissive | [
{
"docstring": "Генерация имени пользователя",
"name": "gen_name",
"signature": "def gen_name(fake: Faker)"
},
{
"docstring": "Отдает n рандомных цифр",
"name": "get_number_range",
"signature": "def get_number_range(n) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_000538 | Implement the Python class `Util` described below.
Class description:
Класс утилит с доп методами
Method signatures and docstrings:
- def gen_name(fake: Faker): Генерация имени пользователя
- def get_number_range(n) -> str: Отдает n рандомных цифр | Implement the Python class `Util` described below.
Class description:
Класс утилит с доп методами
Method signatures and docstrings:
- def gen_name(fake: Faker): Генерация имени пользователя
- def get_number_range(n) -> str: Отдает n рандомных цифр
<|skeleton|>
class Util:
"""Класс утилит с доп методами"""
d... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
<|body_0|>
def get_number_range(n) -> str:
"""Отдает n рандомных цифр"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
exit_flag = False
while not exit_flag:
try:
first_name, middle_name, last_name = fake.name().split(' ')
exit_flag = True
ex... | the_stack_v2_python_sparse | Course_II/Python_SQL/pract/pract3/control/control.py | GeorgiyDemo/FA | train | 46 |
be3ad784cd8c97e97ec274d958d39f6e8bdaea91 | [
"self.num_bits = num_bits\nself.num_hash_fn = num_hash_fn\nself.bits = [0] * num_bits\nself.primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\nself.hash_fns = []\nfor i in xrange(num_hash_fn):\n prime = random.choice(self.primes)\n self.primes.remove(prime)\n self.hash_fns.append(self.generate... | <|body_start_0|>
self.num_bits = num_bits
self.num_hash_fn = num_hash_fn
self.bits = [0] * num_bits
self.primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
self.hash_fns = []
for i in xrange(num_hash_fn):
prime = random.choice(self.primes)
... | Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store data. bits: list, the container for the stored data. primes: list, a list of ... | BloomFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BloomFilter:
"""Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store data. bits: list, the container for th... | stack_v2_sparse_classes_75kplus_train_070190 | 2,204 | permissive | [
{
"docstring": "Initialize a bloom filter by giving the size of the storage array. Params: num_bits: size of the internal array num_hash_fn: number of hash functions to generate to store data.",
"name": "__init__",
"signature": "def __init__(self, num_bits, num_hash_fn)"
},
{
"docstring": "Gener... | 4 | stack_v2_sparse_classes_30k_train_015182 | Implement the Python class `BloomFilter` described below.
Class description:
Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store... | Implement the Python class `BloomFilter` described below.
Class description:
Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store... | 1c5b1433c3d6bfd834df35dee08607fcbdd9f4e3 | <|skeleton|>
class BloomFilter:
"""Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store data. bits: list, the container for th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BloomFilter:
"""Models a bloom filter data structure. A bloom filter holds an array of bytes and a small set of hash functions. Attributes: num_bits: int, the size of the memory the datastructure uses. num_hash_fn: int, how many hash function to use to store data. bits: list, the container for the stored data... | the_stack_v2_python_sparse | python/algo/src/bloom_filter.py | topliceanu/learn | train | 26 |
169ad5b1a2ec6eccfdd96115c9ceab43a2a9e240 | [
"QWidget.__init__(self)\nself.setFixedHeight(150)\nself.initUI()",
"main_layout = QVBoxLayout()\nimg = QImage(':/assets/logo_100.svg')\npmap = QPixmap.fromImage(img).scaled(50, 50, Qt.KeepAspectRatio)\nlogo_label = QLabel()\nlogo_label.setPixmap(pmap)\nlogo_label.setAlignment(Qt.AlignCenter)\nlogo_label.setFixedH... | <|body_start_0|>
QWidget.__init__(self)
self.setFixedHeight(150)
self.initUI()
<|end_body_0|>
<|body_start_1|>
main_layout = QVBoxLayout()
img = QImage(':/assets/logo_100.svg')
pmap = QPixmap.fromImage(img).scaled(50, 50, Qt.KeepAspectRatio)
logo_label = QLabel()... | Class that contains the logo of the application | Logo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logo:
"""Class that contains the logo of the application"""
def __init__(self):
"""Constructor of the class"""
<|body_0|>
def initUI(self):
"""Setup the GUI elements"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
QWidget.__init__(self)
... | stack_v2_sparse_classes_75kplus_train_070191 | 1,911 | no_license | [
{
"docstring": "Constructor of the class",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Setup the GUI elements",
"name": "initUI",
"signature": "def initUI(self)"
}
] | 2 | null | Implement the Python class `Logo` described below.
Class description:
Class that contains the logo of the application
Method signatures and docstrings:
- def __init__(self): Constructor of the class
- def initUI(self): Setup the GUI elements | Implement the Python class `Logo` described below.
Class description:
Class that contains the logo of the application
Method signatures and docstrings:
- def __init__(self): Constructor of the class
- def initUI(self): Setup the GUI elements
<|skeleton|>
class Logo:
"""Class that contains the logo of the applica... | a6e40f9778284426a15c05ef362dde243e687888 | <|skeleton|>
class Logo:
"""Class that contains the logo of the application"""
def __init__(self):
"""Constructor of the class"""
<|body_0|>
def initUI(self):
"""Setup the GUI elements"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logo:
"""Class that contains the logo of the application"""
def __init__(self):
"""Constructor of the class"""
QWidget.__init__(self)
self.setFixedHeight(150)
self.initUI()
def initUI(self):
"""Setup the GUI elements"""
main_layout = QVBoxLayout()
... | the_stack_v2_python_sparse | behavior_studio/ui/gui/views/logo.py | dcharrezt/BehaviorStudio | train | 0 |
368f3d65b3dcbbfb9b9ff08b82a8748cb8826381 | [
"super().setUp()\nself.login(self.CURRICULUM_ADMIN_EMAIL, is_super_admin=True)\ncsrf_token = self.get_new_csrf_token()\nself.post_json('/adminhandler', {'action': 'reload_exploration', 'exploration_id': '3'}, csrf_token=csrf_token)\nself.logout()",
"library_groups = summary_services.get_library_groups([])\nexpect... | <|body_start_0|>
super().setUp()
self.login(self.CURRICULUM_ADMIN_EMAIL, is_super_admin=True)
csrf_token = self.get_new_csrf_token()
self.post_json('/adminhandler', {'action': 'reload_exploration', 'exploration_id': '3'}, csrf_token=csrf_token)
self.logout()
<|end_body_0|>
<|bod... | Test functions for getting summary dicts for library groups. | LibraryGroupsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryGroupsTest:
"""Test functions for getting summary dicts for library groups."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration ... | stack_v2_sparse_classes_75kplus_train_070192 | 47,358 | permissive | [
{
"docstring": "Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration with id '3'. - (4) Admin logs out.",
"name": "setUp",
"signature": "def setUp(self) -> None"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_050801 | Implement the Python class `LibraryGroupsTest` described below.
Class description:
Test functions for getting summary dicts for library groups.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) ... | Implement the Python class `LibraryGroupsTest` described below.
Class description:
Test functions for getting summary dicts for library groups.
Method signatures and docstrings:
- def setUp(self) -> None: Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) ... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class LibraryGroupsTest:
"""Test functions for getting summary dicts for library groups."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryGroupsTest:
"""Test functions for getting summary dicts for library groups."""
def setUp(self) -> None:
"""Populate the database of explorations and their summaries. The sequence of events is: - (1) Admin logs in. - (2) Admin access admin page. - (3) Admin reloads exploration with id '3'. ... | the_stack_v2_python_sparse | core/domain/summary_services_test.py | oppia/oppia | train | 6,172 |
eeb7e1ad29fdea677afb0d384184dcee2c69d095 | [
"headers = []\nfor field in self.get_fields():\n field_name = field.column_name.split('__')[0]\n try:\n f = self.Meta.model._meta.get_field(field_name)\n except FieldDoesNotExist:\n headers.append(ugettext(field.column_name))\n else:\n headers.append(ugettext(f.verbose_name))\nretur... | <|body_start_0|>
headers = []
for field in self.get_fields():
field_name = field.column_name.split('__')[0]
try:
f = self.Meta.model._meta.get_field(field_name)
except FieldDoesNotExist:
headers.append(ugettext(field.column_name))
... | Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-import-export/issues/52 | FriendlyExportMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendlyExportMixin:
"""Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-import-export/issues/52"""
def get... | stack_v2_sparse_classes_75kplus_train_070193 | 1,535 | no_license | [
{
"docstring": "Return column headers based on verbose_name.",
"name": "get_export_headers",
"signature": "def get_export_headers(self)"
},
{
"docstring": "Use get_XXX_display when exporting fields that support it.",
"name": "export_field",
"signature": "def export_field(self, field, obj... | 2 | stack_v2_sparse_classes_30k_test_002404 | Implement the Python class `FriendlyExportMixin` described below.
Class description:
Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-... | Implement the Python class `FriendlyExportMixin` described below.
Class description:
Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-... | 28b91b582616c27c241460d456378c4e0a690771 | <|skeleton|>
class FriendlyExportMixin:
"""Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-import-export/issues/52"""
def get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FriendlyExportMixin:
"""Mixin for "friendlier" output when exporting models. It uses verbose names in column headers and get_XXX_display for values that support it. Might cause trouble when importing data back. https://github.com/django-import-export/django-import-export/issues/52"""
def get_export_heade... | the_stack_v2_python_sparse | utils/resources.py | jerivas/campmanager | train | 0 |
750d24eab80c9c45669671e6f463bfee0b0caa0b | [
"for _ in range(self.n_retries):\n try:\n r = requests.get(url)\n pathlib.Path(data_folder).mkdir(parents=True, exist_ok=True)\n open(os.path.join(data_folder, filename), 'wb').write(r.content)\n break\n except urllib.error.URLError:\n print(f'Download of {url} failed; wait ... | <|body_start_0|>
for _ in range(self.n_retries):
try:
r = requests.get(url)
pathlib.Path(data_folder).mkdir(parents=True, exist_ok=True)
open(os.path.join(data_folder, filename), 'wb').write(r.content)
break
except urllib.er... | This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all classes/groups. | WorstCase | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all cl... | stack_v2_sparse_classes_75kplus_train_070194 | 7,265 | permissive | [
{
"docstring": "Method to download the data given its' url, and the desired folder to stor int",
"name": "download",
"signature": "def download(self, url, data_folder, filename, md5)"
},
{
"docstring": "Calls the download method to download the cleaned labels from [3], as well as superclasses us... | 4 | stack_v2_sparse_classes_30k_train_004791 | Implement the Python class `WorstCase` described below.
Class description:
This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifie... | Implement the Python class `WorstCase` described below.
Class description:
This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifie... | 74b3cda69a2b90bcefed3848faca41a92ad0c9bf | <|skeleton|>
class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorstCase:
"""This task evaluates a set of metrics, mostly related to worst-class performance, as described in [1]. It is motivated by [2], where the authors note that using only accuracy as a metric is not enough to evaluate the performance of the classifier, as it must not be the same on all classes/groups.... | the_stack_v2_python_sparse | shifthappens/tasks/worst_case/worst_case.py | shift-happens-benchmark/icml-2022 | train | 39 |
3b6dd19f6d0ad43bf8fe62e84f348525992328b5 | [
"sum = 0\nres = []\nfor i in nums:\n if i == 1:\n sum += 1\n else:\n res.append(sum)\n sum = 0\n res.append(sum)\nreturn max(res)",
"sum = 0\nres = 0\nfor i in nums:\n if i == 1:\n sum += 1\n else:\n res = max(res, sum)\n sum = 0\n res = max(res, sum)\nr... | <|body_start_0|>
sum = 0
res = []
for i in nums:
if i == 1:
sum += 1
else:
res.append(sum)
sum = 0
res.append(sum)
return max(res)
<|end_body_0|>
<|body_start_1|>
sum = 0
res = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sum = 0
res = []
for i... | stack_v2_sparse_classes_75kplus_train_070195 | 1,088 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMaxConsecutiveOnes",
"signature": "def findMaxConsecutiveOnes(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMax",
"signature": "def findMax(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026894 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): :type nums: List[int] :rtype: int
- def findMax(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): :type nums: List[int] :rtype: int
- def findMax(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def find... | 1040b5dbbe509abe42df848bc34dd1626d7a05fb | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
sum = 0
res = []
for i in nums:
if i == 1:
sum += 1
else:
res.append(sum)
sum = 0
res.append(sum)
... | the_stack_v2_python_sparse | list/findMaxConsecutiveOnes.py | NJ-zero/LeetCode_Answer | train | 1 | |
af553b1a01357c7a48d6cc1a4194709b84a76368 | [
"Exception.__init__(self, message)\nif ret is not None:\n code = ret.status_code\n try:\n js = ret.json()\n except Exception as e:\n js = str(e) + '\\n' + str(ret)\n self.ret = (code, js, ret)\nelse:\n self.ret = (None, None)",
"s = Exception.__str__(self)\nf = 'STATUS: {0}, JSON: {1}... | <|body_start_0|>
Exception.__init__(self, message)
if ret is not None:
code = ret.status_code
try:
js = ret.json()
except Exception as e:
js = str(e) + '\n' + str(ret)
self.ret = (code, js, ret)
else:
sel... | exception raised by @see cl AzureClient | AzureException | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureException:
"""exception raised by @see cl AzureClient"""
def __init__(self, message, ret):
"""store more information than a regular exception @param message error message @param ret results of the requests"""
<|body_0|>
def __str__(self):
"""usual"""
... | stack_v2_sparse_classes_75kplus_train_070196 | 971 | permissive | [
{
"docstring": "store more information than a regular exception @param message error message @param ret results of the requests",
"name": "__init__",
"signature": "def __init__(self, message, ret)"
},
{
"docstring": "usual",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017395 | Implement the Python class `AzureException` described below.
Class description:
exception raised by @see cl AzureClient
Method signatures and docstrings:
- def __init__(self, message, ret): store more information than a regular exception @param message error message @param ret results of the requests
- def __str__(se... | Implement the Python class `AzureException` described below.
Class description:
exception raised by @see cl AzureClient
Method signatures and docstrings:
- def __init__(self, message, ret): store more information than a regular exception @param message error message @param ret results of the requests
- def __str__(se... | 10b0f6c99c79ef0264e10ddd9f8df1f3cbaa2139 | <|skeleton|>
class AzureException:
"""exception raised by @see cl AzureClient"""
def __init__(self, message, ret):
"""store more information than a regular exception @param message error message @param ret results of the requests"""
<|body_0|>
def __str__(self):
"""usual"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AzureException:
"""exception raised by @see cl AzureClient"""
def __init__(self, message, ret):
"""store more information than a regular exception @param message error message @param ret results of the requests"""
Exception.__init__(self, message)
if ret is not None:
c... | the_stack_v2_python_sparse | src/pyenbc/remote/azure_exception.py | sdpython/pyenbc | train | 0 |
42ea35ecc815d28fdee25c237820881c55996441 | [
"if value is not None and isinstance(value, Enum):\n return value.name\nreturn str(value)",
"if isinstance(value, Enum):\n return value\nfor name, member in kwargs.get('enum').__members__.items():\n if name == value or member.value == value:\n return member\nraise TypeError('{} does not match enum... | <|body_start_0|>
if value is not None and isinstance(value, Enum):
return value.name
return str(value)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, Enum):
return value
for name, member in kwargs.get('enum').__members__.items():
if name == valu... | SelectType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to select Keyword Args: enum (Enum): Enumeration type"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_070197 | 901 | no_license | [
{
"docstring": "Convert a value to a JSON serializable value",
"name": "serialize",
"signature": "def serialize(value, **kwargs)"
},
{
"docstring": "Convert value to select Keyword Args: enum (Enum): Enumeration type",
"name": "deserialize",
"signature": "def deserialize(value, **kwargs)... | 2 | null | Implement the Python class `SelectType` described below.
Class description:
Implement the SelectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to select Keyword Args: enum (Enum): Enumeratio... | Implement the Python class `SelectType` described below.
Class description:
Implement the SelectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to select Keyword Args: enum (Enum): Enumeratio... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class SelectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to select Keyword Args: enum (Enum): Enumeration type"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
if value is not None and isinstance(value, Enum):
return value.name
return str(value)
def deserialize(value, **kwargs):
"""Convert value to select Keyword Args: enum ... | the_stack_v2_python_sparse | nio/types/select.py | niolabs/nio | train | 5 | |
ad10a6b19597963f86834e618fa4dd179df85216 | [
"connection = client_object.connection\ncommand = 'get certificate api thumbprint'\npylogger.debug('Command to get manager thumbprint %s' % command)\nexpect_prompt = ['bytes*', '>']\nresult = connection.request(command, expect_prompt)\nstdout_lines = result.response_data.splitlines()\nthumbprint_index_in_output = 0... | <|body_start_0|>
connection = client_object.connection
command = 'get certificate api thumbprint'
pylogger.debug('Command to get manager thumbprint %s' % command)
expect_prompt = ['bytes*', '>']
result = connection.request(command, expect_prompt)
stdout_lines = result.res... | NSX70CRUDImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSX70CRUDImpl:
def get_manager_thumbprint(cls, client_object):
"""Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager> show api certificate thumbprint f71250ab638c9939a91b0db1b89619a43a9cda44a2c8628167ce5327d44bd16f nim... | stack_v2_sparse_classes_75kplus_train_070198 | 2,819 | no_license | [
{
"docstring": "Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager> show api certificate thumbprint f71250ab638c9939a91b0db1b89619a43a9cda44a2c8628167ce5327d44bd16f nimbus-cloud-nsxmanager>",
"name": "get_manager_thumbprint",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_012878 | Implement the Python class `NSX70CRUDImpl` described below.
Class description:
Implement the NSX70CRUDImpl class.
Method signatures and docstrings:
- def get_manager_thumbprint(cls, client_object): Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager... | Implement the Python class `NSX70CRUDImpl` described below.
Class description:
Implement the NSX70CRUDImpl class.
Method signatures and docstrings:
- def get_manager_thumbprint(cls, client_object): Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class NSX70CRUDImpl:
def get_manager_thumbprint(cls, client_object):
"""Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager> show api certificate thumbprint f71250ab638c9939a91b0db1b89619a43a9cda44a2c8628167ce5327d44bd16f nim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NSX70CRUDImpl:
def get_manager_thumbprint(cls, client_object):
"""Method to NSX manager thumbprint Sample output of the command 'show api certificate thumbprint': nimbus-cloud-nsxmanager> show api certificate thumbprint f71250ab638c9939a91b0db1b89619a43a9cda44a2c8628167ce5327d44bd16f nimbus-cloud-nsxm... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/nsx/manager/cli/nsx70_crud_impl.py | Cloudxtreme/MyProject | train | 0 | |
ac7070f701a0cfa5199b92e0e333614fb76fcec2 | [
"data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}\nresponse = self.client.post('/1.0/posts/', data)\nself.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)",
"self.client.login(username=self.user.username, password=s... | <|body_start_0|>
data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}
response = self.client.post('/1.0/posts/', data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
<|end_body_0|>
<|body_start... | PostCreateAPITest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostCreateAPITest:
def test_user_must_be_authenticated(self):
"""Ensures that the user must be authenticated to create a post"""
<|body_0|>
def test_post_must_be_in_user_blog(self):
"""Ensures that a post is published in the authenticated user's blog"""
<|bod... | stack_v2_sparse_classes_75kplus_train_070199 | 20,627 | no_license | [
{
"docstring": "Ensures that the user must be authenticated to create a post",
"name": "test_user_must_be_authenticated",
"signature": "def test_user_must_be_authenticated(self)"
},
{
"docstring": "Ensures that a post is published in the authenticated user's blog",
"name": "test_post_must_be... | 2 | stack_v2_sparse_classes_30k_train_018781 | Implement the Python class `PostCreateAPITest` described below.
Class description:
Implement the PostCreateAPITest class.
Method signatures and docstrings:
- def test_user_must_be_authenticated(self): Ensures that the user must be authenticated to create a post
- def test_post_must_be_in_user_blog(self): Ensures that... | Implement the Python class `PostCreateAPITest` described below.
Class description:
Implement the PostCreateAPITest class.
Method signatures and docstrings:
- def test_user_must_be_authenticated(self): Ensures that the user must be authenticated to create a post
- def test_post_must_be_in_user_blog(self): Ensures that... | 56bfe19853bfec4581870a0075d0f21ee4d4bfda | <|skeleton|>
class PostCreateAPITest:
def test_user_must_be_authenticated(self):
"""Ensures that the user must be authenticated to create a post"""
<|body_0|>
def test_post_must_be_in_user_blog(self):
"""Ensures that a post is published in the authenticated user's blog"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostCreateAPITest:
def test_user_must_be_authenticated(self):
"""Ensures that the user must be authenticated to create a post"""
data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}
response = self.clien... | the_stack_v2_python_sparse | blogs/tests.py | dmpinero/practica_Python_Django_Avanzado | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.