blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([albert_layer.attention.query.weight, albert_layer.attention.key.weight, albert_layer.attention.value.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([albert_layer.attention.query.bias, albert_layer.attention.key.bias, albert_layer.attent... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([albert_layer.attention.query.weight, albert_layer.attention.key.weight, albert_layer.attention.value.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([albert_layer.attention.query.bias, albert_layer.atten... | AlbertLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbertLayerBetterTransformer:
def __init__(self, albert_layer, config):
"""A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_layer (`torch.nn.Module`): The original ALBERT Layer where the weights needs to be retrieved."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001900 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_layer (`torch.nn.Module`): The original ALBERT Layer where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, albert_layer, config)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_004094 | Implement the Python class `AlbertLayerBetterTransformer` described below.
Class description:
Implement the AlbertLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, albert_layer, config): A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_... | Implement the Python class `AlbertLayerBetterTransformer` described below.
Class description:
Implement the AlbertLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, albert_layer, config): A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class AlbertLayerBetterTransformer:
def __init__(self, albert_layer, config):
"""A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_layer (`torch.nn.Module`): The original ALBERT Layer where the weights needs to be retrieved."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlbertLayerBetterTransformer:
def __init__(self, albert_layer, config):
"""A simple conversion of the ALBERT layer to its `BetterTransformer` implementation. Args: albert_layer (`torch.nn.Module`): The original ALBERT Layer where the weights needs to be retrieved."""
super().__init__(config)
... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
d9b0933561881e6b13c2e17cd335a6cd4338af21 | [
"super(ContentMetadata, self).__init__(auth)\nself.id = testXMLValue(elem.find(nspath('Name')))\nself.title = testXMLValue(elem.find(nspath('Title')))\nself.abstract = testXMLValue(elem.find(nspath('Abstract')))\nself.keywords = [f.text for f in elem.findall(nspath('Keywords'))]\nself.boundingBox = None\nb = elem.f... | <|body_start_0|>
super(ContentMetadata, self).__init__(auth)
self.id = testXMLValue(elem.find(nspath('Name')))
self.title = testXMLValue(elem.find(nspath('Title')))
self.abstract = testXMLValue(elem.find(nspath('Abstract')))
self.keywords = [f.text for f in elem.findall(nspath('K... | Abstraction for WFS metadata. Implements IMetadata. | ContentMetadata | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None):
"""."""
<|body_0|>
def parse_remote_metadata(self, timeout=30):
"""Parse remote metadata for MetadataU... | stack_v2_sparse_classes_10k_train_001901 | 16,493 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None)"
},
{
"docstring": "Parse remote metadata for MetadataURL of format 'XML' and add it as metadataUrl['metadata']",
"name": "parse_remote_metadata",
"s... | 2 | stack_v2_sparse_classes_30k_train_007276 | Implement the Python class `ContentMetadata` described below.
Class description:
Abstraction for WFS metadata. Implements IMetadata.
Method signatures and docstrings:
- def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None): .
- def parse_remote_metadata(self, timeout=30): Parse remote m... | Implement the Python class `ContentMetadata` described below.
Class description:
Abstraction for WFS metadata. Implements IMetadata.
Method signatures and docstrings:
- def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None): .
- def parse_remote_metadata(self, timeout=30): Parse remote m... | 94b68c3a497978404edf486140138e4b9e340aba | <|skeleton|>
class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None):
"""."""
<|body_0|>
def parse_remote_metadata(self, timeout=30):
"""Parse remote metadata for MetadataU... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parent, parse_remote_metadata=False, timeout=30, auth=None):
"""."""
super(ContentMetadata, self).__init__(auth)
self.id = testXMLValue(elem.find(nspath('Name')))
self.title... | the_stack_v2_python_sparse | owslib/feature/wfs100.py | bird-house/OWSLib | train | 2 |
211e74285c92d6c731fea774cb7f83a564920a4a | [
"try:\n request_line = (yield from parse_line(read_line))\nexcept EOFError as exc:\n raise EOFError('connection closed while reading HTTP request line') from exc\ntry:\n method, raw_path, version = request_line.split(b' ', 2)\nexcept ValueError:\n raise ValueError(f'invalid HTTP request line: {d(request... | <|body_start_0|>
try:
request_line = (yield from parse_line(read_line))
except EOFError as exc:
raise EOFError('connection closed while reading HTTP request line') from exc
try:
method, raw_path, version = request_line.split(b' ', 2)
except ValueError:... | WebSocket handshake request. :param path: path and optional query :param headers: | Request | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't ... | stack_v2_sparse_classes_10k_train_001902 | 10,688 | permissive | [
{
"docstring": "Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't URL-decoded or validated in any way. ``path`` and ``headers`` are expected to contain only ASCII characters. Other characters are represented with surrogate escapes. :func:`parse_request` doesn't attempt to read the req... | 2 | stack_v2_sparse_classes_30k_train_000623 | Implement the Python class `Request` described below.
Class description:
WebSocket handshake request. :param path: path and optional query :param headers:
Method signatures and docstrings:
- def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']: Parse an HTTP/1.1 GE... | Implement the Python class `Request` described below.
Class description:
WebSocket handshake request. :param path: path and optional query :param headers:
Method signatures and docstrings:
- def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']: Parse an HTTP/1.1 GE... | 6b8d8cf9622eadef47bd10690c1bf1e7fd892bfd | <|skeleton|>
class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't URL-decoded o... | the_stack_v2_python_sparse | env/lib/python3.8/site-packages/websockets/http11.py | EtienneBrJ/Portfolio | train | 1 |
d59704128656e8a2f7539c3eabae5c763395e213 | [
"if model._meta.app_label == 'syncwerk_ccnet_models':\n return 'ccnet'\nreturn None",
"if model._meta.app_label == 'syncwerk_ccnet_models':\n return 'ccnet'\nreturn None",
"if obj1._meta.app_label == 'syncwerk_ccnet_models' or obj2._meta.app_label == 'syncwerk_ccnet_models':\n return True\nreturn None"... | <|body_start_0|>
if model._meta.app_label == 'syncwerk_ccnet_models':
return 'ccnet'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'syncwerk_ccnet_models':
return 'ccnet'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta... | A router to control all database operations on models related to ccnet | SyncwerkCcnetModelsRouter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncwerkCcnetModelsRouter:
"""A router to control all database operations on models related to ccnet"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet'"""
<|body_0|>
def db_for_write(self, model... | stack_v2_sparse_classes_10k_train_001903 | 1,265 | permissive | [
{
"docstring": "Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet'",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all operations on syncwerk_ccnet_models models to 'ccnet'",
"name": "db_for_write",
"s... | 4 | null | Implement the Python class `SyncwerkCcnetModelsRouter` described below.
Class description:
A router to control all database operations on models related to ccnet
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet... | Implement the Python class `SyncwerkCcnetModelsRouter` described below.
Class description:
A router to control all database operations on models related to ccnet
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet... | 13b3ed26a04248211ef91ca70dccc617be27a3c3 | <|skeleton|>
class SyncwerkCcnetModelsRouter:
"""A router to control all database operations on models related to ccnet"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet'"""
<|body_0|>
def db_for_write(self, model... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyncwerkCcnetModelsRouter:
"""A router to control all database operations on models related to ccnet"""
def db_for_read(self, model, **hints):
"""Point all operations which has app_label='syncwerk_ccnet_models' models to 'ccnet'"""
if model._meta.app_label == 'syncwerk_ccnet_models':
... | the_stack_v2_python_sparse | fhs/usr/share/python/syncwerk/restapi/restapi/syncwerk_ccnet_models/routers.py | syncwerk/syncwerk-server-restapi | train | 0 |
00caa4a1925c26b087b2375c382d02818aa00af0 | [
"translatable_content_ids = exploration.get_translatable_content_ids()\nupdated_suggestions = []\nfor suggestion in suggestions:\n if suggestion.change_cmd['content_id'] in translatable_content_ids:\n continue\n suggestion.status = suggestion_models.STATUS_REJECTED\n suggestion.final_reviewer_id = f... | <|body_start_0|>
translatable_content_ids = exploration.get_translatable_content_ids()
updated_suggestions = []
for suggestion in suggestions:
if suggestion.change_cmd['content_id'] in translatable_content_ids:
continue
suggestion.status = suggestion_model... | Job that rejects translation suggestions with missing content ids. | RejectTranslationSuggestionsWithMissingContentIdJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSu... | stack_v2_sparse_classes_10k_train_001904 | 11,707 | permissive | [
{
"docstring": "Marks translation suggestion models as 'rejected' if the content ID for the suggestion no longer exists. The final_reviewer_id will be set to feconf.SUGGESTION_BOT_USER_ID. Args: suggestions: list(GeneralSuggestionModel). A list of translation suggestion models corresponding to the given explora... | 2 | stack_v2_sparse_classes_30k_train_001608 | Implement the Python class `RejectTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Job that rejects translation suggestions with missing content ids.
Method signatures and docstrings:
- def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], expl... | Implement the Python class `RejectTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Job that rejects translation suggestions with missing content ids.
Method signatures and docstrings:
- def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], expl... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RejectTranslationSuggestionsWithMissingContentIdJob:
"""Job that rejects translation suggestions with missing content ids."""
def _reject_obsolete_suggestions(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[suggestion_models.GeneralSuggestionModel... | the_stack_v2_python_sparse | core/jobs/batch_jobs/rejecting_suggestion_for_invalid_content_ids_jobs.py | oppia/oppia | train | 6,172 |
bca5312e2d829af609e673de5447a2eee714d989 | [
"d = {}\nfor i in nums:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\nx = d.get(0, 0)\ny = d.get(1, 0)\nz = d.get(2, 0)\nnums[:x] = [0] * x\nnums[x:x + y] = [1] * y\nnums[x + y:] = [2] * z",
"start = 0\nend = len(nums) - 1\ni = 0\nwhile i <= end:\n if nums[i] == 0:\n nums[start], nums... | <|body_start_0|>
d = {}
for i in nums:
if i in d:
d[i] += 1
else:
d[i] = 1
x = d.get(0, 0)
y = d.get(1, 0)
z = d.get(2, 0)
nums[:x] = [0] * x
nums[x:x + y] = [1] * y
nums[x + y:] = [2] * z
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通"""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.... | stack_v2_sparse_classes_10k_train_001905 | 1,037 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 进阶",
"name... | 2 | stack_v2_sparse_classes_30k_train_004070 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通
- def sortColors2(self, nums): :type nums: List[int] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通
- def sortColors2(self, nums): :type nums: List[int] :rtyp... | 624975f767f6efa1d7361cc077eaebc344d57210 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通"""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. 普通"""
d = {}
for i in nums:
if i in d:
d[i] += 1
else:
d[i] = 1
x = d.get(0, 0)
y = ... | the_stack_v2_python_sparse | 75. 分类颜色.py | dx19910707/LeetCode | train | 0 | |
264b500238e2e0aa50fbf23ec1a26dff5741e31c | [
"self.detener = False\nself.tira = tira\nself.jpg = jpg\nself.pasos = pasos\nself.nuevo_pct_fila = nuevo_pct_fila\nself.tiempo_s = tiempo_s",
"if self.detener:\n return\nwhile self.nuevo_pct_fila > 100.0:\n self.nuevo_pct_fila -= 100.0\nself.tira.poner_imagen(self.jpg, self.pasos, self.nuevo_pct_fila, self.... | <|body_start_0|>
self.detener = False
self.tira = tira
self.jpg = jpg
self.pasos = pasos
self.nuevo_pct_fila = nuevo_pct_fila
self.tiempo_s = tiempo_s
<|end_body_0|>
<|body_start_1|>
if self.detener:
return
while self.nuevo_pct_fila > 100.0:
... | Siguiente iteracion de la imagen. | Siguiente | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Siguiente:
"""Siguiente iteracion de la imagen."""
def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s):
"""Siguiente iteracion de la imagen. Guarda referencia a todos los valores."""
<|body_0|>
def f(self):
"""Poner la siguiente imagen."""
<|bo... | stack_v2_sparse_classes_10k_train_001906 | 12,576 | no_license | [
{
"docstring": "Siguiente iteracion de la imagen. Guarda referencia a todos los valores.",
"name": "__init__",
"signature": "def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s)"
},
{
"docstring": "Poner la siguiente imagen.",
"name": "f",
"signature": "def f(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005964 | Implement the Python class `Siguiente` described below.
Class description:
Siguiente iteracion de la imagen.
Method signatures and docstrings:
- def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s): Siguiente iteracion de la imagen. Guarda referencia a todos los valores.
- def f(self): Poner la siguiente im... | Implement the Python class `Siguiente` described below.
Class description:
Siguiente iteracion de la imagen.
Method signatures and docstrings:
- def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s): Siguiente iteracion de la imagen. Guarda referencia a todos los valores.
- def f(self): Poner la siguiente im... | 8c62f28b9b4af3f609ae88c7ffa22fef45b99c24 | <|skeleton|>
class Siguiente:
"""Siguiente iteracion de la imagen."""
def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s):
"""Siguiente iteracion de la imagen. Guarda referencia a todos los valores."""
<|body_0|>
def f(self):
"""Poner la siguiente imagen."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Siguiente:
"""Siguiente iteracion de la imagen."""
def __init__(self, tira, jpg, pasos, nuevo_pct_fila, tiempo_s):
"""Siguiente iteracion de la imagen. Guarda referencia a todos los valores."""
self.detener = False
self.tira = tira
self.jpg = jpg
self.pasos = pasos... | the_stack_v2_python_sparse | tira.py | antonio-fiol/tren | train | 0 |
5bdcace672df14724c42ef88461bdc91041be62e | [
"self.lexicon = lexicon\nL_inv = self.lexicon.L_inv.to(device)\nif L_inv.properties & k2.fsa_properties.ARC_SORTED != 0:\n L_inv = k2.arc_sort(L_inv)\nassert L_inv.requires_grad is False\nassert oov in self.lexicon.words\nself.L_inv = L_inv\nself.oov_id = self.lexicon.words[oov]\nself.oov = oov\nself.device = de... | <|body_start_0|>
self.lexicon = lexicon
L_inv = self.lexicon.L_inv.to(device)
if L_inv.properties & k2.fsa_properties.ARC_SORTED != 0:
L_inv = k2.arc_sort(L_inv)
assert L_inv.requires_grad is False
assert oov in self.lexicon.words
self.L_inv = L_inv
se... | MmiTrainingGraphCompiler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MmiTrainingGraphCompiler:
def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'):
"""Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001907 | 6,137 | permissive | [
{
"docstring": "Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word.",
"name": "__init__",
"signature": "def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>')"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_005440 | Implement the Python class `MmiTrainingGraphCompiler` described below.
Class description:
Implement the MmiTrainingGraphCompiler class.
Method signatures and docstrings:
- def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): Args: L_inv: Its labels are words, while its aux_labels are phones. ... | Implement the Python class `MmiTrainingGraphCompiler` described below.
Class description:
Implement the MmiTrainingGraphCompiler class.
Method signatures and docstrings:
- def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): Args: L_inv: Its labels are words, while its aux_labels are phones. ... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class MmiTrainingGraphCompiler:
def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'):
"""Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MmiTrainingGraphCompiler:
def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'):
"""Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word."""
self.lexicon = lexicon
... | the_stack_v2_python_sparse | snowfall/training/mmi_graph.py | csukuangfj/snowfall | train | 0 | |
c6d5278b72b661cdcd4e1d5b0c8413faaaadb86d | [
"def hashURL():\n code = ''\n tmp = ''\n for i in range(6):\n tmp = letters[random.randint(0, 10000) % 62]\n code = code + tmp\n return code\nprefix = 'http://tinyurl.com/'\nif longUrl in long_short:\n return prefix + long_short[longUrl]\nelse:\n suffix = hashURL()\n long_short[lo... | <|body_start_0|>
def hashURL():
code = ''
tmp = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
code = code + tmp
return code
prefix = 'http://tinyurl.com/'
if longUrl in long_short:
re... | 如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。 | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。"""
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL ... | stack_v2_sparse_classes_10k_train_001908 | 1,624 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | null | Implement the Python class `Codec` described below.
Class description:
如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Dec... | Implement the Python class `Codec` described below.
Class description:
如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Dec... | 034efcefe9940267abcf4c9cab655b2344e3e901 | <|skeleton|>
class Codec:
"""如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。"""
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。"""
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
def hashURL():
code = ''
tmp = ''
for i in range(6):
... | the_stack_v2_python_sparse | 535_encode_and_decode_tinyURL.py | HongsenHe/algo2018 | train | 0 |
0a76dda96da294e4b6a991576766591671bb12ed | [
"self.snmp_object = snmp_object\ntest_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'\nsuper().__init__(snmp_object, test_oid, tags=['layer1'])",
"final = defaultdict(lambda: defaultdict(dict))\nvalues = self.cviroutedvlanifindex()\nfor key, value in values.items():\n final[key]['cviRoutedVlanIfIndex'] = value\nreturn ... | <|body_start_0|>
self.snmp_object = snmp_object
test_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'
super().__init__(snmp_object, test_oid, tags=['layer1'])
<|end_body_0|>
<|body_start_1|>
final = defaultdict(lambda: defaultdict(dict))
values = self.cviroutedvlanifindex()
for ke... | Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if not. layer1: Returns all needed layer 1 MIB inf... | CiscoVlanIftableRelationshipQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_10k_train_001909 | 2,856 | permissive | [
{
"docstring": "Function for intializing the class. Args: snmp_object: SNMP Interact class object from snmp_manager.py Returns: None",
"name": "__init__",
"signature": "def __init__(self, snmp_object)"
},
{
"docstring": "Get layer 1 data from device. Args: None Returns: final: Final results",
... | 3 | stack_v2_sparse_classes_30k_train_004217 | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if... | the_stack_v2_python_sparse | switchmap/snmp/cisco/mib_ciscovlaniftablerelationship.py | PalisadoesFoundation/switchmap-ng | train | 8 |
4199eda2ca0aa78dc913b9ede078bd66d3296303 | [
"if not root:\n return 0\np_list, num = ([root], 1)\nwhile True:\n c_list = list()\n for i in p_list:\n if not i.left and (not i.right):\n return num\n if i.left:\n c_list.append(i.left)\n if i.right:\n c_list.append(i.right)\n num += 1\n p_list =... | <|body_start_0|>
if not root:
return 0
p_list, num = ([root], 1)
while True:
c_list = list()
for i in p_list:
if not i.left and (not i.right):
return num
if i.left:
c_list.append(i.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
<|body_0|>
def minDepthDfs(self, root: TreeNode) -> int:
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
p_list, num = ([root], 1)
... | stack_v2_sparse_classes_10k_train_001910 | 3,231 | no_license | [
{
"docstring": "BFS",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "DFS",
"name": "minDepthDfs",
"signature": "def minDepthDfs(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_003047 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: BFS
- def minDepthDfs(self, root: TreeNode) -> int: DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: BFS
- def minDepthDfs(self, root: TreeNode) -> int: DFS
<|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
... | d265eb981a7586d46d0ced3accc2ea186dc7691c | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
<|body_0|>
def minDepthDfs(self, root: TreeNode) -> int:
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
if not root:
return 0
p_list, num = ([root], 1)
while True:
c_list = list()
for i in p_list:
if not i.left and (not i.right):
return num
... | the_stack_v2_python_sparse | pythonCode/No101-150/no111.py | odinfor/leetcode | train | 0 | |
7a52729afd66878cf5bb3d80fb169202e724bcef | [
"self.s = s\nself.t = t\nself.dict = {}\nself.m = len(s)\nself.n = len(t)\n\ndef dfs(i, j):\n if j >= self.n:\n return 1\n if i >= self.m:\n return 0\n if (i, j) in self.dict:\n return self.dict[i, j]\n if self.s[i] == self.t[j]:\n a = dfs(i + 1, j) + dfs(i + 1, j + 1)\n e... | <|body_start_0|>
self.s = s
self.t = t
self.dict = {}
self.m = len(s)
self.n = len(t)
def dfs(i, j):
if j >= self.n:
return 1
if i >= self.m:
return 0
if (i, j) in self.dict:
return self.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
<|body_0|>
def numDistinct_1(self, s, t):
""":type s: str :type t: str :rtype: int 252ms"""
<|body_1|>
def numDistinct_2(self, s, t):
""":type s: str :type t: str ... | stack_v2_sparse_classes_10k_train_001911 | 14,277 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: int",
"name": "numDistinct",
"signature": "def numDistinct(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: int 252ms",
"name": "numDistinct_1",
"signature": "def numDistinct_1(self, s, t)"
},
{
"docstring": ":typ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDistinct(self, s, t): :type s: str :type t: str :rtype: int
- def numDistinct_1(self, s, t): :type s: str :type t: str :rtype: int 252ms
- def numDistinct_2(self, s, t): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDistinct(self, s, t): :type s: str :type t: str :rtype: int
- def numDistinct_1(self, s, t): :type s: str :type t: str :rtype: int 252ms
- def numDistinct_2(self, s, t): :... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
<|body_0|>
def numDistinct_1(self, s, t):
""":type s: str :type t: str :rtype: int 252ms"""
<|body_1|>
def numDistinct_2(self, s, t):
""":type s: str :type t: str ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numDistinct(self, s, t):
""":type s: str :type t: str :rtype: int"""
self.s = s
self.t = t
self.dict = {}
self.m = len(s)
self.n = len(t)
def dfs(i, j):
if j >= self.n:
return 1
if i >= self.m:
... | the_stack_v2_python_sparse | DistinctSubsequences_HARD_115.py | 953250587/leetcode-python | train | 2 | |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([bert_layer.attention.self.query.weight, bert_layer.attention.self.key.weight, bert_layer.attention.self.value.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([bert_layer.attention.self.query.bias, bert_layer.attention.self.key.bias, bert... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([bert_layer.attention.self.query.weight, bert_layer.attention.self.key.weight, bert_layer.attention.self.value.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([bert_layer.attention.self.query.bias, bert_l... | BertLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertLayerBetterTransformer:
def __init__(self, bert_layer, config):
"""A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original BERT Layer where the weights needs to be retrieved."""
<|body_0|>
def fo... | stack_v2_sparse_classes_10k_train_001912 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original BERT Layer where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, bert_layer, config)"
},
{
"docstring": "T... | 2 | stack_v2_sparse_classes_30k_train_001134 | Implement the Python class `BertLayerBetterTransformer` described below.
Class description:
Implement the BertLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, bert_layer, config): A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`to... | Implement the Python class `BertLayerBetterTransformer` described below.
Class description:
Implement the BertLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, bert_layer, config): A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`to... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class BertLayerBetterTransformer:
def __init__(self, bert_layer, config):
"""A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original BERT Layer where the weights needs to be retrieved."""
<|body_0|>
def fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BertLayerBetterTransformer:
def __init__(self, bert_layer, config):
"""A simple conversion of the BERT layer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original BERT Layer where the weights needs to be retrieved."""
super().__init__(config)
sel... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
0419d8e106afa6a4dbaad23097815b8a293c2c17 | [
"self.base_path = base_path\nself.mapreduce_spec = mapreduce_spec\nself.shard_id = shard_id\nself.slice_id = slice_id\nself.input_reader = input_reader\nself.initial_input_reader = initial_input_reader\nself.output_writer = output_writer\nself.retries = retries\nself.handler = handler\nself._input_reader_json = sel... | <|body_start_0|>
self.base_path = base_path
self.mapreduce_spec = mapreduce_spec
self.shard_id = shard_id
self.slice_id = slice_id
self.input_reader = input_reader
self.initial_input_reader = initial_input_reader
self.output_writer = output_writer
self.ret... | A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, shard_id. These are used to validate the task. | TransientShardState | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, sh... | stack_v2_sparse_classes_10k_train_001913 | 41,282 | permissive | [
{
"docstring": "Init. Args: base_path: base path of this mapreduce job. Deprecated. mapreduce_spec: an instance of MapReduceSpec. shard_id: shard id. slice_id: slice id. When enqueuing task for the next slice, this number is incremented by 1. input_reader: input reader instance for this shard. initial_input_rea... | 5 | null | Implement the Python class `TransientShardState` described below.
Class description:
A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are dupli... | Implement the Python class `TransientShardState` described below.
Class description:
A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are dupli... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, sh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransientShardState:
"""A shard's states that are kept in task payload. TransientShardState holds two types of states: 1. Some states just don't need to be saved to datastore. e.g. serialized input reader and output writer instances. 2. Some states are duplicated from datastore, e.g. slice_id, shard_id. These... | the_stack_v2_python_sparse | third_party/mapreduce/mapreduce/model.py | catapult-project/catapult | train | 2,032 |
8fd79c94c695933a1bf128d9a40ac494ca818fde | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('CreateKeywordsSamples', params, headers=headers)\n response = json.loads(body)\n model = models.CreateKeywordsSamplesResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('CreateKeywordsSamples', params, headers=headers)
response = json.loads(body)
model = models.CreateKeywordsSamplesResponse()
model._deserialize(r... | CmsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmsClient:
def CreateKeywordsSamples(self, request):
"""创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRequest` :rtype: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRespon... | stack_v2_sparse_classes_10k_train_001914 | 6,597 | permissive | [
{
"docstring": "创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRequest` :rtype: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesResponse`",
"name": "CreateKeywordsSamples",
"signature": "def... | 6 | stack_v2_sparse_classes_30k_train_003512 | Implement the Python class `CmsClient` described below.
Class description:
Implement the CmsClient class.
Method signatures and docstrings:
- def CreateKeywordsSamples(self, request): 创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKey... | Implement the Python class `CmsClient` described below.
Class description:
Implement the CmsClient class.
Method signatures and docstrings:
- def CreateKeywordsSamples(self, request): 创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKey... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class CmsClient:
def CreateKeywordsSamples(self, request):
"""创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRequest` :rtype: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRespon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CmsClient:
def CreateKeywordsSamples(self, request):
"""创建关键词接口 :param request: Request instance for CreateKeywordsSamples. :type request: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesRequest` :rtype: :class:`tencentcloud.cms.v20190321.models.CreateKeywordsSamplesResponse`"""
... | the_stack_v2_python_sparse | tencentcloud/cms/v20190321/cms_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
8e085268f34cc56ce856a7edbb494a08f45ae7a8 | [
"if not root:\n return []\nstack = [root]\nresult = []\nwhile stack:\n node = stack.pop()\n if not node:\n continue\n result.append(node.val)\n for each_node in reversed(node.children):\n stack.append(each_node)\nreturn result",
"result = []\n\ndef helper(node):\n if not node:\n ... | <|body_start_0|>
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
if not node:
continue
result.append(node.val)
for each_node in reversed(node.children):
stack.app... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def preorder_recursive(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
... | stack_v2_sparse_classes_10k_train_001915 | 1,397 | no_license | [
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "preorder",
"signature": "def preorder(self, root)"
},
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "preorder_recursive",
"signature": "def preorder_recursive(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002051 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: Node :rtype: List[int]
- def preorder_recursive(self, root): :type root: Node :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: Node :rtype: List[int]
- def preorder_recursive(self, root): :type root: Node :rtype: List[int]
<|skeleton|>
class Solution:
def preor... | 643df908343b38fa758f9dbcbbadd03ae8dbed74 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def preorder_recursive(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
if not node:
continue
result.append(node.val)
... | the_stack_v2_python_sparse | LeetCode/week_42/589_N叉树的前序遍历.py | Colaplusice/algorithm_and_data_structure | train | 0 | |
afb6c810bfb8c1a74bcb32ce02e3e388f214ed4d | [
"import sys, traceback\nexc_str = exc_only_str = _('Missing exception information')\ntry:\n etype, value, tb = sys.exc_info()\n exc_str = ''.join(traceback.format_exception(etype, value, tb))\n exc_only_str = ''.join(traceback.format_exception_only(etype, value))\nfinally:\n etype = value = tb = None\nr... | <|body_start_0|>
import sys, traceback
exc_str = exc_only_str = _('Missing exception information')
try:
etype, value, tb = sys.exc_info()
exc_str = ''.join(traceback.format_exception(etype, value, tb))
exc_only_str = ''.join(traceback.format_exception_only(ety... | A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog | ExceptionDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionDialog:
"""A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog"""
def create_exception_str():
"""Create two string... | stack_v2_sparse_classes_10k_train_001916 | 4,228 | no_license | [
{
"docstring": "Create two strings from latest exception.",
"name": "create_exception_str",
"signature": "def create_exception_str()"
},
{
"docstring": "Return error dialog containing Python trace for latest exception",
"name": "_create_error_dialog",
"signature": "def _create_error_dial... | 3 | stack_v2_sparse_classes_30k_train_003245 | Implement the Python class `ExceptionDialog` described below.
Class description:
A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog
Method signatures and do... | Implement the Python class `ExceptionDialog` described below.
Class description:
A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog
Method signatures and do... | 7e6e08a2acb34fe2dce6631f9f255dae5ab34a6b | <|skeleton|>
class ExceptionDialog:
"""A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog"""
def create_exception_str():
"""Create two string... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExceptionDialog:
"""A specialized Dialog. TODO actually make it a subclass instead of owning. For now, this might be redundant. The class hierarchy should be: GimpUi.Dialog Dialog (GimpFu) ControlDialog ExceptionDialog WarningDialog"""
def create_exception_str():
"""Create two strings from latest... | the_stack_v2_python_sparse | gimpfu/gui/exception_dialog.py | bootchk/GimpFu-v3 | train | 21 |
09f0d520cb76ba2d4f5258a5d45d84d6099b3f80 | [
"pcs = getToolByName(self, CACHE_TOOL_ID, None)\nif pcs is None or not pcs.getEnabled():\n return ()\nmember = pcs.getMember()\nrequest = content.REQUEST\nrule, header_set = pcs.getRuleAndHeaderSet(request, content, view_method, member)\nif header_set:\n expr_context = rule._getExpressionContext(request, cont... | <|body_start_0|>
pcs = getToolByName(self, CACHE_TOOL_ID, None)
if pcs is None or not pcs.getEnabled():
return ()
member = pcs.getMember()
request = content.REQUEST
rule, header_set = pcs.getRuleAndHeaderSet(request, content, view_method, member)
if header_set... | Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods. | CSCachingPolicyManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSCachingPolicyManager:
"""Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods."""
def getHeadersToAddAndRemove(self, content, view_method, keywords, time=None):
"""Return a tuple of HTTP caching headers, (headers_to_add, headers_to_remove). The f... | stack_v2_sparse_classes_10k_train_001917 | 4,929 | no_license | [
{
"docstring": "Return a tuple of HTTP caching headers, (headers_to_add, headers_to_remove). The first item is a list of headers to add to the response in the form (header name, header value). The second item is a list of headers that should be removed (before adding).",
"name": "getHeadersToAddAndRemove",
... | 4 | null | Implement the Python class `CSCachingPolicyManager` described below.
Class description:
Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods.
Method signatures and docstrings:
- def getHeadersToAddAndRemove(self, content, view_method, keywords, time=None): Return a tuple of HTTP ca... | Implement the Python class `CSCachingPolicyManager` described below.
Class description:
Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods.
Method signatures and docstrings:
- def getHeadersToAddAndRemove(self, content, view_method, keywords, time=None): Return a tuple of HTTP ca... | f359bb64db22f468db5d1e411638790e94d535a2 | <|skeleton|>
class CSCachingPolicyManager:
"""Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods."""
def getHeadersToAddAndRemove(self, content, view_method, keywords, time=None):
"""Return a tuple of HTTP caching headers, (headers_to_add, headers_to_remove). The f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CSCachingPolicyManager:
"""Manage the set of CachingPolicy objects for the site; dispatch to them from skin methods."""
def getHeadersToAddAndRemove(self, content, view_method, keywords, time=None):
"""Return a tuple of HTTP caching headers, (headers_to_add, headers_to_remove). The first item is ... | the_stack_v2_python_sparse | Products.CacheSetup/trunk/Products/CacheSetup/content/caching_policy_manager.py | kroman0/products | train | 0 |
765960cefd69e56fe3a82a1ddd7a1474de3e82f8 | [
"if params:\n url = url_concat(url, params)\nhttp_client = AsyncHTTPClient()\nresponse = await http_client.fetch(url, method='GET', headers=headers, request_timeout=timeout)\nif response.code not in (200, 201, 202, 203, 204, 205, 206):\n logger.error('url:', url, 'response code:', response.code, 'response bod... | <|body_start_0|>
if params:
url = url_concat(url, params)
http_client = AsyncHTTPClient()
response = await http_client.fetch(url, method='GET', headers=headers, request_timeout=timeout)
if response.code not in (200, 201, 202, 203, 204, 205, 206):
logger.error('url... | a wrapper of async http request | AsyncHttpRequests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf... | stack_v2_sparse_classes_10k_train_001918 | 3,653 | permissive | [
{
"docstring": "HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf-8解码 @param parse_json 是否解析返回body为json格式,默认为True @param timeout 请求超时时间,默认30秒 @return data 返回的http body",
"name": "get",
"signature": "async def get(cls, url, params=N... | 2 | stack_v2_sparse_classes_30k_train_007280 | Implement the Python class `AsyncHttpRequests` described below.
Class description:
a wrapper of async http request
Method signatures and docstrings:
- async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30): HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param ... | Implement the Python class `AsyncHttpRequests` described below.
Class description:
a wrapper of async http request
Method signatures and docstrings:
- async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30): HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param ... | 931fca8fab9d7397c52cf9e76a76b1c60e190403 | <|skeleton|>
class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf-8解码 @param p... | the_stack_v2_python_sparse | src/utils/http_client.py | Karmenzind/fp-server | train | 180 |
aef499a01cb90d14f70e7b19f8501bddbce1854c | [
"n = len(nums)\nlo, hi = (0, n - 1)\nwhile lo < hi and nums[lo] <= nums[lo + 1]:\n lo += 1\nwhile lo < hi and nums[hi - 1] <= nums[hi]:\n hi -= 1\nif hi <= lo:\n return 0\nmini = float('inf')\nmaxa = -float('inf')\nfor i in range(lo, hi + 1):\n mini = min(mini, nums[i])\n maxa = max(maxa, nums[i])\nw... | <|body_start_0|>
n = len(nums)
lo, hi = (0, n - 1)
while lo < hi and nums[lo] <= nums[lo + 1]:
lo += 1
while lo < hi and nums[hi - 1] <= nums[hi]:
hi -= 1
if hi <= lo:
return 0
mini = float('inf')
maxa = -float('inf')
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value... | stack_v2_sparse_classes_10k_train_001919 | 2,142 | no_license | [
{
"docstring": "Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value nums[lo - 1] <= min && max <= nums[hi + 1]",
"name": "findUnsortedSubarr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value nums[lo - 1] ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/581 Shortest Unsorted Continuous Subarray.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
c94aef0fbd65bedd39dff72490bb640c55ff51c9 | [
"ret = []\n\ndef swap(i, j):\n if i == j:\n return\n print('swap({},{})'.format(i, j))\n temp = nums[i]\n nums[i] = nums[j]\n nums[j] = temp\n\ndef isduplicate(start, end):\n return nums[end] in nums[start:end]\n\ndef permute_rec(start):\n if start == len(nums) - 1:\n ret.append(n... | <|body_start_0|>
ret = []
def swap(i, j):
if i == j:
return
print('swap({},{})'.format(i, j))
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def isduplicate(start, end):
return nums[end] in nums[start:end]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique_vt(self, nums):
"""solution with visit_table"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
def swap(i, j):
... | stack_v2_sparse_classes_10k_train_001920 | 2,669 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": "solution with visit_table",
"name": "permuteUnique_vt",
"signature": "def permuteUnique_vt(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004578 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique_vt(self, nums): solution with visit_table | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique_vt(self, nums): solution with visit_table
<|skeleton|>
class Solution:
def ... | bf03743a3676ca9a8c107f92cf3858b6887d0308 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique_vt(self, nums):
"""solution with visit_table"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
ret = []
def swap(i, j):
if i == j:
return
print('swap({},{})'.format(i, j))
temp = nums[i]
nums[i] = nums[j]
nums[j... | the_stack_v2_python_sparse | python/47_permutations.py | liaison/LeetCode | train | 17 | |
a0a268d7fedd1574c3913652b0e3749cbf222223 | [
"test_dictionary = {'donor': 'ME', 'amount': round(float(100), 2)}\nexpected = '\\nDear ME,\\n\\nThank you for your generous donation of $100.00\\n\\nSincerely,\\nThe Charity\\n'\nactual = mailroom4.letter(test_dictionary)\nself.assertEqual(expected, actual)",
"expected = [['William Gates, III', '$', 653784.49, 2... | <|body_start_0|>
test_dictionary = {'donor': 'ME', 'amount': round(float(100), 2)}
expected = '\nDear ME,\n\nThank you for your generous donation of $100.00\n\nSincerely,\nThe Charity\n'
actual = mailroom4.letter(test_dictionary)
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_... | Write a class containing a full suite of tests | TestMailroom | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_letter(self):
"""Test letter output"""
<|body_0|>
def test_calculation(self):
"""Test average and donation count calculations"""
<|body_1|>
def test_table(self):
"""T... | stack_v2_sparse_classes_10k_train_001921 | 2,174 | no_license | [
{
"docstring": "Test letter output",
"name": "test_letter",
"signature": "def test_letter(self)"
},
{
"docstring": "Test average and donation count calculations",
"name": "test_calculation",
"signature": "def test_calculation(self)"
},
{
"docstring": "Test table output format",
... | 4 | stack_v2_sparse_classes_30k_train_000991 | Implement the Python class `TestMailroom` described below.
Class description:
Write a class containing a full suite of tests
Method signatures and docstrings:
- def test_letter(self): Test letter output
- def test_calculation(self): Test average and donation count calculations
- def test_table(self): Test table outpu... | Implement the Python class `TestMailroom` described below.
Class description:
Write a class containing a full suite of tests
Method signatures and docstrings:
- def test_letter(self): Test letter output
- def test_calculation(self): Test average and donation count calculations
- def test_table(self): Test table outpu... | e298b1151dab639659d8dfa56f47bcb43dd3438f | <|skeleton|>
class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_letter(self):
"""Test letter output"""
<|body_0|>
def test_calculation(self):
"""Test average and donation count calculations"""
<|body_1|>
def test_table(self):
"""T... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestMailroom:
"""Write a class containing a full suite of tests"""
def test_letter(self):
"""Test letter output"""
test_dictionary = {'donor': 'ME', 'amount': round(float(100), 2)}
expected = '\nDear ME,\n\nThank you for your generous donation of $100.00\n\nSincerely,\nThe Charity... | the_stack_v2_python_sparse | students/Daniel_Spray/Lesson06/test_mailroom4.py | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | train | 13 |
607c23fcead3d3f2d4a4b0e88524a3708a921c0d | [
"self.index_map = defaultdict(list)\nfor i, word in enumerate(words):\n self.index_map[word].append(i)",
"list1 = self.index_map[word1]\nlist2 = self.index_map[word2]\ni, j = (0, 0)\nret = sys.maxsize\nwhile i < len(list1) and j < len(list2):\n idx1, idx2 = (list1[i], list2[j])\n if idx1 < idx2:\n ... | <|body_start_0|>
self.index_map = defaultdict(list)
for i, word in enumerate(words):
self.index_map[word].append(i)
<|end_body_0|>
<|body_start_1|>
list1 = self.index_map[word1]
list2 = self.index_map[word2]
i, j = (0, 0)
ret = sys.maxsize
while i < l... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.index_map = defaultdict(list)
... | stack_v2_sparse_classes_10k_train_001922 | 1,574 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 7de5f69e6e44ca4e74d75fed2af390b3d2cbd2b9 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.index_map = defaultdict(list)
for i, word in enumerate(words):
self.index_map[word].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
... | the_stack_v2_python_sparse | interview/linkedin/mid/LC244. Shortest Word Distance II.py | zhangshv123/superjump | train | 1 | |
ff3dda7d0cd1d7d16000e7f8d65e71e9e6148d1f | [
"self.filename = filename\nself.app = TK.Tk()\nself.app.title('Photo View Demo')\nmenubar = TK.Menu(self.app)\nfilemenu = TK.Menu(menubar, tearoff=0)\nfilemenu.add_command(label='Open', command=self.open_file)\nfilemenu.add_command(label='Exit', command=self.app.destroy)\nmenubar.add_cascade(label='File', menu=file... | <|body_start_0|>
self.filename = filename
self.app = TK.Tk()
self.app.title('Photo View Demo')
menubar = TK.Menu(self.app)
filemenu = TK.Menu(menubar, tearoff=0)
filemenu.add_command(label='Open', command=self.open_file)
filemenu.add_command(label='Exit', command=... | PhotoGui | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
<|body_0|>
def open_file(self):
"""Request select a photo"""
<|body_1|>
def disp_preview(self):
"""Display preview and details"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_001923 | 3,631 | permissive | [
{
"docstring": "Create a test GUI",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Request select a photo",
"name": "open_file",
"signature": "def open_file(self)"
},
{
"docstring": "Display preview and details",
"name": "disp_preview"... | 3 | stack_v2_sparse_classes_30k_train_007071 | Implement the Python class `PhotoGui` described below.
Class description:
Implement the PhotoGui class.
Method signatures and docstrings:
- def __init__(self, filename=None): Create a test GUI
- def open_file(self): Request select a photo
- def disp_preview(self): Display preview and details | Implement the Python class `PhotoGui` described below.
Class description:
Implement the PhotoGui class.
Method signatures and docstrings:
- def __init__(self, filename=None): Create a test GUI
- def open_file(self): Request select a photo
- def disp_preview(self): Display preview and details
<|skeleton|>
class Photo... | cfba2860145978904d1dd427f2326efeccfc561a | <|skeleton|>
class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
<|body_0|>
def open_file(self):
"""Request select a photo"""
<|body_1|>
def disp_preview(self):
"""Display preview and details"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PhotoGui:
def __init__(self, filename=None):
"""Create a test GUI"""
self.filename = filename
self.app = TK.Tk()
self.app.title('Photo View Demo')
menubar = TK.Menu(self.app)
filemenu = TK.Menu(menubar, tearoff=0)
filemenu.add_command(label='Open', comma... | the_stack_v2_python_sparse | chapter_03/tkphotohandler.py | packtjaniceg/Raspberry-Pi-4-Cookbook-for-Python-Programmers-Fourth-Edition | train | 0 | |
3a46a63d0e3797ac25869926bb92b6092e18df52 | [
"last_jump = True\ndist = nums[0]\nfor i in range(1, len(nums)):\n if last_jump and dist > 0:\n last_jump = True\n dist = max(dist - 1, nums[i])\n else:\n last_jump = False\nreturn last_jump",
"can_jump_at = {}\n\ndef can_jump_recursive_memoize(i):\n if i in can_jump_at:\n ret... | <|body_start_0|>
last_jump = True
dist = nums[0]
for i in range(1, len(nums)):
if last_jump and dist > 0:
last_jump = True
dist = max(dist - 1, nums[i])
else:
last_jump = False
return last_jump
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump_recursive(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
last_jump = True
dist = nums[0]
... | stack_v2_sparse_classes_10k_train_001924 | 1,277 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "can_jump_recursive",
"signature": "def can_jump_recursive(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001132 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump_recursive(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump_recursive(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def canJum... | 9d0ff0f8705451947a6605ab5ef92bb3e27a7147 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump_recursive(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
last_jump = True
dist = nums[0]
for i in range(1, len(nums)):
if last_jump and dist > 0:
last_jump = True
dist = max(dist - 1, nums[i])
else:
... | the_stack_v2_python_sparse | dynamic_programming/jump_game.py | rayt579/leetcode | train | 0 | |
c16005703e57c5d1e2cc81c7ebb7ba49406a221c | [
"control_samples = self._sample_data[column].dropna()\nnew_values = self._values.copy()\nfor sample, ctrl in dict(control_samples).items():\n mask = self._call_mask(self._values[ctrl], self._values[sample])\n new_values.loc[~mask, sample] = mask_value\nreturn self._constructor(new_values)",
"ctrl_sign = np.... | <|body_start_0|>
control_samples = self._sample_data[column].dropna()
new_values = self._values.copy()
for sample, ctrl in dict(control_samples).items():
mask = self._call_mask(self._values[ctrl], self._values[sample])
new_values.loc[~mask, sample] = mask_value
re... | Cnv matrix containing CNV calls (genes-by-samples). | CnvCallMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme... | stack_v2_sparse_classes_10k_train_001925 | 5,483 | no_license | [
{
"docstring": "Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme than the control sample or (c) the sample and control have calls with different signs (loss/gain). Matched control samples should be indicate... | 2 | stack_v2_sparse_classes_30k_train_003756 | Implement the Python class `CnvCallMatrix` described below.
Class description:
Cnv matrix containing CNV calls (genes-by-samples).
Method signatures and docstrings:
- def mask_with_controls(self, column, mask_value=0.0): Masks calls present in control samples. Calls are retained if (a) no call is present in the match... | Implement the Python class `CnvCallMatrix` described below.
Class description:
Cnv matrix containing CNV calls (genes-by-samples).
Method signatures and docstrings:
- def mask_with_controls(self, column, mask_value=0.0): Masks calls present in control samples. Calls are retained if (a) no call is present in the match... | f02c5d0232003c15a571fcadb528268bd4ff1c5b | <|skeleton|>
class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme than the con... | the_stack_v2_python_sparse | Coffee2Go/Coffee/Lib/site-packages/genopandas/ngs/cnv.py | FeliciaWilliamson/Coffee2Go | train | 0 |
ac6003a65a9750b446e7f5b40ea531c2f4831af0 | [
"self.root_nodes = root_nodes\nself.stats = stats\nself.stats_by_env = stats_by_env",
"if dictionary is None:\n return None\nroot_nodes = None\nif dictionary.get('rootNodes') != None:\n root_nodes = list()\n for structure in dictionary.get('rootNodes'):\n root_nodes.append(cohesity_management_sdk.... | <|body_start_0|>
self.root_nodes = root_nodes
self.stats = stats
self.stats_by_env = stats_by_env
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
root_nodes = None
if dictionary.get('rootNodes') != None:
root_nodes = list()
... | Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attributes: root_nodes (list of ProtectionSourceTreeInfo): Specifies the registration, protection an... | GetRegistrationInfoResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRegistrationInfoResponse:
"""Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attributes: root_nodes (list of ProtectionSou... | stack_v2_sparse_classes_10k_train_001926 | 3,189 | permissive | [
{
"docstring": "Constructor for the GetRegistrationInfoResponse class",
"name": "__init__",
"signature": "def __init__(self, root_nodes=None, stats=None, stats_by_env=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represe... | 2 | null | Implement the Python class `GetRegistrationInfoResponse` described below.
Class description:
Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attrib... | Implement the Python class `GetRegistrationInfoResponse` described below.
Class description:
Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attrib... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GetRegistrationInfoResponse:
"""Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attributes: root_nodes (list of ProtectionSou... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetRegistrationInfoResponse:
"""Implementation of the 'GetRegistrationInfoResponse' model. Specifies the registration, protection and permission information of all or a subset of the registered Protection Source Trees or Views on the Cohesity Cluster. Attributes: root_nodes (list of ProtectionSourceTreeInfo):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/get_registration_info_response.py | cohesity/management-sdk-python | train | 24 |
9f63011c1fc6009bfef6603fc54d9d310ea9d3e5 | [
"super().__init__(default_factory)\nself.connection = connect(GUNGAME_DATA_PATH / 'winners.db')\nself.connection.text_factory = str\nself.cursor = self.connection.cursor()\nself.cursor.execute('CREATE TABLE IF NOT EXISTS gungame_winners(unique_id varchar(20), name varchar(31), wins varchar(10) DEFAULT 0, time_stamp... | <|body_start_0|>
super().__init__(default_factory)
self.connection = connect(GUNGAME_DATA_PATH / 'winners.db')
self.connection.text_factory = str
self.cursor = self.connection.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS gungame_winners(unique_id varchar(20), name var... | Database to store player wins. | _WinsDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _WinsDatabase:
"""Database to store player wins."""
def __init__(self, default_factory):
"""Create the dictionary and gather any stored values."""
<|body_0|>
def load_database(self):
"""Fill the dictionary with the data from the stored database."""
<|body... | stack_v2_sparse_classes_10k_train_001927 | 5,149 | no_license | [
{
"docstring": "Create the dictionary and gather any stored values.",
"name": "__init__",
"signature": "def __init__(self, default_factory)"
},
{
"docstring": "Fill the dictionary with the data from the stored database.",
"name": "load_database",
"signature": "def load_database(self)"
... | 4 | stack_v2_sparse_classes_30k_train_004652 | Implement the Python class `_WinsDatabase` described below.
Class description:
Database to store player wins.
Method signatures and docstrings:
- def __init__(self, default_factory): Create the dictionary and gather any stored values.
- def load_database(self): Fill the dictionary with the data from the stored databa... | Implement the Python class `_WinsDatabase` described below.
Class description:
Database to store player wins.
Method signatures and docstrings:
- def __init__(self, default_factory): Create the dictionary and gather any stored values.
- def load_database(self): Fill the dictionary with the data from the stored databa... | dd76d1f581a1a8aff18c2194834665fa66a82aab | <|skeleton|>
class _WinsDatabase:
"""Database to store player wins."""
def __init__(self, default_factory):
"""Create the dictionary and gather any stored values."""
<|body_0|>
def load_database(self):
"""Fill the dictionary with the data from the stored database."""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _WinsDatabase:
"""Database to store player wins."""
def __init__(self, default_factory):
"""Create the dictionary and gather any stored values."""
super().__init__(default_factory)
self.connection = connect(GUNGAME_DATA_PATH / 'winners.db')
self.connection.text_factory = s... | the_stack_v2_python_sparse | addons/source-python/plugins/gungame/core/players/database.py | Hackmastr/GunGame-SP | train | 0 |
78b4250a19b894f63a8d355391a57cc79574566a | [
"acceptance_text = self.cleaned_data['acceptance_text']\ntry:\n render_template(acceptance_text, context=SAMPLE_DECISION_TEMPLATE_CONTEXT)\nexcept TemplateSyntaxError as ex:\n raise ValidationError('Unable to render acceptance template text: %(exception)s', params={'exception': ex})\nreturn acceptance_text",
... | <|body_start_0|>
acceptance_text = self.cleaned_data['acceptance_text']
try:
render_template(acceptance_text, context=SAMPLE_DECISION_TEMPLATE_CONTEXT)
except TemplateSyntaxError as ex:
raise ValidationError('Unable to render acceptance template text: %(exception)s', para... | A form to do field validation of LetterTemplatePage | LetterTemplatePageForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LetterTemplatePageForm:
"""A form to do field validation of LetterTemplatePage"""
def clean_acceptance_text(self):
"""Validate that the acceptance text is a valid Django template with no extra variables"""
<|body_0|>
def clean_rejection_text(self):
"""Validate th... | stack_v2_sparse_classes_10k_train_001928 | 1,468 | permissive | [
{
"docstring": "Validate that the acceptance text is a valid Django template with no extra variables",
"name": "clean_acceptance_text",
"signature": "def clean_acceptance_text(self)"
},
{
"docstring": "Validate that the rejection text is a valid Django template with no extra variables",
"nam... | 2 | stack_v2_sparse_classes_30k_train_003852 | Implement the Python class `LetterTemplatePageForm` described below.
Class description:
A form to do field validation of LetterTemplatePage
Method signatures and docstrings:
- def clean_acceptance_text(self): Validate that the acceptance text is a valid Django template with no extra variables
- def clean_rejection_te... | Implement the Python class `LetterTemplatePageForm` described below.
Class description:
A form to do field validation of LetterTemplatePage
Method signatures and docstrings:
- def clean_acceptance_text(self): Validate that the acceptance text is a valid Django template with no extra variables
- def clean_rejection_te... | 339c67b84b661a37ffe32580da72383d95666c5c | <|skeleton|>
class LetterTemplatePageForm:
"""A form to do field validation of LetterTemplatePage"""
def clean_acceptance_text(self):
"""Validate that the acceptance text is a valid Django template with no extra variables"""
<|body_0|>
def clean_rejection_text(self):
"""Validate th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LetterTemplatePageForm:
"""A form to do field validation of LetterTemplatePage"""
def clean_acceptance_text(self):
"""Validate that the acceptance text is a valid Django template with no extra variables"""
acceptance_text = self.cleaned_data['acceptance_text']
try:
ren... | the_stack_v2_python_sparse | cms/forms.py | mitodl/bootcamp-ecommerce | train | 6 |
d3ce4470d603bdb670ffd903ac853a6263e70f47 | [
"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... | Service to manage texture studio servers cluster. | TextureStudioManagerServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
<|body_0|>
def GetServers(self, request, context):
"""Get all existing servers"""
... | stack_v2_sparse_classes_10k_train_001929 | 9,913 | permissive | [
{
"docstring": "Create a new texture studio server.",
"name": "CreateServer",
"signature": "def CreateServer(self, request, context)"
},
{
"docstring": "Get all existing servers",
"name": "GetServers",
"signature": "def GetServers(self, request, context)"
},
{
"docstring": "Get t... | 5 | stack_v2_sparse_classes_30k_train_000235 | Implement the Python class `TextureStudioManagerServiceServicer` described below.
Class description:
Service to manage texture studio servers cluster.
Method signatures and docstrings:
- def CreateServer(self, request, context): Create a new texture studio server.
- def GetServers(self, request, context): Get all exi... | Implement the Python class `TextureStudioManagerServiceServicer` described below.
Class description:
Service to manage texture studio servers cluster.
Method signatures and docstrings:
- def CreateServer(self, request, context): Create a new texture studio server.
- def GetServers(self, request, context): Get all exi... | 2a640f7667d23f39e50ccc9ba73c98138c6839b5 | <|skeleton|>
class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
<|body_0|>
def GetServers(self, request, context):
"""Get all existing servers"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
r... | the_stack_v2_python_sparse | texturestudio/texturestudio_manage_pb2_grpc.py | MruV-RP/mruv-pb_python | train | 0 |
b4977bf7b14d7cb44640fd1652348c04a546afb7 | [
"project, network, phases = cls._parse_args(network=network, phases=phases)\ndf = Pandas.export_data(network=network, phases=phases, join=True, delim=delim)\nif filename == '':\n filename = project.name\nfname = cls._parse_filename(filename=filename, ext='csv')\ndf.to_csv(fname, index=False)",
"from pandas imp... | <|body_start_0|>
project, network, phases = cls._parse_args(network=network, phases=phases)
df = Pandas.export_data(network=network, phases=phases, join=True, delim=delim)
if filename == '':
filename = project.name
fname = cls._parse_filename(filename=filename, ext='csv')
... | Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent rows contain the data. 2. The property names should be in the usual Open... | CSV | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSV:
"""Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent rows contain the data. 2. The property na... | stack_v2_sparse_classes_10k_train_001930 | 4,965 | permissive | [
{
"docstring": "Save all the pore and throat property data on the Network (and optionally on any Phases objects) to CSV files. Parameters ---------- network : OpenPNM Network The Network containing the data to be stored phases : list of OpenPNM Phases (optional) The Phases whose data should be stored. filename ... | 2 | stack_v2_sparse_classes_30k_train_007038 | Implement the Python class `CSV` described below.
Class description:
Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent ro... | Implement the Python class `CSV` described below.
Class description:
Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent ro... | 5ddd7f7317dd9c6d82e6db5256ec1800dd6eef5d | <|skeleton|>
class CSV:
"""Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent rows contain the data. 2. The property na... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CSV:
"""Reads and writes CSV (comma-separated-value files) containing pore and throat data Notes ----- There are a few rules governing how the data is be stored: 1. The first row of the file (column headers) must contain the property names. The subsequent rows contain the data. 2. The property names should be... | the_stack_v2_python_sparse | openpnm/io/_csv.py | ma-sadeghi/OpenPNM | train | 1 |
631be76e304147dd58947c7b755ab8f3b2b7886f | [
"rights = gci_access.GCIChecker(params)\nrights['any_access'] = ['allow']\nnew_params = {}\nnew_params['logic'] = soc.modules.gci.logic.models.student_ranking.logic\nnew_params['rights'] = rights\nnew_params['name'] = 'Student Ranking'\nnew_params['module_name'] = 'student_ranking'\nnew_params['sidebar_grouping'] =... | <|body_start_0|>
rights = gci_access.GCIChecker(params)
rights['any_access'] = ['allow']
new_params = {}
new_params['logic'] = soc.modules.gci.logic.models.student_ranking.logic
new_params['rights'] = rights
new_params['name'] = 'Student Ranking'
new_params['modul... | View methods for the Tasks. | View | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
<|body_0|>
def showDetails(self, ... | stack_v2_sparse_classes_10k_train_001931 | 4,859 | permissive | [
{
"docstring": "Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Shows ranking details for the ent... | 3 | stack_v2_sparse_classes_30k_val_000324 | Implement the Python class `View` described below.
Class description:
View methods for the Tasks.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for th... | Implement the Python class `View` described below.
Class description:
View methods for the Tasks.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for th... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
<|body_0|>
def showDetails(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
rights = gci_access.GCIChecker(params)
righ... | the_stack_v2_python_sparse | app/soc/modules/gci/views/models/student_ranking.py | pombredanne/Melange-1 | train | 0 |
1b00e99db6ce038e2a920505a6ae0f4e7bc478a2 | [
"super(TransformerLoss, self).__init__()\nself.use_masking = use_masking\nself.bce_pos_weight = bce_pos_weight",
"if self.use_masking:\n mask = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)\n ys = ys.masked_select(mask)\n after_outs = after_outs.masked_select(mask)\n before_outs = before_outs.m... | <|body_start_0|>
super(TransformerLoss, self).__init__()
self.use_masking = use_masking
self.bce_pos_weight = bce_pos_weight
<|end_body_0|>
<|body_start_1|>
if self.use_masking:
mask = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)
ys = ys.masked_select(mas... | Loss function module for TTS-Transformer. | TransformerLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Wei... | stack_v2_sparse_classes_10k_train_001932 | 8,366 | permissive | [
{
"docstring": "Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Weight of positive sample of stop token (only for use_masking=True).",
"name": "__init__",
"signature": "def __init__(self, use_maski... | 2 | stack_v2_sparse_classes_30k_train_005203 | Implement the Python class `TransformerLoss` described below.
Class description:
Loss function module for TTS-Transformer.
Method signatures and docstrings:
- def __init__(self, use_masking=True, bce_pos_weight=5.0): Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part i... | Implement the Python class `TransformerLoss` described below.
Class description:
Loss function module for TTS-Transformer.
Method signatures and docstrings:
- def __init__(self, use_masking=True, bce_pos_weight=5.0): Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part i... | 41dc231931907e8c1fa9b85c5263f87163c723a4 | <|skeleton|>
class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Wei... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Weight of positi... | the_stack_v2_python_sparse | modules/loss.py | wangfn/FastSpeech2 | train | 0 |
44adf6b7c95b2729066649d9ead599fb3c4afeb3 | [
"self.iterator = iterator\nself._tag = False\nself._lastnum = 0",
"if not self._tag:\n self._tag = True\n self._lastnum = self.iterator.next()\nreturn self._lastnum",
"if not self._tag:\n self._lastnum = self.iterator.next()\nself._tag = False\nreturn self._lastnum",
"if not self._tag:\n return se... | <|body_start_0|>
self.iterator = iterator
self._tag = False
self._lastnum = 0
<|end_body_0|>
<|body_start_1|>
if not self._tag:
self._tag = True
self._lastnum = self.iterator.next()
return self._lastnum
<|end_body_1|>
<|body_start_2|>
if not self... | PeekingIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_10k_train_001933 | 1,759 | no_license | [
{
"docstring": "Initialize your data structure here. :type iterator: Iterator",
"name": "__init__",
"signature": "def __init__(self, iterator)"
},
{
"docstring": "Returns the next element in the iteration without advancing the iterator. :rtype: int",
"name": "peek",
"signature": "def pee... | 4 | null | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | c55892c27abcd6f23a86a76e4c42351695470459 | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
self.iterator = iterator
self._tag = False
self._lastnum = 0
def peek(self):
"""Returns the next element in the iteration without advancing the iterat... | the_stack_v2_python_sparse | src/algorithms/python/Peeking_Iterator.py | brickgao/leetcode | train | 1 | |
bbc48d786ea19f95c32e21a0dcb8780616a02c12 | [
"self.packages = []\nif from_file:\n log.debug('Loading RPM profile from file.')\n json_buffer = from_file.read()\n pkg_dicts = json.loads(json_buffer)\n for pkg_dict in pkg_dicts:\n self.packages.append(Package(name=pkg_dict['name'], version=pkg_dict['version'], release=pkg_dict['release'], arch... | <|body_start_0|>
self.packages = []
if from_file:
log.debug('Loading RPM profile from file.')
json_buffer = from_file.read()
pkg_dicts = json.loads(json_buffer)
for pkg_dict in pkg_dicts:
self.packages.append(Package(name=pkg_dict['name'], ... | RPMProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
<|body_0|>
def __accumulateProfile(self, rpm_header_list):
"""Accumulates list of installe... | stack_v2_sparse_classes_10k_train_001934 | 5,448 | no_license | [
{
"docstring": "Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.",
"name": "__init__",
"signature": "def __init__(self, from_file=None)"
},
{
"docstring": "Accumulates list of installed rpm info @param rpm_header_list: lis... | 4 | stack_v2_sparse_classes_30k_train_004284 | Implement the Python class `RPMProfile` described below.
Class description:
Implement the RPMProfile class.
Method signatures and docstrings:
- def __init__(self, from_file=None): Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.
- def __accumul... | Implement the Python class `RPMProfile` described below.
Class description:
Implement the RPMProfile class.
Method signatures and docstrings:
- def __init__(self, from_file=None): Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name.
- def __accumul... | 81643aaaa084575f4e651d3de75a86a9d31a8f49 | <|skeleton|>
class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
<|body_0|>
def __accumulateProfile(self, rpm_header_list):
"""Accumulates list of installe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RPMProfile:
def __init__(self, from_file=None):
"""Load the RPM package profile from a given file, or from rpm itself. NOTE: from_file is a file descriptor, not a file name."""
self.packages = []
if from_file:
log.debug('Loading RPM profile from file.')
json_buf... | the_stack_v2_python_sparse | pulp_rpm/src/pulp_rpm/repo_auth/rhsm/profile.py | jwmatthews/pulp_rpm | train | 0 | |
25de847bee622f603c90072a90a519b5c01b37b2 | [
"if mode == 'python':\n from ..python.tags import tag_manager as tmgr\n return tmgr.register(tag_class_or_alias)\n\ndef decorator(tag_class):\n \"\"\"The decorator for the tag class\"\"\"\n name = tag_class.__name__\n if name.startswith('Tag'):\n name = name[3:]\n if not name.isupper():... | <|body_start_0|>
if mode == 'python':
from ..python.tags import tag_manager as tmgr
return tmgr.register(tag_class_or_alias)
def decorator(tag_class):
"""The decorator for the tag class"""
name = tag_class.__name__
if name.startswith('Tag'):
... | The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database | TagManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagManager:
"""The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database"""
def register(self, tag_class_or_alias=None, mode='standard'):
"""Register a tag This can be worked as a decorator Args: tag_class_or_alias: The tag class or the alias ... | stack_v2_sparse_classes_10k_train_001935 | 3,349 | permissive | [
{
"docstring": "Register a tag This can be worked as a decorator Args: tag_class_or_alias: The tag class or the alias for the tag class to decorate mode: Whether do it for given mode Returns: The decorator or the decorated class",
"name": "register",
"signature": "def register(self, tag_class_or_alias=N... | 3 | stack_v2_sparse_classes_30k_train_000484 | Implement the Python class `TagManager` described below.
Class description:
The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database
Method signatures and docstrings:
- def register(self, tag_class_or_alias=None, mode='standard'): Register a tag This can be worked as a decora... | Implement the Python class `TagManager` described below.
Class description:
The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database
Method signatures and docstrings:
- def register(self, tag_class_or_alias=None, mode='standard'): Register a tag This can be worked as a decora... | bf84d631a2ecab0c020ba883bf2a09042715f772 | <|skeleton|>
class TagManager:
"""The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database"""
def register(self, tag_class_or_alias=None, mode='standard'):
"""Register a tag This can be worked as a decorator Args: tag_class_or_alias: The tag class or the alias ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TagManager:
"""The tag manager Attributes: INSTANCE: The instance of this singleton class tags: The tags database"""
def register(self, tag_class_or_alias=None, mode='standard'):
"""Register a tag This can be worked as a decorator Args: tag_class_or_alias: The tag class or the alias for the tag c... | the_stack_v2_python_sparse | liquid/tags/manager.py | lingfromSh/liquidpy | train | 0 |
c08fa6b6c41bbe8eebf5ec8d758ac05c153c9d33 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('kzhang21_ryuc', 'kzhang21_ryuc')\nurl = 'http://datamechanics.io/data/boston_entertainment.csv'\ndata = pd.read_csv(url, header=0)\ndata_entertainment = data[['BUSINESSNAME', 'LICCATDESC', 'Neighborhood'... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kzhang21_ryuc', 'kzhang21_ryuc')
url = 'http://datamechanics.io/data/boston_entertainment.csv'
data = pd.read_csv(url, header=0)
data_ente... | entertainment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class entertainment:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_10k_train_001936 | 4,668 | 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_005936 | Implement the Python class `entertainment` described below.
Class description:
Implement the entertainment class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | Implement the Python class `entertainment` described below.
Class description:
Implement the entertainment class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class entertainment:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class entertainment:
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('kzhang21_ryuc', 'kzhang21_ryuc')
... | the_stack_v2_python_sparse | kzhang21_ryuc/entertainment.py | maximega/course-2019-spr-proj | train | 2 | |
885528bbd45f9e7fdc481b7a529841bf8339c662 | [
"self.url = url\nself.repo = repo\nself.name = cookbook_name\nself.version = version\nself.manager = who",
"folder = './cookbooks/'\nmsg = 'En el getCookbook. \\n '\nset_info_log('url: ' + self.url + '. name: ' + folder + self.name)\nif self.repo == 'svn':\n try:\n Client().checkout(self.url, folder + s... | <|body_start_0|>
self.url = url
self.repo = repo
self.name = cookbook_name
self.version = version
self.manager = who
<|end_body_0|>
<|body_start_1|>
folder = './cookbooks/'
msg = 'En el getCookbook. \n '
set_info_log('url: ' + self.url + '. name: ' + fold... | Download | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None i... | stack_v2_sparse_classes_10k_train_001937 | 3,001 | no_license | [
{
"docstring": "Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None if all OK or an error on failure",
"name": "__init__",
"signature": "def _... | 3 | stack_v2_sparse_classes_30k_train_004762 | Implement the Python class `Download` described below.
Class description:
Implement the Download class.
Method signatures and docstrings:
- def __init__(self, url, repo, cookbook_name, version, who): Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: softwar... | Implement the Python class `Download` described below.
Class description:
Implement the Download class.
Method signatures and docstrings:
- def __init__(self, url, repo, cookbook_name, version, who): Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: softwar... | 34e1cb245b88789e779282db88108dd512e24bac | <|skeleton|>
class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None if all OK or an... | the_stack_v2_python_sparse | recipes/download.py | telefonicaid/fiware-uploadrecipes | train | 0 | |
9b58ef2b28761f7d76595ec670c015288dcf0c35 | [
"ans = []\nboard = [['.'] * n for _ in range(n)]\nself.fill_row(ans, board, [], n, 0)\nreturn ans",
"if row == n:\n ans.append([''.join(i) for i in board])\n return\nfor col in range(n):\n available = True\n for position in positions:\n if row == position[0] or col == position[1] or abs(row - p... | <|body_start_0|>
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
<|end_body_0|>
<|body_start_1|>
if row == n:
ans.append([''.join(i) for i in board])
return
for col in range(n):
available =... | 20190818 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_10k_train_001938 | 1,601 | no_license | [
{
"docstring": "暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n: int) -> List[List[str]]"
},
{
"docstring": "填入行",
"name": "fill_row",
"signature": "def fill_row(self, ans: List[List[str]], board: List[List[str]], pos... | 2 | stack_v2_sparse_classes_30k_train_005586 | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | Implement the Python class `Solution` described below.
Class description:
20190818
Method signatures and docstrings:
- def solveNQueens(self, n: int) -> List[List[str]]: 暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了
- def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: ... | efea806d49f07d78e3db0390696778d4a7fc6c28 | <|skeleton|>
class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
<|body_0|>
def fill_row(self, ans: List[List[str]], board: List[List[str]], positions: List[tuple], n: int, row: int):
"""填入行""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""20190818"""
def solveNQueens(self, n: int) -> List[List[str]]:
"""暴力依次放入 判断在斜线上可以用 abs(i1-i2)==abs(j1-j2) 之前在哪本书上看过的,忘了"""
ans = []
board = [['.'] * n for _ in range(n)]
self.fill_row(ans, board, [], n, 0)
return ans
def fill_row(self, ans: List[L... | the_stack_v2_python_sparse | ToolsX/leetcode/0051/0051.py | JunLei-MI/PythonX | train | 0 |
04a80cdb3be33cbb185f369a30b4ec3122a588d3 | [
"self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)\nself.cfg_filename = filename\nvalid = Validator()\nif not os.path.exists(self.cfg_filename):\n cfg = ConfigObj(configspec=self.cfg_spec, stringify=True, list_values=True)\n cfg.filename = self.cfg_filename\n test = cfg.validate(v... | <|body_start_0|>
self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)
self.cfg_filename = filename
valid = Validator()
if not os.path.exists(self.cfg_filename):
cfg = ConfigObj(configspec=self.cfg_spec, stringify=True, list_values=True)
cfg.... | Configuration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
<|body_0|>
def save_config(self, new_config):
"""Writes the config file upon exiting the prog... | stack_v2_sparse_classes_10k_train_001939 | 3,999 | no_license | [
{
"docstring": "Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Writes the config file upon exiting the program",
"name": "save_conf... | 2 | stack_v2_sparse_classes_30k_train_000490 | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def __init__(self, filename): Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters
- def save_conf... | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def __init__(self, filename): Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters
- def save_conf... | adf081cd95afd9487d0028235eea58a72a1cc05c | <|skeleton|>
class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
<|body_0|>
def save_config(self, new_config):
"""Writes the config file upon exiting the prog... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Configuration:
def __init__(self, filename):
"""Initializes a config file if does not exist. If exists, uses it to validate the file, and setup default initial parameters"""
self.cfg_spec = ConfigObj(config_spec_text.splitlines(), list_values=False)
self.cfg_filename = filename
... | the_stack_v2_python_sparse | dreampy3/utils/configuration.py | lmt-heterodyne/dreampy3 | train | 0 | |
2b87986897b4c1a914fc6d44e0fd0a9501f56877 | [
"self.split_by_sentence = split_by_sentence\nself.eol = end_of_line_token\ntrain_path = self.PTB_URL + 'train.txt'\nval_path = self.PTB_URL + 'valid.txt'\ntest_path = self.PTB_URL + 'test.txt'\ntrain = self._process(requests.get(train_path).content)\nval = self._process(requests.get(val_path).content)\ntest = self.... | <|body_start_0|>
self.split_by_sentence = split_by_sentence
self.eol = end_of_line_token
train_path = self.PTB_URL + 'train.txt'
val_path = self.PTB_URL + 'valid.txt'
test_path = self.PTB_URL + 'test.txt'
train = self._process(requests.get(train_path).content)
val... | The official PTB dataset. | PTBDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sent... | stack_v2_sparse_classes_10k_train_001940 | 6,879 | permissive | [
{
"docstring": "Initialize the PTBDataset builtin. Parameters ---------- split_by_sentence: bool, Optional If true, tokenizes per sentence. Default ``False``. end_of_line_token: str, Optional Token added at the end of every line. see TabularDataset for other arguments.",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_val_000165 | Implement the Python class `PTBDataset` described below.
Class description:
The official PTB dataset.
Method signatures and docstrings:
- def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None: Initialize th... | Implement the Python class `PTBDataset` described below.
Class description:
The official PTB dataset.
Method signatures and docstrings:
- def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None: Initialize th... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sent... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sentence: bool, O... | the_stack_v2_python_sparse | flambe/nlp/language_modeling/datasets.py | cle-ros/flambe | train | 1 |
bea455fe7a70fbb28bed089de125be7eedbc3c20 | [
"self.__wrapped = wrapped\nself.__retry_if = retry_if\nself.__backoff = backoff\nif self.__backoff <= 0:\n raise ValueError('backoff must be positive')\nself.__multiplier = multiplier\nif self.__multiplier < 1:\n raise ValueError('multiplier must be at least one!')\nself.__max_tries = max_tries\nself.__max_ba... | <|body_start_0|>
self.__wrapped = wrapped
self.__retry_if = retry_if
self.__backoff = backoff
if self.__backoff <= 0:
raise ValueError('backoff must be positive')
self.__multiplier = multiplier
if self.__multiplier < 1:
raise ValueError('multiplier... | Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function again, until it succeeds or we get a non-... | RetryWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function a... | stack_v2_sparse_classes_10k_train_001941 | 4,804 | permissive | [
{
"docstring": "Wrap the given object. :param wrapped: the object to wrap :param retry_if: a method that takes an exception, and returns whether we should retry :type backoff: float :param backoff: the number of seconds to wait the first time we get a retriable error :type multiplier: float :param multiplier: i... | 3 | null | Implement the Python class `RetryWrapper` described below.
Class description:
Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain nu... | Implement the Python class `RetryWrapper` described below.
Class description:
Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain nu... | fe21995e0402878437a828c6a4244025eac8c43b | <|skeleton|>
class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function again, until i... | the_stack_v2_python_sparse | python_modules/libraries/dagster-aws/dagster_aws/utils/mrjob/retry.py | dagster-io/dagster | train | 8,565 |
c179f6185a227367bb957a4354ba34e1a24951b8 | [
"val = {'pay_now': operation_type == 'treasury' and 'pay_later' or 'pay_now', 'payment_option': operation_type == 'treasury' and 'with_writeoff' or 'without_writeoff'}\nif operation_type == 'treasury':\n val.update({'line_dr_ids': False})\n account = self.pool.get('res.partner').browse(cr, uid, partner_id, co... | <|body_start_0|>
val = {'pay_now': operation_type == 'treasury' and 'pay_later' or 'pay_now', 'payment_option': operation_type == 'treasury' and 'with_writeoff' or 'without_writeoff'}
if operation_type == 'treasury':
val.update({'line_dr_ids': False})
account = self.pool.get('res... | account_voucher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return:... | stack_v2_sparse_classes_10k_train_001942 | 3,763 | no_license | [
{
"docstring": "Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return: dictionary of fields values",
"name": "onchange_operation_type",
"signature": "def onchange_operation_type(sel... | 5 | stack_v2_sparse_classes_30k_train_004594 | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None): Method that call when changing operation_type value, when operation is tr... | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None): Method that call when changing operation_type value, when operation is tr... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return: dictionary of... | the_stack_v2_python_sparse | v_7/Dongola/wafi/account_indirect_treasury_feeding/account_custom.py | musabahmed/baba | train | 0 | |
669ba5d3ddcb833f1e01465ccec198b7daee4b80 | [
"super(Linear, self).__init__()\nself.matmul = nn.MatMul()\nself.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float32)), name=None)\nself.add = P.Add()\nself.add_bias = Parameter(Tensor(np.random.uniform(0, 1, linear_bias_shape).astype(np.float32)), name=None)\nself.relu = nn.R... | <|body_start_0|>
super(Linear, self).__init__()
self.matmul = nn.MatMul()
self.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float32)), name=None)
self.add = P.Add()
self.add_bias = Parameter(Tensor(np.random.uniform(0, 1, linear_bias_shape).a... | module of reader downstream | Linear | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
<|body_0|>
def construct(self, hidden_state):
"""construct function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(L... | stack_v2_sparse_classes_10k_train_001943 | 9,011 | permissive | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self, linear_weight_shape, linear_bias_shape)"
},
{
"docstring": "construct function",
"name": "construct",
"signature": "def construct(self, hidden_state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005069 | Implement the Python class `Linear` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape): init function
- def construct(self, hidden_state): construct function | Implement the Python class `Linear` described below.
Class description:
module of reader downstream
Method signatures and docstrings:
- def __init__(self, linear_weight_shape, linear_bias_shape): init function
- def construct(self, hidden_state): construct function
<|skeleton|>
class Linear:
"""module of reader ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
<|body_0|>
def construct(self, hidden_state):
"""construct function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Linear:
"""module of reader downstream"""
def __init__(self, linear_weight_shape, linear_bias_shape):
"""init function"""
super(Linear, self).__init__()
self.matmul = nn.MatMul()
self.matmul_w = Parameter(Tensor(np.random.uniform(0, 1, linear_weight_shape).astype(np.float3... | the_stack_v2_python_sparse | research/nlp/tprr/src/reader_downstream.py | mindspore-ai/models | train | 301 |
eb97a0ab08ff19e2e71e842b5af03e127a6d9cf3 | [
"s = s.strip()\ndot_seen = False\ne_seen = False\nnum_seen = False\nfor i, a in enumerate(s):\n if a.isdigit():\n num_seen = True\n elif a == '.':\n if e_seen or dot_seen:\n return False\n dot_seen = True\n elif a == 'e':\n if e_seen or not num_seen:\n retu... | <|body_start_0|>
s = s.strip()
dot_seen = False
e_seen = False
num_seen = False
for i, a in enumerate(s):
if a.isdigit():
num_seen = True
elif a == '.':
if e_seen or dot_seen:
return False
... | 指数 e 后面只能是数字 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
<|body_0|>
def isNumber2(self, s: str):
... | stack_v2_sparse_classes_10k_train_001944 | 3,962 | permissive | [
{
"docstring": "提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现",
"name": "isNumber",
"signature": "def isNumber(self, s: str)"
},
{
"docstring": "提示:有限状态机 FSM 状态转移图见同目录下 FSM.pn... | 2 | stack_v2_sparse_classes_30k_test_000005 | Implement the Python class `Solution` described below.
Class description:
指数 e 后面只能是数字
Method signatures and docstrings:
- def isNumber(self, s: str): 提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现
... | Implement the Python class `Solution` described below.
Class description:
指数 e 后面只能是数字
Method signatures and docstrings:
- def isNumber(self, s: str): 提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现
... | 889d8fa489f1f2719c5a0dafd3ae51df7b4bf978 | <|skeleton|>
class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
<|body_0|>
def isNumber2(self, s: str):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
s = s.strip()
dot_seen = False
e_seen = Fal... | the_stack_v2_python_sparse | LeetCode/65-有效数字/isNumber.py | jinbooooom/coding-for-algorithms | train | 14 |
831992343fba9a311200361aedc2942f56dab2fd | [
"p = self.params\nif len(inputs.shape) != 4:\n raise ValueError('Input is assumed to be a rank 4 tensor of shape[batch, sequence, heads, dims].')\nif p.embedding_dims % 2:\n raise ValueError('Embedding dim for rotary position embedding must be amultiple of 2.')\nif p.embedding_dims != inputs.shape[3]:\n ra... | <|body_start_0|>
p = self.params
if len(inputs.shape) != 4:
raise ValueError('Input is assumed to be a rank 4 tensor of shape[batch, sequence, heads, dims].')
if p.embedding_dims % 2:
raise ValueError('Embedding dim for rotary position embedding must be amultiple of 2.')
... | Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864 | RotaryPositionalEmbedding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotaryPositionalEmbedding:
"""Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864"""
def fprop(self, inputs: JTensor, position: Optional[JTensor]=None) -> JTensor:
"""Generates a JTensor of sinusoi... | stack_v2_sparse_classes_10k_train_001945 | 24,667 | permissive | [
{
"docstring": "Generates a JTensor of sinusoids with different frequencies. Args: inputs: The input sequence on which to apply the Rotary position embedding. Since rotary position embeddings are applied to query and keys after projection, it is assumed of shape [B, S, N, H]. position: Optional position JTensor... | 2 | null | Implement the Python class `RotaryPositionalEmbedding` described below.
Class description:
Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864
Method signatures and docstrings:
- def fprop(self, inputs: JTensor, position: Optional[... | Implement the Python class `RotaryPositionalEmbedding` described below.
Class description:
Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864
Method signatures and docstrings:
- def fprop(self, inputs: JTensor, position: Optional[... | c00a74b260fcf6ba11199cc4a340c127d6616479 | <|skeleton|>
class RotaryPositionalEmbedding:
"""Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864"""
def fprop(self, inputs: JTensor, position: Optional[JTensor]=None) -> JTensor:
"""Generates a JTensor of sinusoi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RotaryPositionalEmbedding:
"""Applies rotary position embedding for a given 1-d sequence. The Rotary position embedding is described in https://arxiv.org/abs/2104.09864"""
def fprop(self, inputs: JTensor, position: Optional[JTensor]=None) -> JTensor:
"""Generates a JTensor of sinusoids with diffe... | the_stack_v2_python_sparse | lingvo/jax/layers/embedding_softmax.py | tensorflow/lingvo | train | 2,963 |
dbd32240acbc03e36033ba5844c68fc020fd0314 | [
"deps = [('szip', '--with-szlib')]\nfor dep, opt in deps:\n root = get_software_root(dep)\n if root:\n self.cfg.update('configopts', '%s=%s' % (opt, root))\n else:\n self.log.error('Dependency module %s not loaded.' % dep)\nfcomp = 'FC=\"%s\"' % os.getenv('F90')\nself.cfg.update('configopts',... | <|body_start_0|>
deps = [('szip', '--with-szlib')]
for dep, opt in deps:
root = get_software_root(dep)
if root:
self.cfg.update('configopts', '%s=%s' % (opt, root))
else:
self.log.error('Dependency module %s not loaded.' % dep)
... | Support for building/installing HDF5 | EB_hdf5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_hdf5:
"""Support for building/installing HDF5"""
def configure_step(self):
"""Configure build: set require config and make options, and run configure script."""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check for HDF5"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k_train_001946 | 4,328 | no_license | [
{
"docstring": "Configure build: set require config and make options, and run configure script.",
"name": "configure_step",
"signature": "def configure_step(self)"
},
{
"docstring": "Custom sanity check for HDF5",
"name": "sanity_check_step",
"signature": "def sanity_check_step(self)"
... | 2 | stack_v2_sparse_classes_30k_train_005524 | Implement the Python class `EB_hdf5` described below.
Class description:
Support for building/installing HDF5
Method signatures and docstrings:
- def configure_step(self): Configure build: set require config and make options, and run configure script.
- def sanity_check_step(self): Custom sanity check for HDF5 | Implement the Python class `EB_hdf5` described below.
Class description:
Support for building/installing HDF5
Method signatures and docstrings:
- def configure_step(self): Configure build: set require config and make options, and run configure script.
- def sanity_check_step(self): Custom sanity check for HDF5
<|ske... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_hdf5:
"""Support for building/installing HDF5"""
def configure_step(self):
"""Configure build: set require config and make options, and run configure script."""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check for HDF5"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EB_hdf5:
"""Support for building/installing HDF5"""
def configure_step(self):
"""Configure build: set require config and make options, and run configure script."""
deps = [('szip', '--with-szlib')]
for dep, opt in deps:
root = get_software_root(dep)
if root... | the_stack_v2_python_sparse | 1.13.0/easyblock/easyblocks/h/hdf5.py | lsuhpchelp/easybuild_smic | train | 0 |
2b3aa3d95af52fe0dfa235046012c9c40b5ba3bb | [
"self.Wz = np.random.randn(h + i, h)\nself.bz = np.zeros((1, h))\nself.Wr = np.random.randn(h + i, h)\nself.br = np.zeros((1, h))\nself.Wh = np.random.randn(h + i, h)\nself.bh = np.zeros((1, h))\nself.Wy = np.random.randn(h, o)\nself.by = np.zeros((1, o))",
"m, _ = h_prev.shape\nh = np.concatenate((h_prev, x_t), ... | <|body_start_0|>
self.Wz = np.random.randn(h + i, h)
self.bz = np.zeros((1, h))
self.Wr = np.random.randn(h + i, h)
self.br = np.zeros((1, h))
self.Wh = np.random.randn(h + i, h)
self.bh = np.zeros((1, h))
self.Wy = np.random.randn(h, o)
self.by = np.zeros... | the GRU cell class GRU: gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""the GRU cell class GRU: gated recurrent unit"""
def __init__(self, i, h, o):
"""the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases) Wz, bz: for update gate Wr, br: for reset gate Wh, bh: ... | stack_v2_sparse_classes_10k_train_001947 | 2,314 | no_license | [
{
"docstring": "the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases) Wz, bz: for update gate Wr, br: for reset gate Wh, bh: for intermediate hidden state Wy, by: for output",
"name": "__init__",
"signature": "def __init_... | 2 | stack_v2_sparse_classes_30k_train_002314 | Implement the Python class `GRUCell` described below.
Class description:
the GRU cell class GRU: gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases... | Implement the Python class `GRUCell` described below.
Class description:
the GRU cell class GRU: gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class GRUCell:
"""the GRU cell class GRU: gated recurrent unit"""
def __init__(self, i, h, o):
"""the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases) Wz, bz: for update gate Wr, br: for reset gate Wh, bh: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""the GRU cell class GRU: gated recurrent unit"""
def __init__(self, i, h, o):
"""the GRUCell constructor i: dimensionality of the data h: dimensions of hidden state o: dimensions of output fields: (weights and biases) Wz, bz: for update gate Wr, br: for reset gate Wh, bh: for intermedi... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | mag389/holbertonschool-machine_learning | train | 2 |
b81375fe3db43aa96fbfda9dabd194cb53df4a26 | [
"self.level_vectors = level_vectors\nself.labels = labels\nself.pairs_df = pairs_df",
"scores = []\nfor left in range(251):\n if left in self.labels:\n for right in range(left, 251):\n if right in self.labels:\n scores.append(self.compare_vectors(left, right, weights))\nscores_... | <|body_start_0|>
self.level_vectors = level_vectors
self.labels = labels
self.pairs_df = pairs_df
<|end_body_0|>
<|body_start_1|>
scores = []
for left in range(251):
if left in self.labels:
for right in range(left, 251):
if right i... | Comparator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparator:
def __init__(self, level_vectors, labels, pairs_df):
"""Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed ... | stack_v2_sparse_classes_10k_train_001948 | 4,868 | permissive | [
{
"docstring": "Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed vectors pairs_df: dataframe containing pair indices and respective mean scor... | 5 | stack_v2_sparse_classes_30k_train_005405 | Implement the Python class `Comparator` described below.
Class description:
Implement the Comparator class.
Method signatures and docstrings:
- def __init__(self, level_vectors, labels, pairs_df): Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing den... | Implement the Python class `Comparator` described below.
Class description:
Implement the Comparator class.
Method signatures and docstrings:
- def __init__(self, level_vectors, labels, pairs_df): Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing den... | cc9b28b8741b41bea1273c8bc9b4d265d79a1dca | <|skeleton|>
class Comparator:
def __init__(self, level_vectors, labels, pairs_df):
"""Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Comparator:
def __init__(self, level_vectors, labels, pairs_df):
"""Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed vectors pairs_... | the_stack_v2_python_sparse | autoencoder/comparator.py | xingchen1106/match3-level-similarity | train | 0 | |
fb25f86d4956d0617e8e8b9df02a666e9f948b18 | [
"for name, infos in Rt.geom_dict.items():\n if name in Rt.optim_var_dict:\n self.add_input(name, val=infos[1][0])",
"log.info(f'Start optimisation iteration: {Rt.counter}')\nfor name, infos in Rt.geom_dict.items():\n infos[1].append(inputs[name][0])\nif Rt.counter == 0:\n cpacs_in = Rt.modules[0].... | <|body_start_0|>
for name, infos in Rt.geom_dict.items():
if name in Rt.optim_var_dict:
self.add_input(name, val=infos[1][0])
<|end_body_0|>
<|body_start_1|>
log.info(f'Start optimisation iteration: {Rt.counter}')
for name, infos in Rt.geom_dict.items():
... | Classe to define the geometric parameters | Geom_param | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
<|body_0|>
def compute(self, inputs, outputs):
"""Update the geometry of the CPACS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001949 | 20,064 | permissive | [
{
"docstring": "Setup inputs only for the geometry",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Update the geometry of the CPACS",
"name": "compute",
"signature": "def compute(self, inputs, outputs)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000176 | Implement the Python class `Geom_param` described below.
Class description:
Classe to define the geometric parameters
Method signatures and docstrings:
- def setup(self): Setup inputs only for the geometry
- def compute(self, inputs, outputs): Update the geometry of the CPACS | Implement the Python class `Geom_param` described below.
Class description:
Classe to define the geometric parameters
Method signatures and docstrings:
- def setup(self): Setup inputs only for the geometry
- def compute(self, inputs, outputs): Update the geometry of the CPACS
<|skeleton|>
class Geom_param:
"""Cl... | 30ca55b39dc14e3f8ec1e00a475f76024d1b5fef | <|skeleton|>
class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
<|body_0|>
def compute(self, inputs, outputs):
"""Update the geometry of the CPACS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
for name, infos in Rt.geom_dict.items():
if name in Rt.optim_var_dict:
self.add_input(name, val=infos[1][0])
def compute(self, inputs, out... | the_stack_v2_python_sparse | ceasiompy/Optimisation/optimisation.py | cfsengineering/CEASIOMpy | train | 60 |
ec033c87421054d5accc658daf3d040de2b5106f | [
"self._serv = SimpleXMLRPCServer(address, allow_none=True)\nself._db = pyvanas_db\nself._redis = redis\nfor name in self._rpc_methods_:\n self._serv.register_function(getattr(self, name))",
"user_info = self._db['user']\nuser = user_info.find_one({'_id': ObjectId(user_id)})\nstart_utc_time = datetime.datetime.... | <|body_start_0|>
self._serv = SimpleXMLRPCServer(address, allow_none=True)
self._db = pyvanas_db
self._redis = redis
for name in self._rpc_methods_:
self._serv.register_function(getattr(self, name))
<|end_body_0|>
<|body_start_1|>
user_info = self._db['user']
... | vanas_data_server | VanasDataServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VanasDataServer:
"""vanas_data_server"""
def __init__(self, address, pyvanas_db, redis):
"""TODO: to be defined1."""
<|body_0|>
def get_data(self, symbol, start_time, end_time, user_id):
"""docstring for get_data"""
<|body_1|>
def send_status(self, d... | stack_v2_sparse_classes_10k_train_001950 | 2,259 | no_license | [
{
"docstring": "TODO: to be defined1.",
"name": "__init__",
"signature": "def __init__(self, address, pyvanas_db, redis)"
},
{
"docstring": "docstring for get_data",
"name": "get_data",
"signature": "def get_data(self, symbol, start_time, end_time, user_id)"
},
{
"docstring": "发送... | 3 | stack_v2_sparse_classes_30k_train_006282 | Implement the Python class `VanasDataServer` described below.
Class description:
vanas_data_server
Method signatures and docstrings:
- def __init__(self, address, pyvanas_db, redis): TODO: to be defined1.
- def get_data(self, symbol, start_time, end_time, user_id): docstring for get_data
- def send_status(self, data,... | Implement the Python class `VanasDataServer` described below.
Class description:
vanas_data_server
Method signatures and docstrings:
- def __init__(self, address, pyvanas_db, redis): TODO: to be defined1.
- def get_data(self, symbol, start_time, end_time, user_id): docstring for get_data
- def send_status(self, data,... | 80c33304d25f01b321f3351d934190dc927e13dc | <|skeleton|>
class VanasDataServer:
"""vanas_data_server"""
def __init__(self, address, pyvanas_db, redis):
"""TODO: to be defined1."""
<|body_0|>
def get_data(self, symbol, start_time, end_time, user_id):
"""docstring for get_data"""
<|body_1|>
def send_status(self, d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VanasDataServer:
"""vanas_data_server"""
def __init__(self, address, pyvanas_db, redis):
"""TODO: to be defined1."""
self._serv = SimpleXMLRPCServer(address, allow_none=True)
self._db = pyvanas_db
self._redis = redis
for name in self._rpc_methods_:
self... | the_stack_v2_python_sparse | vanas_server/vanas_rpc_server.py | tianhm/pyvanas-halfway | train | 0 |
67425d66f165e89fb8ebd9d1d52ad4d98ae8c381 | [
"batch_size = 4\npadded_length = 6\nnum_classes = 4\nnp.random.seed(1234)\nsequence_length = np.random.randint(0, padded_length + 1, batch_size)\nactivations = np.random.rand(batch_size, padded_length, num_classes)\nlabels = np.random.randint(0, num_classes, [batch_size, padded_length])\nactivations_masked_t, label... | <|body_start_0|>
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(1234)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.random.rand(batch_size, padded_length, num_classes)
labels = np.random.randint(0, num_clas... | RnnCommonTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
<|body_0|>
def testSelectLastActivations(self):
"""Test `select_last_activations`."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
batch_size = 4
... | stack_v2_sparse_classes_10k_train_001951 | 4,838 | permissive | [
{
"docstring": "Test `mask_activations_and_labels`.",
"name": "testMaskActivationsAndLabels",
"signature": "def testMaskActivationsAndLabels(self)"
},
{
"docstring": "Test `select_last_activations`.",
"name": "testSelectLastActivations",
"signature": "def testSelectLastActivations(self)"... | 2 | null | Implement the Python class `RnnCommonTest` described below.
Class description:
Implement the RnnCommonTest class.
Method signatures and docstrings:
- def testMaskActivationsAndLabels(self): Test `mask_activations_and_labels`.
- def testSelectLastActivations(self): Test `select_last_activations`. | Implement the Python class `RnnCommonTest` described below.
Class description:
Implement the RnnCommonTest class.
Method signatures and docstrings:
- def testMaskActivationsAndLabels(self): Test `mask_activations_and_labels`.
- def testSelectLastActivations(self): Test `select_last_activations`.
<|skeleton|>
class R... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
<|body_0|>
def testSelectLastActivations(self):
"""Test `select_last_activations`."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RnnCommonTest:
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(1234)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.... | the_stack_v2_python_sparse | tensorflow/contrib/learn/python/learn/estimators/rnn_common_test.py | NVIDIA/tensorflow | train | 763 | |
9ff101a51354921862b04fdd826669daee7a7bd1 | [
"self.cfg = AutoCFG(self.__defaults).update_fields(kwargs)\nself.secret = secret\nself.logger = new_channel('tokenazer')",
"try:\n return jschema.apply(obj=art.unmarshal(data=cfb_decrypt(self.secret, data=data['d'], iv=data['i']), mask=(bytes((mask[i] ^ self.cfg.mask_1[i % len(self.cfg.mask_1)] for i in range(... | <|body_start_0|>
self.cfg = AutoCFG(self.__defaults).update_fields(kwargs)
self.secret = secret
self.logger = new_channel('tokenazer')
<|end_body_0|>
<|body_start_1|>
try:
return jschema.apply(obj=art.unmarshal(data=cfb_decrypt(self.secret, data=data['d'], iv=data['i']), mas... | This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 ) | Tokenazer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto k... | stack_v2_sparse_classes_10k_train_001952 | 5,190 | permissive | [
{
"docstring": "secret - secret key for crypto kwargs: mask_0 - bytes - extra secret (default: None) mask_1 - bytes - extra secret (default: None)",
"name": "__init__",
"signature": "def __init__(self, secret: bytes, **kwargs) -> None"
},
{
"docstring": ":rtype dict: decoded cookie as dict or No... | 4 | stack_v2_sparse_classes_30k_train_002176 | Implement the Python class `Tokenazer` described below.
Class description:
This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )
Method signatures and docstrings:
- def __init__(self, secret: b... | Implement the Python class `Tokenazer` described below.
Class description:
This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )
Method signatures and docstrings:
- def __init__(self, secret: b... | f8ca3a40c4bcb6c8d75d6e8a3ef796295b734be7 | <|skeleton|>
class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto k... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tokenazer:
"""This module is to encrypt and descrypt tokens like cookie - session_id session_id = art( { 'd': cfb_encrypt( art( <users data>, XOR( mask_1 , mask_local ) ) ) 'i': iv }, mask_0 )"""
def __init__(self, secret: bytes, **kwargs) -> None:
"""secret - secret key for crypto kwargs: mask_0... | the_stack_v2_python_sparse | k2/tokenazer/tokenazer.py | moff4/k2 | train | 2 |
6bfbf95ba1d6f87a8a66fddb73de7414ce6db78d | [
"self.id = id\nself.consumer_id = consumer_id\nself.consumer_ssn = consumer_ssn\nself.requester_name = requester_name\nself.request_id = request_id\nself.constraints = constraints\nself.mtype = mtype\nself.status = status\nself.created_date = created_date\nself.additional_properties = additional_properties",
"if ... | <|body_start_0|>
self.id = id
self.consumer_id = consumer_id
self.consumer_ssn = consumer_ssn
self.requester_name = requester_name
self.request_id = request_id
self.constraints = constraints
self.mtype = mtype
self.status = status
self.created_date... | Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name (string): Name of Finicity partner reque... | ReportSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportSummary:
"""Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name... | stack_v2_sparse_classes_10k_train_001953 | 3,888 | permissive | [
{
"docstring": "Constructor for the ReportSummary class",
"name": "__init__",
"signature": "def __init__(self, id=None, consumer_id=None, consumer_ssn=None, requester_name=None, request_id=None, constraints=None, mtype=None, status=None, created_date=None, additional_properties={})"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_006584 | Implement the Python class `ReportSummary` described below.
Class description:
Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer'... | Implement the Python class `ReportSummary` described below.
Class description:
Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer'... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class ReportSummary:
"""Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReportSummary:
"""Implementation of the 'Report Summary' model. TODO: type model description here. Attributes: id (string): The Finicity report ID consumer_id (string): Finicity ID for the consumer consumer_ssn (string): Last 4 digits of the report consumer's Social Security number requester_name (string): Na... | the_stack_v2_python_sparse | finicityapi/models/report_summary.py | monarchmoney/finicity-python | train | 0 |
1633e726570eb038def367dbda4bac4a1edbd892 | [
"print('Loading weights: ', path)\nsuper(MidasNet, self).__init__()\nuse_pretrained = False if path is None else True\nself.pretrained, self.scratch = _make_encoder(backbone='resnext101_wsl', features=features, use_pretrained=use_pretrained)\nself.scratch.refinenet4 = FeatureFusionBlock(features)\nself.scratch.refi... | <|body_start_0|>
print('Loading weights: ', path)
super(MidasNet, self).__init__()
use_pretrained = False if path is None else True
self.pretrained, self.scratch = _make_encoder(backbone='resnext101_wsl', features=features, use_pretrained=use_pretrained)
self.scratch.refinenet4 =... | Network for monocular depth estimation. | MidasNet | [
"MIT",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional):... | stack_v2_sparse_classes_10k_train_001954 | 2,934 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50",
"name": "__init__",
"signature": "def __init__(self, path=None, features=... | 2 | stack_v2_sparse_classes_30k_train_006898 | Implement the Python class `MidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Numbe... | Implement the Python class `MidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Numbe... | 038fb5afe017b82334ad39a256531d2c4e9e1e1a | <|skeleton|>
class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone net... | the_stack_v2_python_sparse | 15.PaddleGAN/PaddleGAN/ppgan/apps/midas/midas_net.py | yingshaoxo/ML | train | 5 |
1c145999b8e07d52087afc7741082020510d35d6 | [
"self.preSum = [0] * len(w)\nself.preSum[0] = w[0]\nfor i in range(1, len(w)):\n self.preSum[i] = self.preSum[i - 1] + w[i]",
"total = self.preSum[-1]\nrand = random.randint(0, total - 1)\nleft, right = (0, len(self.preSum) - 1)\nwhile left + 1 < right:\n mid = (left + right) // 2\n if rand >= self.preSu... | <|body_start_0|>
self.preSum = [0] * len(w)
self.preSum[0] = w[0]
for i in range(1, len(w)):
self.preSum[i] = self.preSum[i - 1] + w[i]
<|end_body_0|>
<|body_start_1|>
total = self.preSum[-1]
rand = random.randint(0, total - 1)
left, right = (0, len(self.preS... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.preSum = [0] * len(w)
self.preSum[0] = w[0]
for i in range(1, len(w)):
... | stack_v2_sparse_classes_10k_train_001955 | 3,072 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006263 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.preSum = [0] * len(w)
self.preSum[0] = w[0]
for i in range(1, len(w)):
self.preSum[i] = self.preSum[i - 1] + w[i]
def pickIndex(self):
""":rtype: int"""
total = self.preSum[-1]
... | the_stack_v2_python_sparse | co_linkedin/528_Random_Pick_with_Weight.py | vsdrun/lc_public | train | 6 | |
7b3fd1b4d7ad2f761b44c130da4a361968f8cefe | [
"embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))\nif self.example:\n embed.add_field(name='Example', value=utils.truncate(self.example, 1024), inline=False)\nembed.add_field(name='👍', value=utils.commas(self.thumbs_up))\nembed.add_field(name='👎', value=utils.commas(self.thumbs... | <|body_start_0|>
embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))
if self.example:
embed.add_field(name='Example', value=utils.truncate(self.example, 1024), inline=False)
embed.add_field(name='👍', value=utils.commas(self.thumbs_up))
embed.add... | Represents an Urban Dictionary entry. | UrbanDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
<|body_0|>
async def query(cls, session: ClientSession, word: str) -> Union[None, 'UrbanDefinition']:
"""Que... | stack_v2_sparse_classes_10k_train_001956 | 5,625 | permissive | [
{
"docstring": "Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.",
"name": "embed",
"signature": "def embed(self) -> Embed"
},
{
"docstring": "Queries UrbanDictionary for a definition.",
"name": "query",
"signature": "async def query(cls, session: ClientSession, word: str) -... | 2 | stack_v2_sparse_classes_30k_test_000374 | Implement the Python class `UrbanDefinition` described below.
Class description:
Represents an Urban Dictionary entry.
Method signatures and docstrings:
- def embed(self) -> Embed: Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.
- async def query(cls, session: ClientSession, word: str) -> Union[None, 'U... | Implement the Python class `UrbanDefinition` described below.
Class description:
Represents an Urban Dictionary entry.
Method signatures and docstrings:
- def embed(self) -> Embed: Makes a :class:``discord.Embed`` from an ``UrbanDefinition``.
- async def query(cls, session: ClientSession, word: str) -> Union[None, 'U... | 5a0e73b8ac71cd3dc0f724f07aff8a54feb69551 | <|skeleton|>
class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
<|body_0|>
async def query(cls, session: ClientSession, word: str) -> Union[None, 'UrbanDefinition']:
"""Que... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UrbanDefinition:
"""Represents an Urban Dictionary entry."""
def embed(self) -> Embed:
"""Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
embed = Embed(title=self.word, description=utils.truncate(self.definition, 2048))
if self.example:
embed.add_field... | the_stack_v2_python_sparse | dog/ext/fun.py | Snarloff/dogbot | train | 1 |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(size, (tuple, list)):\n assert len(size) == 3, 'Size must contain THREE number when it is a tuple or list, got {}.'.format(len(size))\n self.size = size\nelif isinstance(size, int):\n self.size = (size, size, size)\nelse:\n print('Size must be a list or tuple, got {}.'.format(type(size)))... | <|body_start_0|>
if isinstance(size, (tuple, list)):
assert len(size) == 3, 'Size must contain THREE number when it is a tuple or list, got {}.'.format(len(size))
self.size = size
elif isinstance(size, int):
self.size = (size, size, size)
else:
pri... | RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resize至目标尺寸 nonzero_mask,如果为True,则只在label mask有效(非0)区域内进行滑窗 如果为False,则在image整个区域内进行... | RandomCrop4D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomCrop4D:
"""RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resize至目标尺寸 nonzero_mask,如果为True,则只在label m... | stack_v2_sparse_classes_10k_train_001957 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, size, scale=(0.8, 1.2), ratio=(3.0 / 4.0, 4.0 / 3.0), interpolation=1, pre_crop=False, nonzero_mask=False)"
},
{
"docstring": "Get parameters for ``crop`` for a random sized crop. Args: img (numpy ndarray): Image to be c... | 3 | null | Implement the Python class `RandomCrop4D` described below.
Class description:
RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resi... | Implement the Python class `RandomCrop4D` described below.
Class description:
RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resi... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomCrop4D:
"""RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resize至目标尺寸 nonzero_mask,如果为True,则只在label m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomCrop4D:
"""RandomCrop至预设尺寸 scale: 切出cube的体积与原图体积的比值范围 ratio: 切出cube的每一边长的抖动范围 size: resize的目标尺寸 interpolation: [1-5], skimage.zoom的order数。注意分割模式下label的order统一为0 pre_crop: bool,如果为True,则先切一个目标尺寸左右的cube,再resize,通常用于滑窗模式; 如果为False,则从原图上扣一个与原图接近的cube,再resize至目标尺寸 nonzero_mask,如果为True,则只在label mask有效(非0)区域内进... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
5a64418b307c241aac4824f46f6d0041f1222aa9 | [
"QSearchTreeWidget.__init__(self, parent)\nself.header().hide()\nself.setRootIsDecorated(False)\nself.delegate = QAliasParameterTreeWidgetItemDelegate(self, self)\nself.setItemDelegate(self.delegate)\nself.aliasNames = []\nself.itemDoubleClicked.connect(self.changeAlias)",
"self.clear()\nif not pipeline:\n ret... | <|body_start_0|>
QSearchTreeWidget.__init__(self, parent)
self.header().hide()
self.setRootIsDecorated(False)
self.delegate = QAliasParameterTreeWidgetItemDelegate(self, self)
self.setItemDelegate(self.delegate)
self.aliasNames = []
self.itemDoubleClicked.connect(... | QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module | QAliasParameterTreeWidget | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QAliasParameterTreeWidget:
"""QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module"""
def __init__(self, parent=None):
"""QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidget Set up size policy and header"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001958 | 18,014 | permissive | [
{
"docstring": "QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidget Set up size policy and header",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "updateFromPipeline(pipeline: Pipeline) -> None Read the list of aliases and parameters from the... | 3 | stack_v2_sparse_classes_30k_train_000055 | Implement the Python class `QAliasParameterTreeWidget` described below.
Class description:
QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module
Method signatures and docstrings:
- def __init__(self, parent=None): QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidge... | Implement the Python class `QAliasParameterTreeWidget` described below.
Class description:
QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module
Method signatures and docstrings:
- def __init__(self, parent=None): QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidge... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class QAliasParameterTreeWidget:
"""QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module"""
def __init__(self, parent=None):
"""QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidget Set up size policy and header"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QAliasParameterTreeWidget:
"""QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module"""
def __init__(self, parent=None):
"""QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidget Set up size policy and header"""
QSearchTreeWidget.__init__(... | the_stack_v2_python_sparse | vistrails_current/vistrails/gui/mashups/alias_parameter_view.py | lumig242/VisTrailsRecommendation | train | 3 |
3aebed1187e0a3086bc994d64758c0dafedd22af | [
"if root is None:\n return\nif root.left is None and root.right is None:\n res[0] += partial * 10 + root.val\n return\nself.sumNumbersHelper(root.left, partial * 10 + root.val, res)\nself.sumNumbersHelper(root.right, partial * 10 + root.val, res)",
"res = [0]\nself.sumNumbersHelper(root, partial=0, res=r... | <|body_start_0|>
if root is None:
return
if root.left is None and root.right is None:
res[0] += partial * 10 + root.val
return
self.sumNumbersHelper(root.left, partial * 10 + root.val, res)
self.sumNumbersHelper(root.right, partial * 10 + root.val, res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
<|body_0|>
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_001959 | 901 | no_license | [
{
"docstring": "partial is a number, before comming to this level res is a list of one number. We will update that number",
"name": "sumNumbersHelper",
"signature": "def sumNumbersHelper(self, root, partial, res)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers",
... | 2 | stack_v2_sparse_classes_30k_train_003317 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbersHelper(self, root, partial, res): partial is a number, before comming to this level res is a list of one number. We will update that number
- def sumNumbers(self, r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbersHelper(self, root, partial, res): partial is a number, before comming to this level res is a list of one number. We will update that number
- def sumNumbers(self, r... | 6e051eb554d9cf6f424f1e0a77f3072adf7f64c4 | <|skeleton|>
class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
<|body_0|>
def sumNumbers(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbersHelper(self, root, partial, res):
"""partial is a number, before comming to this level res is a list of one number. We will update that number"""
if root is None:
return
if root.left is None and root.right is None:
res[0] += partial * 10 ... | the_stack_v2_python_sparse | 129. Sum Root to Leaf Numbers.py | vincent-kangzhou/LeetCode-Python | train | 0 | |
755736cbfcedd7616f93d2b7c4a148e5548063e4 | [
"gini = GiniFile(filename_or_obj)\ngini_attrs = gini.get_attrs()\ncoords = dict(gini._make_coord_vars() + [gini._make_time_var()])\ncoords['time'] = CFDatetimeCoder().decode(coords['time'])\n(proj_name, proj_var), (data_name, data_var) = gini._make_data_vars()\ndata_var.attrs.pop('coordinates')\ndecoded_data_var = ... | <|body_start_0|>
gini = GiniFile(filename_or_obj)
gini_attrs = gini.get_attrs()
coords = dict(gini._make_coord_vars() + [gini._make_time_var()])
coords['time'] = CFDatetimeCoder().decode(coords['time'])
(proj_name, proj_var), (data_name, data_var) = gini._make_data_vars()
... | Entry point for direct reading of GINI data into Xarray. | GiniXarrayBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GiniXarrayBackend:
"""Entry point for direct reading of GINI data into Xarray."""
def open_dataset(self, filename_or_obj, *, drop_variables=None):
"""Open the GINI datafile as a Xarray dataset. This is the main entrypoint for plugging into Xarray read support."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001960 | 18,582 | permissive | [
{
"docstring": "Open the GINI datafile as a Xarray dataset. This is the main entrypoint for plugging into Xarray read support.",
"name": "open_dataset",
"signature": "def open_dataset(self, filename_or_obj, *, drop_variables=None)"
},
{
"docstring": "Try to guess whether we can read this file. T... | 2 | stack_v2_sparse_classes_30k_train_000666 | Implement the Python class `GiniXarrayBackend` described below.
Class description:
Entry point for direct reading of GINI data into Xarray.
Method signatures and docstrings:
- def open_dataset(self, filename_or_obj, *, drop_variables=None): Open the GINI datafile as a Xarray dataset. This is the main entrypoint for p... | Implement the Python class `GiniXarrayBackend` described below.
Class description:
Entry point for direct reading of GINI data into Xarray.
Method signatures and docstrings:
- def open_dataset(self, filename_or_obj, *, drop_variables=None): Open the GINI datafile as a Xarray dataset. This is the main entrypoint for p... | c7124e6f375eb5810ce49d53c9d5501c2efdfb75 | <|skeleton|>
class GiniXarrayBackend:
"""Entry point for direct reading of GINI data into Xarray."""
def open_dataset(self, filename_or_obj, *, drop_variables=None):
"""Open the GINI datafile as a Xarray dataset. This is the main entrypoint for plugging into Xarray read support."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GiniXarrayBackend:
"""Entry point for direct reading of GINI data into Xarray."""
def open_dataset(self, filename_or_obj, *, drop_variables=None):
"""Open the GINI datafile as a Xarray dataset. This is the main entrypoint for plugging into Xarray read support."""
gini = GiniFile(filename_... | the_stack_v2_python_sparse | src/metpy/io/gini.py | Unidata/MetPy | train | 1,041 |
01cda23f1541d885ff24899f2d840e19b88284b3 | [
"result = []\nfor i in range(0, len(nums) + 1):\n result += self.combinationSolo(nums, i)\nreturn result",
"nums = sorted(nums)\nif k == 0:\n return [[]]\nelif k == len(nums):\n return [nums]\nelif k == 1:\n result = []\n for i in nums:\n if [i] not in result:\n result.append([i])... | <|body_start_0|>
result = []
for i in range(0, len(nums) + 1):
result += self.combinationSolo(nums, i)
return result
<|end_body_0|>
<|body_start_1|>
nums = sorted(nums)
if k == 0:
return [[]]
elif k == len(nums):
return [nums]
... | Solution_B | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove duplicated on the run"""
<|body_0|>
def combinationSolo(self, nums: List[int], k: int) -> ... | stack_v2_sparse_classes_10k_train_001961 | 4,175 | permissive | [
{
"docstring": "With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove duplicated on the run",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Helper for A1, refer to LC0... | 2 | stack_v2_sparse_classes_30k_test_000020 | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove dupl... | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove dupl... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove duplicated on the run"""
<|body_0|>
def combinationSolo(self, nums: List[int], k: int) -> ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_B:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""With the help from the combinationSolo from Leetcode LC077 no need to use tuple, direct use list and remove duplicated on the run"""
result = []
for i in range(0, len(nums) + 1):
result += self.com... | the_stack_v2_python_sparse | LeetCode/LC090_subsets_ii.py | jxie0755/Learning_Python | train | 0 | |
5d515b05714c524a6c42646fa26afae38e68c618 | [
"test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)\nerr_path = self.get_error_path()\nfor id, ch in self._channels.items():\n res, tr = ch.check(self)\n aux = {err_path + 'Ch{}_{}'.format(id, err): val for err, val in tr.items()}\n traceback.update(aux)\n test &= res\nreturn (te... | <|body_start_0|>
test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)
err_path = self.get_error_path()
for id, ch in self._channels.items():
res, tr = ch.check(self)
aux = {err_path + 'Ch{}_{}'.format(id, err): val for err, val in tr.items()}
... | Set the parameters of the different channels of the AWG. | SetAWGParametersTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
<|body_0|>
def register_preferences(self):
"""Overriden to handle channels."""
<|bod... | stack_v2_sparse_classes_10k_train_001962 | 8,675 | permissive | [
{
"docstring": "Automatically test all parameters evaluation.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
},
{
"docstring": "Overriden to handle channels.",
"name": "register_preferences",
"signature": "def register_preferences(self)"
},
{
"docstring": "Han... | 4 | stack_v2_sparse_classes_30k_train_005556 | Implement the Python class `SetAWGParametersTask` described below.
Class description:
Set the parameters of the different channels of the AWG.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Automatically test all parameters evaluation.
- def register_preferences(self): Overriden to handle chann... | Implement the Python class `SetAWGParametersTask` described below.
Class description:
Set the parameters of the different channels of the AWG.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Automatically test all parameters evaluation.
- def register_preferences(self): Overriden to handle chann... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
<|body_0|>
def register_preferences(self):
"""Overriden to handle channels."""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SetAWGParametersTask:
"""Set the parameters of the different channels of the AWG."""
def check(self, *args, **kwargs):
"""Automatically test all parameters evaluation."""
test, traceback = super(SetAWGParametersTask, self).check(*args, **kwargs)
err_path = self.get_error_path()
... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/instr/set_awg_parameters.py | Exopy/exopy_hqc_legacy | train | 0 |
acdeb0ae8076e8448f8140d5ec45e7c45216eeee | [
"req_body = cli.make_body(managementAddress=management_address, localUsername=local_username, localPassword=local_password, remoteUsername=remote_username, remotePassword=remote_password, connectionType=connection_type)\nresp = cli.post(cls().resource_class, **req_body)\nresp.raise_if_err()\nreturn cls.get(cli, res... | <|body_start_0|>
req_body = cli.make_body(managementAddress=management_address, localUsername=local_username, localPassword=local_password, remoteUsername=remote_username, remotePassword=remote_password, connectionType=connection_type)
resp = cli.post(cls().resource_class, **req_body)
resp.raise... | UnityRemoteSystem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param manag... | stack_v2_sparse_classes_10k_train_001963 | 3,443 | permissive | [
{
"docstring": "Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param management_address: the management IP address of the remote system. :param local_username: administrative username of local system. :param local_password: administrative password of loc... | 3 | stack_v2_sparse_classes_30k_train_006349 | Implement the Python class `UnityRemoteSystem` described below.
Class description:
Implement the UnityRemoteSystem class.
Method signatures and docstrings:
- def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): Configures... | Implement the Python class `UnityRemoteSystem` described below.
Class description:
Implement the UnityRemoteSystem class.
Method signatures and docstrings:
- def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): Configures... | ccfccba0bceda34c0d5dc8105c95731036f4e955 | <|skeleton|>
class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param manag... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param management_address:... | the_stack_v2_python_sparse | storops/unity/resource/remote_system.py | emc-openstack/storops | train | 61 | |
0101cb4e170a8d168a24134fee231c0d44274d44 | [
"try:\n self.network_driver.apply_qos_on_port(qos_policy_id, amp_data[constants.VRRP_PORT_ID])\nexcept Exception:\n if not is_revert:\n raise\n LOG.warning('Failed to undo qos policy %(qos_id)s on vrrp port: %(port)s from amphorae: %(amp)s', {'qos_id': request_qos_id, 'port': amp_data[constants.VRRP... | <|body_start_0|>
try:
self.network_driver.apply_qos_on_port(qos_policy_id, amp_data[constants.VRRP_PORT_ID])
except Exception:
if not is_revert:
raise
LOG.warning('Failed to undo qos policy %(qos_id)s on vrrp port: %(port)s from amphorae: %(amp)s', {'q... | Apply Quality of Services to the VIP | ApplyQosAmphora | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplyQosAmphora:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
<|body_0|>
def execute(self, loadb... | stack_v2_sparse_classes_10k_train_001964 | 44,034 | permissive | [
{
"docstring": "Call network driver to apply QoS Policy on the vrrp ports.",
"name": "_apply_qos_on_vrrp_port",
"signature": "def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None)"
},
{
"docstring": "Apply qos policy on the vrrp ports whic... | 3 | null | Implement the Python class `ApplyQosAmphora` described below.
Class description:
Apply Quality of Services to the VIP
Method signatures and docstrings:
- def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ... | Implement the Python class `ApplyQosAmphora` described below.
Class description:
Apply Quality of Services to the VIP
Method signatures and docstrings:
- def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class ApplyQosAmphora:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
<|body_0|>
def execute(self, loadb... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApplyQosAmphora:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_port(self, loadbalancer, amp_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
try:
self.network_driver.apply_qos_on_po... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/network_tasks.py | openstack/octavia | train | 147 |
c94b6162201b3f3ad180d02919b9f005cff7b750 | [
"self.head = ListNode(0)\ndummy = self.head\nfor i in range(1, maxNumbers):\n dummy.next = ListNode(i)\n dummy = dummy.next",
"if self.head:\n val, self.head = (self.head.val, self.head.next)\nelse:\n val = -1\nreturn val",
"dummy = self.head\nwhile dummy:\n if dummy.val == number:\n retur... | <|body_start_0|>
self.head = ListNode(0)
dummy = self.head
for i in range(1, maxNumbers):
dummy.next = ListNode(i)
dummy = dummy.next
<|end_body_0|>
<|body_start_1|>
if self.head:
val, self.head = (self.head.val, self.head.next)
else:
... | PhoneDirectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_10k_train_001965 | 1,715 | no_license | [
{
"docstring": "Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.",
"name": "__init__",
"signature": "def __init__(self, maxNumbers: int)"
},
{
"docstring": "Provide a number which is not assigned to anyone. @return - Return an... | 4 | null | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | 00bf9a8164008aa17507b1c87ce72a3374bcb7b9 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
self.head = ListNode(0)
dummy = self.head
for i in range(1, maxNumbers):
dummy.next = Li... | the_stack_v2_python_sparse | solutions/379.design-phone-directory.py | quixoteji/Leetcode | train | 1 | |
cefbd0464db5762ad670394baf0502c961302603 | [
"self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.gram = Unit.objects.create(name='gram', caffe=self.caffe)\nU... | <|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')
self.gram = Unit.objects.create... | Unit tests. | UnitModelTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitModelTest:
"""Unit tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_unit(self):
"""Check creating units."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', stre... | stack_v2_sparse_classes_10k_train_001966 | 14,711 | permissive | [
{
"docstring": "Test data setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check creating units.",
"name": "test_unit",
"signature": "def test_unit(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002130 | Implement the Python class `UnitModelTest` described below.
Class description:
Unit tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_unit(self): Check creating units. | Implement the Python class `UnitModelTest` described below.
Class description:
Unit tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_unit(self): Check creating units.
<|skeleton|>
class UnitModelTest:
"""Unit tests."""
def setUp(self):
"""Test data setup."""
... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class UnitModelTest:
"""Unit tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_unit(self):
"""Check creating units."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnitModelTest:
"""Unit tests."""
def setUp(self):
"""Test data setup."""
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', h... | the_stack_v2_python_sparse | caffe/reports/test_models.py | VirrageS/io-kawiarnie | train | 3 |
660a39530aa637823311a8cc9e113bf07aeaba00 | [
"self.edges = edges\nself.t_width = t_width\nself.t_height = t_height\nwidth = t_width - 2 * border\nheight = t_height - 2 * border\nassert width >= 1\nassert height >= 1\nx_coords, y_coords = zip(*points)\nunscaled_width = max(x_coords) - min(x_coords)\nunscaled_height = max(y_coords) - min(y_coords)\nc_width = wi... | <|body_start_0|>
self.edges = edges
self.t_width = t_width
self.t_height = t_height
width = t_width - 2 * border
height = t_height - 2 * border
assert width >= 1
assert height >= 1
x_coords, y_coords = zip(*points)
unscaled_width = max(x_coords) - ... | This used to be a single function but there is too much going on in it. | ImgHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels ... | stack_v2_sparse_classes_10k_train_001967 | 13,149 | no_license | [
{
"docstring": "@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels @param t_height: the image height in pixels @param border: the width and height of the image border in pixels",
"name": "__init__",
"signature": "def __init__... | 3 | null | Implement the Python class `ImgHelper` described below.
Class description:
This used to be a single function but there is too much going on in it.
Method signatures and docstrings:
- def __init__(self, points, edges, t_width, t_height, border): @param points: an ordered list of (x, y) pairs @param edges: a set of poi... | Implement the Python class `ImgHelper` described below.
Class description:
This used to be a single function but there is too much going on in it.
Method signatures and docstrings:
- def __init__(self, points, edges, t_width, t_height, border): @param points: an ordered list of (x, y) pairs @param edges: a set of poi... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels @param t_heig... | the_stack_v2_python_sparse | 20100817b.py | argriffing/xgcode | train | 1 |
07e722aad14f035fc6c4408b2b49093b6fcc10f9 | [
"super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes)\nself.compute_per_class_metrics = compute_per_class_metrics\nself.zero_division = zero_division\nself.num_classes = num_classes\nself.reset()",
"kv_metrics = {}\nfor aggregation_name, aggregated_metrics in zi... | <|body_start_0|>
super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, num_classes=num_classes)
self.compute_per_class_metrics = compute_per_class_metrics
self.zero_division = zero_division
self.num_classes = num_classes
self.reset()
<|end_body_0|>
<|bo... | Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, allows compute metric's value on call compute_per_class_metrics: bool... | MultilabelPrecisionRecallF1SupportMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, a... | stack_v2_sparse_classes_10k_train_001968 | 34,447 | permissive | [
{
"docstring": "Init PrecisionRecallF1SupportMetric instance",
"name": "__init__",
"signature": "def __init__(self, zero_division: int=0, compute_on_call: bool=True, compute_per_class_metrics: bool=SETTINGS.compute_per_class_metrics, prefix: str=None, suffix: str=None, num_classes: Optional[int]=None) -... | 6 | stack_v2_sparse_classes_30k_train_005792 | Implement the Python class `MultilabelPrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be on... | Implement the Python class `MultilabelPrecisionRecallF1SupportMetric` described below.
Class description:
Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be on... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultilabelPrecisionRecallF1SupportMetric:
"""Metric that can collect statistics and count precision, recall, f1_score and support with it. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, allows compute... | the_stack_v2_python_sparse | catalyst/metrics/_classification.py | catalyst-team/catalyst | train | 3,038 |
4763bebac4d86b4e61cbce3d297de04ebbcc7d01 | [
"self.domain_obj = domains.ProdDiscreteNumericDomain([[4.3, 2.1, 9.8, 10], [11.2, -23.1, 19.8], [1123, 213, 1980, 1.1]])\nself.points = [[2.1, -23.1, 1980], (10, 11.2, 1.1), [9.8, 19.8, 1123]]\nself.non_points = [[2.1 - 13.1, 1980], ('kky', 11.2, 1.1), [9.8, 19.8, 1123, 21]]",
"self.report('Testing if exception i... | <|body_start_0|>
self.domain_obj = domains.ProdDiscreteNumericDomain([[4.3, 2.1, 9.8, 10], [11.2, -23.1, 19.8], [1123, 213, 1980, 1.1]])
self.points = [[2.1, -23.1, 1980], (10, 11.2, 1.1), [9.8, 19.8, 1123]]
self.non_points = [[2.1 - 13.1, 1980], ('kky', 11.2, 1.1), [9.8, 19.8, 1123, 21]]
<|end_... | ProdDiscreteDomain Domain. | ProdDiscreteNumericDomain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProdDiscreteNumericDomain:
"""ProdDiscreteDomain Domain."""
def _child_set_up(self):
"""Child set up."""
<|body_0|>
def test_non_numeric_prod_discrete_domain(self):
"""Constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.domain_obj ... | stack_v2_sparse_classes_10k_train_001969 | 5,755 | permissive | [
{
"docstring": "Child set up.",
"name": "_child_set_up",
"signature": "def _child_set_up(self)"
},
{
"docstring": "Constructor.",
"name": "test_non_numeric_prod_discrete_domain",
"signature": "def test_non_numeric_prod_discrete_domain(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002783 | Implement the Python class `ProdDiscreteNumericDomain` described below.
Class description:
ProdDiscreteDomain Domain.
Method signatures and docstrings:
- def _child_set_up(self): Child set up.
- def test_non_numeric_prod_discrete_domain(self): Constructor. | Implement the Python class `ProdDiscreteNumericDomain` described below.
Class description:
ProdDiscreteDomain Domain.
Method signatures and docstrings:
- def _child_set_up(self): Child set up.
- def test_non_numeric_prod_discrete_domain(self): Constructor.
<|skeleton|>
class ProdDiscreteNumericDomain:
"""ProdDis... | 3eef7d30bcc2e56f2221a624bd8ec7f933f81e40 | <|skeleton|>
class ProdDiscreteNumericDomain:
"""ProdDiscreteDomain Domain."""
def _child_set_up(self):
"""Child set up."""
<|body_0|>
def test_non_numeric_prod_discrete_domain(self):
"""Constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProdDiscreteNumericDomain:
"""ProdDiscreteDomain Domain."""
def _child_set_up(self):
"""Child set up."""
self.domain_obj = domains.ProdDiscreteNumericDomain([[4.3, 2.1, 9.8, 10], [11.2, -23.1, 19.8], [1123, 213, 1980, 1.1]])
self.points = [[2.1, -23.1, 1980], (10, 11.2, 1.1), [9.8... | the_stack_v2_python_sparse | dragonfly/exd/unittest_domains.py | dragonfly/dragonfly | train | 868 |
a0bb364f699895722d5ab88777a41059245036bd | [
"dummy_node = ListNode(-1)\ndummy_node.next = head\npre_node = dummy_node\ncur_node = dummy_node.next\nwhile cur_node:\n if cur_node.val == val:\n pre_node.next = cur_node.next\n break\n pre_node = cur_node\n cur_node = cur_node.next\nreturn dummy_node.next",
"if head.val == val:\n retur... | <|body_start_0|>
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
pre_node.next = cur_node.next
break
pre_node = cur_node
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy_nod... | stack_v2_sparse_classes_10k_train_001970 | 1,496 | no_license | [
{
"docstring": "使用了虚拟头节点,因为匹配的值可能是第一个。",
"name": "deleteNode2",
"signature": "def deleteNode2(self, head: ListNode, val: int) -> ListNode"
},
{
"docstring": "如果匹配的值是第一个直接返回即可.",
"name": "deleteNode",
"signature": "def deleteNode(self, head: ListNode, val: int) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_001573 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可.
<|skeleton|>
... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 18. 删除链表的节点.py | tenqaz/crazy_arithmetic | train | 0 | |
4921da7ce88afd440d097cc404d7f4dd8e132cd1 | [
"for case in self.__class__.SCALES:\n with self.subTest(case=case):\n self.assertEqual(colors.merge_colors(case[0][0], case[0][1]), case[1])",
"for case in self.__class__.TEXTS:\n with self.subTest(case=case):\n self.assertEqual(colors.color_str_to_trio(case[0]), case[1])",
"for case in self... | <|body_start_0|>
for case in self.__class__.SCALES:
with self.subTest(case=case):
self.assertEqual(colors.merge_colors(case[0][0], case[0][1]), case[1])
<|end_body_0|>
<|body_start_1|>
for case in self.__class__.TEXTS:
with self.subTest(case=case):
... | Tests for color-related helper functions. | TestColors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestColors:
"""Tests for color-related helper functions."""
def test_merge_colors(self):
"""Test blending colors together."""
<|body_0|>
def test_color_str_to_trio(self):
"""Test converting color text codes to integer trios."""
<|body_1|>
def test_co... | stack_v2_sparse_classes_10k_train_001971 | 1,921 | no_license | [
{
"docstring": "Test blending colors together.",
"name": "test_merge_colors",
"signature": "def test_merge_colors(self)"
},
{
"docstring": "Test converting color text codes to integer trios.",
"name": "test_color_str_to_trio",
"signature": "def test_color_str_to_trio(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004126 | Implement the Python class `TestColors` described below.
Class description:
Tests for color-related helper functions.
Method signatures and docstrings:
- def test_merge_colors(self): Test blending colors together.
- def test_color_str_to_trio(self): Test converting color text codes to integer trios.
- def test_color_... | Implement the Python class `TestColors` described below.
Class description:
Tests for color-related helper functions.
Method signatures and docstrings:
- def test_merge_colors(self): Test blending colors together.
- def test_color_str_to_trio(self): Test converting color text codes to integer trios.
- def test_color_... | 539868dab2041b7694c0d53e8e74cf1b5b033653 | <|skeleton|>
class TestColors:
"""Tests for color-related helper functions."""
def test_merge_colors(self):
"""Test blending colors together."""
<|body_0|>
def test_color_str_to_trio(self):
"""Test converting color text codes to integer trios."""
<|body_1|>
def test_co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestColors:
"""Tests for color-related helper functions."""
def test_merge_colors(self):
"""Test blending colors together."""
for case in self.__class__.SCALES:
with self.subTest(case=case):
self.assertEqual(colors.merge_colors(case[0][0], case[0][1]), case[1])... | the_stack_v2_python_sparse | test_igseq/test_colors.py | ShawHahnLab/igseq | train | 1 |
95328ba825f7ed1978fcb69c68ec5a821f6f7f6b | [
"if s == '':\n if p == '' or p == '*':\n return True\n return False\nif p == '':\n if s != '':\n return False\ns_l = len(s)\np_l = len(p)\nmatrix = [[0 for _ in range(s_l + 1)] for _ in range(p_l + 1)]\nmatrix[0][0] = 1\nfor i in range(1, p_l + 1):\n for j in range(0, s_l + 1):\n p_... | <|body_start_0|>
if s == '':
if p == '' or p == '*':
return True
return False
if p == '':
if s != '':
return False
s_l = len(s)
p_l = len(p)
matrix = [[0 for _ in range(s_l + 1)] for _ in range(p_l + 1)]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch2(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
if p == '' or p ==... | stack_v2_sparse_classes_10k_train_001972 | 2,719 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch2",
"signature": "def isMatch2(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007233 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch2(self, s, p): :type s: str :type p: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch2(self, s, p): :type s: str :type p: str :rtype: bool
<|skeleton|>
class Solution:
def isMatch(... | 707829268535a80cfe0ffa1dc0623520c3fcbecf | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch2(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
if s == '':
if p == '' or p == '*':
return True
return False
if p == '':
if s != '':
return False
s_l = len(s)
p_l = len(p... | the_stack_v2_python_sparse | leetcode/1-50/_44_isMatch.py | blackwings001/algorithm | train | 0 | |
612474ec474c976d80b4bd68a95b3d59746fea29 | [
"json_str = request.body\njson_obj = json.loads(json_str)\nreceiver = json_obj['receiver']\nreceiver_phone = json_obj['receiver_phone']\naddress = json_obj['address']\npostcode = json_obj['postcode']\ntag = json_obj['tag']\nuser = request.myuser\nold_address = Address.objects.filter(username=user, is_active=True)\n... | <|body_start_0|>
json_str = request.body
json_obj = json.loads(json_str)
receiver = json_obj['receiver']
receiver_phone = json_obj['receiver_phone']
address = json_obj['address']
postcode = json_obj['postcode']
tag = json_obj['tag']
user = request.myuser
... | AddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressView:
def post(self, request, username):
"""新建地址"""
<|body_0|>
def get(self, request, username):
"""查看地址"""
<|body_1|>
def put(self, request, address_id, username):
"""修改地址"""
<|body_2|>
def delete(self, request, username, add... | stack_v2_sparse_classes_10k_train_001973 | 10,804 | no_license | [
{
"docstring": "新建地址",
"name": "post",
"signature": "def post(self, request, username)"
},
{
"docstring": "查看地址",
"name": "get",
"signature": "def get(self, request, username)"
},
{
"docstring": "修改地址",
"name": "put",
"signature": "def put(self, request, address_id, usern... | 4 | stack_v2_sparse_classes_30k_train_000294 | Implement the Python class `AddressView` described below.
Class description:
Implement the AddressView class.
Method signatures and docstrings:
- def post(self, request, username): 新建地址
- def get(self, request, username): 查看地址
- def put(self, request, address_id, username): 修改地址
- def delete(self, request, username, ... | Implement the Python class `AddressView` described below.
Class description:
Implement the AddressView class.
Method signatures and docstrings:
- def post(self, request, username): 新建地址
- def get(self, request, username): 查看地址
- def put(self, request, address_id, username): 修改地址
- def delete(self, request, username, ... | de9776bad68fcb25a7dbe8b1767e9df980a8b83c | <|skeleton|>
class AddressView:
def post(self, request, username):
"""新建地址"""
<|body_0|>
def get(self, request, username):
"""查看地址"""
<|body_1|>
def put(self, request, address_id, username):
"""修改地址"""
<|body_2|>
def delete(self, request, username, add... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddressView:
def post(self, request, username):
"""新建地址"""
json_str = request.body
json_obj = json.loads(json_str)
receiver = json_obj['receiver']
receiver_phone = json_obj['receiver_phone']
address = json_obj['address']
postcode = json_obj['postcode']
... | the_stack_v2_python_sparse | fruit_vegetable/user/views.py | txd-git/fruit_vegetables | train | 0 | |
3ba226bd8235087e580332fb2c887692ffb2d073 | [
"self.dest_db_name = dest_db_name\nself.dest_edb_filepath = dest_edb_filepath\nself.dest_log_dirpath = dest_log_dirpath\nself.entity_id = entity_id\nself.mount_db = mount_db\nself.progress_monitor_path = progress_monitor_path\nself.restore_as_recovery_db = restore_as_recovery_db\nself.target_host_entity = target_ho... | <|body_start_0|>
self.dest_db_name = dest_db_name
self.dest_edb_filepath = dest_edb_filepath
self.dest_log_dirpath = dest_log_dirpath
self.entity_id = entity_id
self.mount_db = mount_db
self.progress_monitor_path = progress_monitor_path
self.restore_as_recovery_db... | Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example: e:\\myexchange\\hrdb\\hr_db.edb. dest_log_dirpath (string): Target LOG dir path. Example: e:\\myexchang... | RestoreExchangeParams_DatabaseOptions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreExchangeParams_DatabaseOptions:
"""Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example: e:\\myexchange\\hrdb\\hr_db.edb. dest_... | stack_v2_sparse_classes_10k_train_001974 | 4,408 | permissive | [
{
"docstring": "Constructor for the RestoreExchangeParams_DatabaseOptions class",
"name": "__init__",
"signature": "def __init__(self, dest_db_name=None, dest_edb_filepath=None, dest_log_dirpath=None, entity_id=None, mount_db=None, progress_monitor_path=None, restore_as_recovery_db=None, target_host_ent... | 2 | null | Implement the Python class `RestoreExchangeParams_DatabaseOptions` described below.
Class description:
Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example:... | Implement the Python class `RestoreExchangeParams_DatabaseOptions` described below.
Class description:
Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example:... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreExchangeParams_DatabaseOptions:
"""Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example: e:\\myexchange\\hrdb\\hr_db.edb. dest_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreExchangeParams_DatabaseOptions:
"""Implementation of the 'RestoreExchangeParams_DatabaseOptions' model. TODO: type description here. Attributes: dest_db_name (string): Destination Database Name dest_edb_filepath (string): Target EDB dir path. Example: e:\\myexchange\\hrdb\\hr_db.edb. dest_log_dirpath (... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_exchange_params_database_options.py | cohesity/management-sdk-python | train | 24 |
dd3a6d3378d1f21e072c9b0411a2059d9e429d9e | [
"self.device_tree = device_tree\nself.logical_volume_name = logical_volume_name\nself.logical_volume_uuid = logical_volume_uuid\nself.volume_group_name = volume_group_name\nself.volume_group_uuid = volume_group_uuid",
"if dictionary is None:\n return None\ndevice_tree = cohesity_management_sdk.models.device_tr... | <|body_start_0|>
self.device_tree = device_tree
self.logical_volume_name = logical_volume_name
self.logical_volume_uuid = logical_volume_uuid
self.volume_group_name = volume_group_name
self.volume_group_uuid = volume_group_uuid
<|end_body_0|>
<|body_start_1|>
if dictiona... | Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_volume_name (string): Logical volume name. logical_volume... | VolumeInfo_LogicalVolumeInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_v... | stack_v2_sparse_classes_10k_train_001975 | 2,832 | permissive | [
{
"docstring": "Constructor for the VolumeInfo_LogicalVolumeInfo class",
"name": "__init__",
"signature": "def __init__(self, device_tree=None, logical_volume_name=None, logical_volume_uuid=None, volume_group_name=None, volume_group_uuid=None)"
},
{
"docstring": "Creates an instance of this mode... | 2 | null | Implement the Python class `VolumeInfo_LogicalVolumeInfo` described below.
Class description:
Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions t... | Implement the Python class `VolumeInfo_LogicalVolumeInfo` described below.
Class description:
Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_volume_name (s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/volume_info_logical_volume_info.py | cohesity/management-sdk-python | train | 24 |
1b86360c2208d537ab4c1ffa5b47c0ea9bd70823 | [
"super().__init__(econet_device)\nself.entity_description = description\nself._attr_name = f'{econet_device.device_name}_{description.name}'\nself._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'",
"value = getattr(self._econet, self.entity_description.key)\nif self.en... | <|body_start_0|>
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{description.name}'
self._attr_unique_id = f'{econet_device.device_id}_{econet_device.device_name}_{description.name}'
<|end_body_0|>
<|body_start_1|>
... | Define a Econet sensor. | EcoNetSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_001976 | 4,025 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None"
},
{
"docstring": "Return sensors state.",
"name": "native_value",
"signature": "def native_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002031 | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state. | Implement the Python class `EcoNetSensor` described below.
Class description:
Define a Econet sensor.
Method signatures and docstrings:
- def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None: Initialize.
- def native_value(self): Return sensors state.
<|skeleton|>
class EcoNetSe... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def native_value(self):
"""Return sensors state."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EcoNetSensor:
"""Define a Econet sensor."""
def __init__(self, econet_device: Equipment, description: SensorEntityDescription) -> None:
"""Initialize."""
super().__init__(econet_device)
self.entity_description = description
self._attr_name = f'{econet_device.device_name}_{... | the_stack_v2_python_sparse | homeassistant/components/econet/sensor.py | home-assistant/core | train | 35,501 |
9cfa265a1dbfe5f394575eb74dc3fca408a743a5 | [
"sigma_rules = []\nall_sigma_rules = SigmaRule.query.all()\nfor rule in all_sigma_rules:\n sigma_rules.append(ts_sigma_lib.enrich_sigma_rule_object(rule=rule, parse_yaml=False))\nmeta = {'rules_count': len(sigma_rules)}\nreturn jsonify({'objects': sigma_rules, 'meta': meta})",
"rule_yaml = request.json.get('ru... | <|body_start_0|>
sigma_rules = []
all_sigma_rules = SigmaRule.query.all()
for rule in all_sigma_rules:
sigma_rules.append(ts_sigma_lib.enrich_sigma_rule_object(rule=rule, parse_yaml=False))
meta = {'rules_count': len(sigma_rules)}
return jsonify({'objects': sigma_rule... | Resource to get list of all SigmaRules. | SigmaRuleListResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SigmaRuleListResource:
"""Resource to get list of all SigmaRules."""
def get(self):
"""Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representations of the rules. Returns: List of sigma rules represented... | stack_v2_sparse_classes_10k_train_001977 | 12,205 | permissive | [
{
"docstring": "Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representations of the rules. Returns: List of sigma rules represented in JSON e.g. {\"objects\": [sigma_rules], \"meta\": {\"rules_count\": 42}.",
"name": "get",
... | 2 | null | Implement the Python class `SigmaRuleListResource` described below.
Class description:
Resource to get list of all SigmaRules.
Method signatures and docstrings:
- def get(self): Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representatio... | Implement the Python class `SigmaRuleListResource` described below.
Class description:
Resource to get list of all SigmaRules.
Method signatures and docstrings:
- def get(self): Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representatio... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SigmaRuleListResource:
"""Resource to get list of all SigmaRules."""
def get(self):
"""Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representations of the rules. Returns: List of sigma rules represented... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SigmaRuleListResource:
"""Resource to get list of all SigmaRules."""
def get(self):
"""Fetches Sigma rules from the database. Fetches all Sigma rules stored in the database on the system and returns a list of JSON representations of the rules. Returns: List of sigma rules represented in JSON e.g.... | the_stack_v2_python_sparse | timesketch/api/v1/resources/sigma.py | google/timesketch | train | 2,263 |
a4957e869e3ce074b3e14fc167c0652f5637f5dd | [
"def dfs(node):\n nonlocal ans\n if not node:\n ans += 'None,'\n return\n ans += str(node.val) + ','\n dfs(node.left)\n dfs(node.right)\nans = ''\ndfs(root)\nreturn ans",
"def dfs(queue):\n if queue[0] == 'None':\n queue.popleft()\n return None\n node = TreeNode(qu... | <|body_start_0|>
def dfs(node):
nonlocal ans
if not node:
ans += 'None,'
return
ans += str(node.val) + ','
dfs(node.left)
dfs(node.right)
ans = ''
dfs(root)
return ans
<|end_body_0|>
<|body_start... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node):
nonlocal ans
... | stack_v2_sparse_classes_10k_train_001978 | 949 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005668 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string.
- def deserialize(self, data): Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string.
- def deserialize(self, data): Decodes your encoded data to tree.
<|skeleton|>
class Codec:
def serialize(self, root... | 03afae2bf1407b8cf81e5e642f6d62ad4238dfe3 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
def dfs(node):
nonlocal ans
if not node:
ans += 'None,'
return
ans += str(node.val) + ','
dfs(node.left)
dfs(node.right)
... | the_stack_v2_python_sparse | data_structures/trees/04_serialize_deserialize.py | juanjones5/cs-concepts | train | 0 | |
4bf7aebc5baaa5224d030607aa79889a5b515035 | [
"directory_path = Path(directory_path)\noutput_path = Path(output_path)\narchive_file_extension = 'tar' if cls._MODE_STRING == '' else f'tar.{cls._MODE_STRING}'\narchive_path = output_path / f'{directory_path.stem}.{archive_file_extension}'\nwith tarfile.open(archive_path, f'w:{cls._MODE_STRING}') as tar_file:\n ... | <|body_start_0|>
directory_path = Path(directory_path)
output_path = Path(output_path)
archive_file_extension = 'tar' if cls._MODE_STRING == '' else f'tar.{cls._MODE_STRING}'
archive_path = output_path / f'{directory_path.stem}.{archive_file_extension}'
with tarfile.open(archive_... | A static class for managing tar archives. | _TarArchiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TarArchiver:
"""A static class for managing tar archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_10k_train_001979 | 7,567 | permissive | [
{
"docstring": "Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_path: The directory with the files to archive. :param output_path: The output path to store the created archive file. :return: The crea... | 2 | stack_v2_sparse_classes_30k_train_002675 | Implement the Python class `_TarArchiver` described below.
Class description:
A static class for managing tar archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | Implement the Python class `_TarArchiver` described below.
Class description:
A static class for managing tar archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _TarArchiver:
"""A static class for managing tar archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _TarArchiver:
"""A static class for managing tar archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_... | the_stack_v2_python_sparse | mlrun/package/utils/_archiver.py | mlrun/mlrun | train | 1,093 |
2738a587cdebd824e5a118e99e4aefeb834e1e21 | [
"super(MBConv, self).__init__()\nif norm_layer is None:\n norm_layer = nn.BatchNorm2d\nif act_layer is None:\n act_layer = nn.ReLU6\nif kernel_size == 3:\n conv_dw = conv3x3\nelif kernel_size == 5:\n conv_dw = conv5x5\nelse:\n raise ValueError('MBConv class only supports kernel size 3x3, 5x5')\nself.... | <|body_start_0|>
super(MBConv, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if act_layer is None:
act_layer = nn.ReLU6
if kernel_size == 3:
conv_dw = conv3x3
elif kernel_size == 5:
conv_dw = conv5x5
el... | mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K: input channels; K': output channe... | MBConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K:... | stack_v2_sparse_classes_10k_train_001980 | 20,656 | no_license | [
{
"docstring": "Constructor Args: inplanes: (int) number of input channels outplanes: (int) number of output channels expansion: (int) expansion factor for inverted residuals kernel_size: (int) 3x3 or 5x5 conv-dw filter stride: (int) stride for conv-dw filter dropout: (float) p = dropout; default = 0 (no dropou... | 2 | stack_v2_sparse_classes_30k_train_000526 | Implement the Python class `MBConv` described below.
Class description:
mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s ... | Implement the Python class `MBConv` described below.
Class description:
mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s ... | a0c51824b9c4c458918ef9a40a925cd576137d75 | <|skeleton|>
class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MBConv:
"""mobile-inverted-bottleneck block structure: - 1x1-conv > bn > relu > 3x3/5x5-conv-dw > bn > relu > (optional) SE > 1x1-conv > bn options: - SE optimization - kernel_sizes: 3x3, 5x5 - expansion factor > 1 notes: - input: H x H x K; bottleneck: H/s x H/s x tK; output: H/s x H/s x K' - K: input channe... | the_stack_v2_python_sparse | model/mnasnet.py | baihuaxie/ConvLab | train | 0 |
77b4fa5853a57fc81e6d0349b8dbfa99548d4bc0 | [
"self.warmup = warmup\nself.n_steps = n_steps\nsuper().__init__(optimizer, lr_lambda=self.lr_lambda, last_epoch=-1)",
"if step < self.warmup:\n return float(step) / float(max(1, self.warmup))\nreturn max(0.0, float(self.n_steps - step) / float(max(1.0, self.n_steps - self.warmup)))"
] | <|body_start_0|>
self.warmup = warmup
self.n_steps = n_steps
super().__init__(optimizer, lr_lambda=self.lr_lambda, last_epoch=-1)
<|end_body_0|>
<|body_start_1|>
if step < self.warmup:
return float(step) / float(max(1, self.warmup))
return max(0.0, float(self.n_steps... | Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used after every training batch. | WarmupLinearScheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarmupLinearScheduler:
"""Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used after every training batch."""
de... | stack_v2_sparse_classes_10k_train_001981 | 1,483 | permissive | [
{
"docstring": "Initialize the WarmupLinearScheduler. Parameters ---------- optimizer : torch.optim.Optimizer Wrapped optimizer. warmup : int The number of linear warmup phases n_steps : int, optional The index of last step. Default: -1",
"name": "__init__",
"signature": "def __init__(self, optimizer, w... | 2 | stack_v2_sparse_classes_30k_train_005694 | Implement the Python class `WarmupLinearScheduler` described below.
Class description:
Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used... | Implement the Python class `WarmupLinearScheduler` described below.
Class description:
Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class WarmupLinearScheduler:
"""Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used after every training batch."""
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WarmupLinearScheduler:
"""Linear warmup and then linear decay. Linearly increases learning rate from 0 to 1 over `warmup` training steps. Linearly decreases learning rate from 1. to 0. over remaining `n_steps - warmup` steps. This scheduler is generally used after every training batch."""
def __init__(se... | the_stack_v2_python_sparse | flambe/optim/linear.py | cle-ros/flambe | train | 1 |
94666a58f4c1db92770b2893b8f1081ed685fb03 | [
"super(CompressInteractionNetworkLayer, self).__init__()\nself.embed_size = embed_size\nself.is_direct = is_direct\nself.layer_sizes = [num_fields] + layer_sizes\nself.model = nn.ModuleList()\nfor i, (s_i, s_j) in enumerate(zip(self.layer_sizes[:-1], self.layer_sizes[1:])):\n cin = nn.Sequential()\n in_c = se... | <|body_start_0|>
super(CompressInteractionNetworkLayer, self).__init__()
self.embed_size = embed_size
self.is_direct = is_direct
self.layer_sizes = [num_fields] + layer_sizes
self.model = nn.ModuleList()
for i, (s_i, s_j) in enumerate(zip(self.layer_sizes[:-1], self.layer... | Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions with outer product by 1D convolution with a :math:`1 * 1` kernel. :Reference: #. `Jianxun Lian et al,... | CompressInteractionNetworkLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompressInteractionNetworkLayer:
"""Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions with outer product by 1D convolution with ... | stack_v2_sparse_classes_10k_train_001982 | 8,279 | permissive | [
{
"docstring": "Initialize CompressInteractionNetworkLayer Args: embed_size (int): Size of embedding tensor num_fields (int): Number of inputs' fields output_size (int): Output size of compress interaction network layer_sizes (List[int]): Layer sizes of compress interaction network is_direct (bool, optional): W... | 2 | stack_v2_sparse_classes_30k_train_002798 | Implement the Python class `CompressInteractionNetworkLayer` described below.
Class description:
Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions wit... | Implement the Python class `CompressInteractionNetworkLayer` described below.
Class description:
Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions wit... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class CompressInteractionNetworkLayer:
"""Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions with outer product by 1D convolution with ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompressInteractionNetworkLayer:
"""Layer class of Compress Interaction Network (CIN). Compress Interaction Network was used in xDeepFM by Jianxun Lian et al, 2018. It compress cross-features tensors calculated by element-wise cross features interactions with outer product by 1D convolution with a :math:`1 * ... | the_stack_v2_python_sparse | torecsys/layers/ctr/compress_interaction_network.py | zwcdp/torecsys | train | 0 |
e261913ca6a92f5484f083f1a655151de3e7f054 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | This service allows management of links between Google Ads accounts and other accounts. | AccountLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountLinkServiceServicer:
"""This service allows management of links between Google Ads accounts and other accounts."""
def GetAccountLink(self, request, context):
"""Returns the account link in full detail."""
<|body_0|>
def MutateAccountLink(self, request, context):
... | stack_v2_sparse_classes_10k_train_001983 | 3,318 | permissive | [
{
"docstring": "Returns the account link in full detail.",
"name": "GetAccountLink",
"signature": "def GetAccountLink(self, request, context)"
},
{
"docstring": "Creates or removes an account link.",
"name": "MutateAccountLink",
"signature": "def MutateAccountLink(self, request, context)... | 2 | stack_v2_sparse_classes_30k_train_001081 | Implement the Python class `AccountLinkServiceServicer` described below.
Class description:
This service allows management of links between Google Ads accounts and other accounts.
Method signatures and docstrings:
- def GetAccountLink(self, request, context): Returns the account link in full detail.
- def MutateAccou... | Implement the Python class `AccountLinkServiceServicer` described below.
Class description:
This service allows management of links between Google Ads accounts and other accounts.
Method signatures and docstrings:
- def GetAccountLink(self, request, context): Returns the account link in full detail.
- def MutateAccou... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class AccountLinkServiceServicer:
"""This service allows management of links between Google Ads accounts and other accounts."""
def GetAccountLink(self, request, context):
"""Returns the account link in full detail."""
<|body_0|>
def MutateAccountLink(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountLinkServiceServicer:
"""This service allows management of links between Google Ads accounts and other accounts."""
def GetAccountLink(self, request, context):
"""Returns the account link in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details(... | the_stack_v2_python_sparse | google/ads/google_ads/v4/proto/services/account_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
307a1b9a0df5573e6251c96fb23efcd429de09c4 | [
"def run(r):\n ld = 0\n rd = 0\n llm = 0\n rlm = 0\n lmax = 0\n if r.left:\n ld += 1\n d, llm = run(r.left)\n ld = ld + d\n if r.right:\n rd += 1\n d, rlm = run(r.right)\n rd = rd + d\n lmax = max(llm, rlm, rd + ld)\n return (rd if rd > ld else ld... | <|body_start_0|>
def run(r):
ld = 0
rd = 0
llm = 0
rlm = 0
lmax = 0
if r.left:
ld += 1
d, llm = run(r.left)
ld = ld + d
if r.right:
rd += 1
d, rlm =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right."""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/r... | stack_v2_sparse_classes_10k_train_001984 | 2,572 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/ri... | 2 | stack_v2_sparse_classes_30k_train_001760 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.
- def rewrite(self, root): :type root: TreeNode :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.
- def rewrite(self, root): :type root: TreeNode :r... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right."""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right."""
def run(r):
ld = 0
rd = 0
llm = 0
rlm = 0
lmax = 0
if r.left:
... | the_stack_v2_python_sparse | tree/543_Diameter_of_Binary_Tree.py | vsdrun/lc_public | train | 6 | |
5819fc5031474b321b0c610d1e562b85a6ced586 | [
"if not root:\n return 0\n\ndef visit(prefixes, node: TreeNode) -> int:\n new_prefixes = {key + node.val: count for key, count in prefixes.items()}\n new_prefixes[node.val] = new_prefixes.get(node.val, 0) + 1\n count = new_prefixes.get(target, 0)\n if node.left:\n count += visit(new_prefixes, ... | <|body_start_0|>
if not root:
return 0
def visit(prefixes, node: TreeNode) -> int:
new_prefixes = {key + node.val: count for key, count in prefixes.items()}
new_prefixes[node.val] = new_prefixes.get(node.val, 0) + 1
count = new_prefixes.get(target, 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
<|body_0|>
def pathSum(self,... | stack_v2_sparse_classes_10k_train_001985 | 2,344 | no_license | [
{
"docstring": "Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths.",
"name": "pathSum",
"signature": "def pathSum(self, root: TreeNode, target: int) -> int"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_005561 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root: TreeNode, target: int) -> int: Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for mult... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root: TreeNode, target: int) -> int: Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for mult... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
<|body_0|>
def pathSum(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root: TreeNode, target: int) -> int:
"""Traverse the tree downward, and try each path. Keep during the descent the possible starting sums (in a dictionary for multiplicities). On the way up, sum the number of paths."""
if not root:
return 0
def ... | the_stack_v2_python_sparse | binary_tree/PathSum3.py | QuentinDuval/PythonExperiments | train | 3 | |
ce24f7bcc30664ff103f6ab5a00e3c88a6982157 | [
"api_version = '2019-06-01'\nurl = self.check_dns_name_availability.metadata['url']\npath_format_arguments = {'location': self._serialize.url('location', location, 'str'), 'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str')}\nurl = self._client.format_url(url, **... | <|body_start_0|>
api_version = '2019-06-01'
url = self.check_dns_name_availability.metadata['url']
path_format_arguments = {'location': self._serialize.url('location', location, 'str'), 'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str')}
... | NetworkManagementClientOperationsMixin | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain... | stack_v2_sparse_classes_10k_train_001986 | 7,118 | permissive | [
{
"docstring": "Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain name. :type location: str :param domain_name_label: The domain name to be verified. It must conform to the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. :... | 2 | null | Implement the Python class `NetworkManagementClientOperationsMixin` described below.
Class description:
Implement the NetworkManagementClientOperationsMixin class.
Method signatures and docstrings:
- def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config)... | Implement the Python class `NetworkManagementClientOperationsMixin` described below.
Class description:
Implement the NetworkManagementClientOperationsMixin class.
Method signatures and docstrings:
- def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config)... | b8c2cf97e991adf0c0a207d810316b8f4686dc29 | <|skeleton|>
class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetworkManagementClientOperationsMixin:
def check_dns_name_availability(self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is available for use. :param location: The location of the domain name. :type l... | the_stack_v2_python_sparse | src/connection-monitor-preview/azext_connection_monitor_preview/vendored_sdks/v2019_06_01/v2019_06_01/operations/_network_management_client_operations.py | Azure/azure-cli-extensions | train | 336 | |
25864eb74e296efc76a83fc1a505f0f74294dd38 | [
"with benchmark('Generate a list of all reserved attribute names'):\n if not cls._reserved_names.get(definition_type):\n definition_map = {model._inflector.table_singular: model for model in ggrc.models.all_models.all_models}\n definition_map.update({model._inflector.model_singular: model for model... | <|body_start_0|>
with benchmark('Generate a list of all reserved attribute names'):
if not cls._reserved_names.get(definition_type):
definition_map = {model._inflector.table_singular: model for model in ggrc.models.all_models.all_models}
definition_map.update({model._... | Adds methods needed for attribute name vaidation | AttributeValidator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a st... | stack_v2_sparse_classes_10k_train_001987 | 2,376 | permissive | [
{
"docstring": "Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a static frozen set. All later calls just get this set. Returns: frozen set containing all reserved attribute names for the current object.",... | 2 | stack_v2_sparse_classes_30k_train_002491 | Implement the Python class `AttributeValidator` described below.
Class description:
Adds methods needed for attribute name vaidation
Method signatures and docstrings:
- def _get_reserved_names(cls, definition_type): Get a list of all attribute names in all objects. On first call this function computes all possible na... | Implement the Python class `AttributeValidator` described below.
Class description:
Adds methods needed for attribute name vaidation
Method signatures and docstrings:
- def _get_reserved_names(cls, definition_type): Get a list of all attribute names in all objects. On first call this function computes all possible na... | 9bdc0fc6ca9e252f4919db682d80e360d5581eb4 | <|skeleton|>
class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a static frozen s... | the_stack_v2_python_sparse | src/ggrc/models/mixins/attributevalidator.py | HLD/ggrc-core | train | 0 |
a35aa2414811648dbc9f44eb89346fcb4ca0781d | [
"self.action = action\nself.cluster_info = cluster_info\nself.details = details\nself.domain = domain\nself.entity_id = entity_id\nself.entity_name = entity_name\nself.entity_type = entity_type\nself.human_timestamp = human_timestamp\nself.impersonation = impersonation\nself.ip = ip\nself.new_record = new_record\ns... | <|body_start_0|>
self.action = action
self.cluster_info = cluster_info
self.details = details
self.domain = domain
self.entity_id = entity_id
self.entity_name = entity_name
self.entity_type = entity_type
self.human_timestamp = human_timestamp
self.... | Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action that caused the log to be generated. cluste... | ClusterAuditLog | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action ... | stack_v2_sparse_classes_10k_train_001988 | 6,311 | permissive | [
{
"docstring": "Constructor for the ClusterAuditLog class",
"name": "__init__",
"signature": "def __init__(self, action=None, cluster_info=None, details=None, domain=None, entity_id=None, entity_name=None, entity_type=None, human_timestamp=None, impersonation=None, ip=None, new_record=None, original_ten... | 2 | stack_v2_sparse_classes_30k_train_004812 | Implement the Python class `ClusterAuditLog` described below.
Class description:
Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes:... | Implement the Python class `ClusterAuditLog` described below.
Class description:
Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes:... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterAuditLog:
"""Implementation of the 'ClusterAuditLog' model. Specifies information about a single Cluster audit log. When an action (such as pausing a Protection Job) occurs, an audit log is generated that provides details about the action. Attributes: action (string): Specifies the action that caused t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_audit_log.py | cohesity/management-sdk-python | train | 24 |
4c58f6ce4f5f92e69fa53334ce11acbf1e113b63 | [
"entity = self.entities.find_entity_by_id(event.entity_id)\nskill = self.entities.find_entity_by_id(event.skill_entity_id)\nskill_target_component = skill.components.get('point_ranged_targeted_skill', None)\nif not skill_target_component:\n return\ntarget_point = entity.components['input'].input[EntityInput.TARG... | <|body_start_0|>
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entity_id)
skill_target_component = skill.components.get('point_ranged_targeted_skill', None)
if not skill_target_component:
return
target_po... | Point ranged targeted skill system. | PointRangedTargetedSkillSystem | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|... | stack_v2_sparse_classes_10k_train_001989 | 21,180 | permissive | [
{
"docstring": "Handle an entity skill usage attempt.",
"name": "on_entity_skill_usage_attempt",
"signature": "def on_entity_skill_usage_attempt(self, event)"
},
{
"docstring": "Handle an entity skill usage.",
"name": "on_entity_skill_usage",
"signature": "def on_entity_skill_usage(self,... | 2 | stack_v2_sparse_classes_30k_train_003449 | Implement the Python class `PointRangedTargetedSkillSystem` described below.
Class description:
Point ranged targeted skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill... | Implement the Python class `PointRangedTargetedSkillSystem` described below.
Class description:
Point ranged targeted skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill... | 1d84c2869a242a112e57c6cafc6da7329f9d0808 | <|skeleton|>
class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entit... | the_stack_v2_python_sparse | akurra/skills.py | multatronic/akurra | train | 0 |
09a1b6c560f856e1d686ae30b19f01eb21edce10 | [
"painter = QPainter(self.outPixmap())\npainter.drawPixmap(QPoint(0, 0), self.startPixmap())\nreturn (0.0, 1.0)",
"out = self.outPixmap()\npainter = QPainter(out)\npainter.eraseRect(0, 0, out.width(), out.height())\npainter.setOpacity(1.0 - alpha)\npainter.drawPixmap(QPoint(0, 0), self.startPixmap())\npainter.setO... | <|body_start_0|>
painter = QPainter(self.outPixmap())
painter.drawPixmap(QPoint(0, 0), self.startPixmap())
return (0.0, 1.0)
<|end_body_0|>
<|body_start_1|>
out = self.outPixmap()
painter = QPainter(out)
painter.eraseRect(0, 0, out.width(), out.height())
painter.... | A QPixmapTransition which animates using a cross fade effect. | QCrossFadeTransition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appro... | stack_v2_sparse_classes_10k_train_001990 | 14,565 | permissive | [
{
"docstring": "Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appropriate alpha blending value.",
"name": "preparePixmap",
"signature": "def preparePixmap(self)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_val_000313 | Implement the Python class `QCrossFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a cross fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The t... | Implement the Python class `QCrossFadeTransition` described below.
Class description:
A QPixmapTransition which animates using a cross fade effect.
Method signatures and docstrings:
- def preparePixmap(self): Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The t... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QCrossFadeTransition:
"""A QPixmapTransition which animates using a cross fade effect."""
def preparePixmap(self):
"""Prepare the pixmap(s) for the transition. This method draws the starting pixmap into the output pixmap. The transition updates then draw the two pixmaps with an appropriate alpha ... | the_stack_v2_python_sparse | enaml/qt/q_pixmap_transition.py | MatthieuDartiailh/enaml | train | 26 |
efefecd09ad8506b7a9421370f064661fa5e39ee | [
"_1 = ListNode(1)\n_2 = ListNode(2)\n_3 = ListNode(3)\n_4 = ListNode(4)\n_1.next = _2\n_2.next = _3\n_3.next = _4\ns = Solution()\nnode = s.swapPairs(_1)\nself.assertIsNotNone(node)\nfor i in [2, 1, 4, 3]:\n self.assertEqual(i, node.val)\n node = node.next",
"_1 = ListNode(1)\n_2 = ListNode(2)\n_3 = ListNod... | <|body_start_0|>
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = ListNode(4)
_1.next = _2
_2.next = _3
_3.next = _4
s = Solution()
node = s.swapPairs(_1)
self.assertIsNotNone(node)
for i in [2, 1, 4, 3]:
self.ass... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_0|>
def test2(self):
"""给定 1->2->3, 你应该返回 2->1->3."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = L... | stack_v2_sparse_classes_10k_train_001991 | 1,673 | no_license | [
{
"docstring": "给定 1->2->3->4, 你应该返回 2->1->4->3.",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "给定 1->2->3, 你应该返回 2->1->3.",
"name": "test2",
"signature": "def test2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005158 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): 给定 1->2->3->4, 你应该返回 2->1->4->3.
- def test2(self): 给定 1->2->3, 你应该返回 2->1->3. | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): 给定 1->2->3->4, 你应该返回 2->1->4->3.
- def test2(self): 给定 1->2->3, 你应该返回 2->1->3.
<|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3... | 248b620791611001ebb471dcf8284437264b2f20 | <|skeleton|>
class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_0|>
def test2(self):
"""给定 1->2->3, 你应该返回 2->1->3."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test:
def test1(self):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
_1 = ListNode(1)
_2 = ListNode(2)
_3 = ListNode(3)
_4 = ListNode(4)
_1.next = _2
_2.next = _3
_3.next = _4
s = Solution()
node = s.swapPairs(_1)
self.assertIsNo... | the_stack_v2_python_sparse | 24_swap_nodes_in_pairs/_1.py | chxj1992/leetcode-exercise | train | 0 | |
252582162b5d1ef00d22b9799e3277364b18cb80 | [
"if rx == 'Msip1mm':\n self.nhorns = 6\n self.spacing = 0\n self.rotation = 0\n self.RIGHT = np.array([0, 0, 0, 0, 0, 0])\n self.UP = np.array([0, 0, 0, 0, 0, 0])\nelse:\n self.nhorns = 16\n self.spacing = spacing\n self.rotation = rotation / 180.0 * np.pi\n self.RIGHT = np.array([-1.5, -... | <|body_start_0|>
if rx == 'Msip1mm':
self.nhorns = 6
self.spacing = 0
self.rotation = 0
self.RIGHT = np.array([0, 0, 0, 0, 0, 0])
self.UP = np.array([0, 0, 0, 0, 0, 0])
else:
self.nhorns = 16
self.spacing = spacing
... | Class to define the geometry of the SEQUOIA array and provide methods to compute offsets. | Grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of ... | stack_v2_sparse_classes_10k_train_001992 | 3,326 | no_license | [
{
"docstring": "Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of array relative to telescope in degrees",
"name": "__init__",
"signature": "def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0)"
},
{
"docstring": "Returns... | 3 | stack_v2_sparse_classes_30k_train_005775 | Implement the Python class `Grid` described below.
Class description:
Class to define the geometry of the SEQUOIA array and provide methods to compute offsets.
Method signatures and docstrings:
- def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0): Constructor for Grid class. Args: spacing (float): spacing ... | Implement the Python class `Grid` described below.
Class description:
Class to define the geometry of the SEQUOIA array and provide methods to compute offsets.
Method signatures and docstrings:
- def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0): Constructor for Grid class. Args: spacing (float): spacing ... | 4064f6ca5d2807fbb99626838493d0f91cbd8748 | <|skeleton|>
class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of array relativ... | the_stack_v2_python_sparse | lmtslr/grid/grid.py | myunm82/SpectralLineReduction | train | 0 |
3e6c5418e3d758fa7ba00ad034288c3e2eaacf06 | [
"self.entity_description = description\nslug = slugify(description.key.replace('/', '_'))\nself.entity_id = f'sensor.{slug}'",
"@callback\ndef message_received(message):\n \"\"\"Handle new MQTT messages.\"\"\"\n if self.entity_description.state is not None:\n self._attr_native_value = self.entity_des... | <|body_start_0|>
self.entity_description = description
slug = slugify(description.key.replace('/', '_'))
self.entity_id = f'sensor.{slug}'
<|end_body_0|>
<|body_start_1|>
@callback
def message_received(message):
"""Handle new MQTT messages."""
if self.ent... | Representation of a DSMR sensor that is updated via MQTT. | DSMRSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DSMRSensor:
"""Representation of a DSMR sensor that is updated via MQTT."""
def __init__(self, description: DSMRReaderSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
async def async_added_to_hass(self):
"""Subscribe to MQTT events."""
... | stack_v2_sparse_classes_10k_train_001993 | 1,510 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, description: DSMRReaderSensorEntityDescription) -> None"
},
{
"docstring": "Subscribe to MQTT events.",
"name": "async_added_to_hass",
"signature": "async def async_added_to_hass(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001006 | Implement the Python class `DSMRSensor` described below.
Class description:
Representation of a DSMR sensor that is updated via MQTT.
Method signatures and docstrings:
- def __init__(self, description: DSMRReaderSensorEntityDescription) -> None: Initialize the sensor.
- async def async_added_to_hass(self): Subscribe ... | Implement the Python class `DSMRSensor` described below.
Class description:
Representation of a DSMR sensor that is updated via MQTT.
Method signatures and docstrings:
- def __init__(self, description: DSMRReaderSensorEntityDescription) -> None: Initialize the sensor.
- async def async_added_to_hass(self): Subscribe ... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class DSMRSensor:
"""Representation of a DSMR sensor that is updated via MQTT."""
def __init__(self, description: DSMRReaderSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
async def async_added_to_hass(self):
"""Subscribe to MQTT events."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DSMRSensor:
"""Representation of a DSMR sensor that is updated via MQTT."""
def __init__(self, description: DSMRReaderSensorEntityDescription) -> None:
"""Initialize the sensor."""
self.entity_description = description
slug = slugify(description.key.replace('/', '_'))
self... | the_stack_v2_python_sparse | homeassistant/components/dsmr_reader/sensor.py | AlexxIT/home-assistant | train | 9 |
d6787d664dbbbc47aae21014bfded5f9c918d483 | [
"dao = Dao()\nfrom main_index import Interface_Tasking\ninter_task = Interface_Tasking()\ntestees = []\nall_timings = dao.find_by_timing()\nfor all_timing in all_timings:\n gev = gevent.spawn(inter_task.give_one_mongo_params, all_timing)\n testees.append(gev)\ngevent.joinall(testees)\nglobal timer\ndelta_t = ... | <|body_start_0|>
dao = Dao()
from main_index import Interface_Tasking
inter_task = Interface_Tasking()
testees = []
all_timings = dao.find_by_timing()
for all_timing in all_timings:
gev = gevent.spawn(inter_task.give_one_mongo_params, all_timing)
t... | 定义定时类,只是面向对象罢了,没什么大不同的 | alarm_schedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
<|body_0|>
def input_one_time(self):
"""给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE"""
<|body_1|>
def... | stack_v2_sparse_classes_10k_train_001994 | 3,321 | no_license | [
{
"docstring": "进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的",
"name": "alarm_gogogo",
"signature": "def alarm_gogogo(self)"
},
{
"docstring": "给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE",
"name": "input_one_time",
"signature": "def input_one_time(self)"
}... | 3 | stack_v2_sparse_classes_30k_val_000276 | Implement the Python class `alarm_schedule` described below.
Class description:
定义定时类,只是面向对象罢了,没什么大不同的
Method signatures and docstrings:
- def alarm_gogogo(self): 进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的
- def input_one_time(self): 给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE
- def get... | Implement the Python class `alarm_schedule` described below.
Class description:
定义定时类,只是面向对象罢了,没什么大不同的
Method signatures and docstrings:
- def alarm_gogogo(self): 进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的
- def input_one_time(self): 给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE
- def get... | 2ec589d7267b03df8ae8b5df8d4d3ce8253d097c | <|skeleton|>
class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
<|body_0|>
def input_one_time(self):
"""给前端的接口,这样就可以做定时了 不管是修改了定时时间还是触发定时任务,都可以用 :return: NONE"""
<|body_1|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class alarm_schedule:
"""定义定时类,只是面向对象罢了,没什么大不同的"""
def alarm_gogogo(self):
"""进入后其实当用户修改时间后是会停止的,而且会修改下次执行时间... 如果用户不修改时间他就是一个永不停歇的函数 24小时制的"""
dao = Dao()
from main_index import Interface_Tasking
inter_task = Interface_Tasking()
testees = []
all_timings = dao.fi... | the_stack_v2_python_sparse | src/interface_tasking/alarm_scheduling.py | Ka1evi/Angular-SPA | train | 0 |
5a3019d7b527a261a3998ab321a087802fab86f7 | [
"mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1)\nif mcpfpp_rcs:\n self.supplier_account_position_id = mcpfpp_rcs.account_position_id.id\nelse:\n self.supplier_account_position_id = False"... | <|body_start_0|>
mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1)
if mcpfpp_rcs:
self.supplier_account_position_id = mcpfpp_rcs.account_position_id.id
else:
... | res_partner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class res_partner:
def _get_supplier_account_position_id(self):
"""Fonction qui retourne la position fiscale selon la société"""
<|body_0|>
def write(self, vals=None):
"""Interdiction de changer de catégorie"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001995 | 7,933 | no_license | [
{
"docstring": "Fonction qui retourne la position fiscale selon la société",
"name": "_get_supplier_account_position_id",
"signature": "def _get_supplier_account_position_id(self)"
},
{
"docstring": "Interdiction de changer de catégorie",
"name": "write",
"signature": "def write(self, va... | 2 | stack_v2_sparse_classes_30k_train_001206 | Implement the Python class `res_partner` described below.
Class description:
Implement the res_partner class.
Method signatures and docstrings:
- def _get_supplier_account_position_id(self): Fonction qui retourne la position fiscale selon la société
- def write(self, vals=None): Interdiction de changer de catégorie | Implement the Python class `res_partner` described below.
Class description:
Implement the res_partner class.
Method signatures and docstrings:
- def _get_supplier_account_position_id(self): Fonction qui retourne la position fiscale selon la société
- def write(self, vals=None): Interdiction de changer de catégorie
... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class res_partner:
def _get_supplier_account_position_id(self):
"""Fonction qui retourne la position fiscale selon la société"""
<|body_0|>
def write(self, vals=None):
"""Interdiction de changer de catégorie"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class res_partner:
def _get_supplier_account_position_id(self):
"""Fonction qui retourne la position fiscale selon la société"""
mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1)
... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/multi_company/res_partner.py | kazacube-mziouadi/ceci | train | 0 | |
2f5ccad2d1fba4c608abe198d9c772f45a7cd808 | [
"count = len(prices)\nif count < 2:\n return 0\ndp = [0 for _ in xrange(count)]\nfor i in xrange(1, count):\n if prices[i] >= prices[i - 1]:\n dp[i] = dp[i - 1] + (prices[i] - prices[i - 1])\n else:\n dp[i] = dp[i - 1]\nreturn dp[-1]",
"count = len(prices)\nif count < 2:\n return 0\nprof... | <|body_start_0|>
count = len(prices)
if count < 2:
return 0
dp = [0 for _ in xrange(count)]
for i in xrange(1, count):
if prices[i] >= prices[i - 1]:
dp[i] = dp[i - 1] + (prices[i] - prices[i - 1])
else:
dp[i] = dp[i - 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_O_1_space(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = len(prices)
if ... | stack_v2_sparse_classes_10k_train_001996 | 854 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_O_1_space",
"signature": "def maxProfit_O_1_space(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_O_1_space(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_O_1_space(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
d... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_O_1_space(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
count = len(prices)
if count < 2:
return 0
dp = [0 for _ in xrange(count)]
for i in xrange(1, count):
if prices[i] >= prices[i - 1]:
dp[i] = dp[i - 1... | the_stack_v2_python_sparse | 122_best_time_to_buy_and_sell_stock_2/sol.py | lianke123321/leetcode_sol | train | 0 | |
296d03b0580dd8c490a1fe69ad1bca8fd23dad8d | [
"prev = None\nwhile head:\n link = head.next\n head.next = prev\n prev, head = (head, link)\nreturn prev",
"head1 = self.reverse_list(head1)\nhead2 = self.reverse_list(head2)\ncurr1, curr2 = (head1, head2)\nrem = 0\nprev = None\nwhile curr1 and curr2:\n curr_sum = curr1.val + curr2.val + rem\n curr... | <|body_start_0|>
prev = None
while head:
link = head.next
head.next = prev
prev, head = (head, link)
return prev
<|end_body_0|>
<|body_start_1|>
head1 = self.reverse_list(head1)
head2 = self.reverse_list(head2)
curr1, curr2 = (head1, h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
<|body_0|>
def addTwoNumbers(self, head1, head2):
"""Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m ar... | stack_v2_sparse_classes_10k_train_001997 | 2,113 | no_license | [
{
"docstring": "Reverses linked list and returns a link to new head pointer.",
"name": "reverse_list",
"signature": "def reverse_list(self, head)"
},
{
"docstring": "Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of the linked... | 2 | stack_v2_sparse_classes_30k_val_000041 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head): Reverses linked list and returns a link to new head pointer.
- def addTwoNumbers(self, head1, head2): Returns head pointer to a new linked list. Tim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head): Reverses linked list and returns a link to new head pointer.
- def addTwoNumbers(self, head1, head2): Returns head pointer to a new linked list. Tim... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
<|body_0|>
def addTwoNumbers(self, head1, head2):
"""Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
prev = None
while head:
link = head.next
head.next = prev
prev, head = (head, link)
return prev
def addTwoNumbers(self, head1, hea... | the_stack_v2_python_sparse | Linked_Lists/add_two_numbers_2.py | vladn90/Algorithms | train | 0 | |
b4ecaf76d184aa68e3b715f653dbb78741c8ef69 | [
"article = get_object_or_404(Article, slug=self.kwargs['slug'])\ndata = request.data\nserializer = self.serializer_class(data=data)\nif serializer.is_valid():\n serializer.save(author=self.request.user, article=article)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\nreturn Response(serial... | <|body_start_0|>
article = get_object_or_404(Article, slug=self.kwargs['slug'])
data = request.data
serializer = self.serializer_class(data=data)
if serializer.is_valid():
serializer.save(author=self.request.user, article=article)
return Response(serializer.data, ... | A user can comment on an article | ArticleCommentAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleCommentAPIView:
"""A user can comment on an article"""
def post(self, request, slug=None):
"""Comment on an article in the application"""
<|body_0|>
def get(self, request, slug=None):
"""Get all the comments of an article"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k_train_001998 | 8,748 | permissive | [
{
"docstring": "Comment on an article in the application",
"name": "post",
"signature": "def post(self, request, slug=None)"
},
{
"docstring": "Get all the comments of an article",
"name": "get",
"signature": "def get(self, request, slug=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002090 | Implement the Python class `ArticleCommentAPIView` described below.
Class description:
A user can comment on an article
Method signatures and docstrings:
- def post(self, request, slug=None): Comment on an article in the application
- def get(self, request, slug=None): Get all the comments of an article | Implement the Python class `ArticleCommentAPIView` described below.
Class description:
A user can comment on an article
Method signatures and docstrings:
- def post(self, request, slug=None): Comment on an article in the application
- def get(self, request, slug=None): Get all the comments of an article
<|skeleton|>... | e8438b78b88c52d108520429d0b67cd3d13e0824 | <|skeleton|>
class ArticleCommentAPIView:
"""A user can comment on an article"""
def post(self, request, slug=None):
"""Comment on an article in the application"""
<|body_0|>
def get(self, request, slug=None):
"""Get all the comments of an article"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArticleCommentAPIView:
"""A user can comment on an article"""
def post(self, request, slug=None):
"""Comment on an article in the application"""
article = get_object_or_404(Article, slug=self.kwargs['slug'])
data = request.data
serializer = self.serializer_class(data=data)... | the_stack_v2_python_sparse | authors/apps/comments/views.py | andela/ah-sealteam | train | 1 |
00d1355c4758fcaf0a9db7003b749f9795d8ef44 | [
"self.threaded = threaded\nself.colorize = colorize\nkwargs['fmt'] = LOG_FORMAT.format('', '', color='')\nif self.colorize:\n color = ''\n if random_color:\n color = random.choice(COLOR_SEQS)\n kwargs['fmt'] = LOG_FORMAT.format(BOLD, RESET_SEQ, color=color)\nsuper(WolfFormatter, self).__init__(**kwa... | <|body_start_0|>
self.threaded = threaded
self.colorize = colorize
kwargs['fmt'] = LOG_FORMAT.format('', '', color='')
if self.colorize:
color = ''
if random_color:
color = random.choice(COLOR_SEQS)
kwargs['fmt'] = LOG_FORMAT.format(BOL... | Helper class used to add color to log messages depending on their level. | WolfFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WolfFormatter:
"""Helper class used to add color to log messages depending on their level."""
def __init__(self, colorize: bool=True, random_color: bool=False, threaded: bool=False, **kwargs: Any) -> None:
"""Initializes the WolfFormatter object. Args: colorize (bool): If True, outpu... | stack_v2_sparse_classes_10k_train_001999 | 3,839 | permissive | [
{
"docstring": "Initializes the WolfFormatter object. Args: colorize (bool): If True, output will be colorized. random_color (bool): If True, will colorize the module name with a random color picked from COLOR_SEQS.",
"name": "__init__",
"signature": "def __init__(self, colorize: bool=True, random_color... | 2 | stack_v2_sparse_classes_30k_train_003035 | Implement the Python class `WolfFormatter` described below.
Class description:
Helper class used to add color to log messages depending on their level.
Method signatures and docstrings:
- def __init__(self, colorize: bool=True, random_color: bool=False, threaded: bool=False, **kwargs: Any) -> None: Initializes the Wo... | Implement the Python class `WolfFormatter` described below.
Class description:
Helper class used to add color to log messages depending on their level.
Method signatures and docstrings:
- def __init__(self, colorize: bool=True, random_color: bool=False, threaded: bool=False, **kwargs: Any) -> None: Initializes the Wo... | bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c | <|skeleton|>
class WolfFormatter:
"""Helper class used to add color to log messages depending on their level."""
def __init__(self, colorize: bool=True, random_color: bool=False, threaded: bool=False, **kwargs: Any) -> None:
"""Initializes the WolfFormatter object. Args: colorize (bool): If True, outpu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WolfFormatter:
"""Helper class used to add color to log messages depending on their level."""
def __init__(self, colorize: bool=True, random_color: bool=False, threaded: bool=False, **kwargs: Any) -> None:
"""Initializes the WolfFormatter object. Args: colorize (bool): If True, output will be col... | the_stack_v2_python_sparse | dftimewolf/lib/logging_utils.py | log2timeline/dftimewolf | train | 248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.