blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
797dfcfff6749fb51880e5888829a1c957e406fe | [
"Parametre.__init__(self, 'creer', 'create')\nself.schema = '(<cle>)'\nself.aide_courte = 'crée une perturbation'\nself.aide_longue = \"Cette commande permet de créer une perturbation météorologique dans la salle où vous vous trouvez (par exemple, faire apparaître un nuage). La salle où vous vous trouvez est prise ... | <|body_start_0|>
Parametre.__init__(self, 'creer', 'create')
self.schema = '(<cle>)'
self.aide_courte = 'crée une perturbation'
self.aide_longue = "Cette commande permet de créer une perturbation météorologique dans la salle où vous vous trouvez (par exemple, faire apparaître un nuage). ... | Commande 'meteo créer' | PrmCreer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmCreer:
"""Commande 'meteo créer'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parame... | stack_v2_sparse_classes_75kplus_train_004600 | 4,658 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049414 | Implement the Python class `PrmCreer` described below.
Class description:
Commande 'meteo créer'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande | Implement the Python class `PrmCreer` described below.
Class description:
Commande 'meteo créer'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
<|skeleton|>
class PrmCreer:
"""Commande 'mete... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmCreer:
"""Commande 'meteo créer'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmCreer:
"""Commande 'meteo créer'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'creer', 'create')
self.schema = '(<cle>)'
self.aide_courte = 'crée une perturbation'
self.aide_longue = "Cette commande permet de créer une perturb... | the_stack_v2_python_sparse | src/primaires/meteo/commandes/meteo/creer.py | vincent-lg/tsunami | train | 5 |
c098ec858e0bb4de7c76d69293f67e35d41f97c6 | [
"curve_data = self._data()\nmax_abs_y, _ = curve.guess.max_height(curve_data.y, absolute=True)\nuser_opt.bounds.set_if_empty(a=(-2 * max_abs_y, 2 * max_abs_y), sigma=(0, np.ptp(curve_data.x)), freq=(min(curve_data.x), max(curve_data.x)), b=(-max_abs_y, max_abs_y))\nuser_opt.p0.set_if_empty(b=curve.guess.constant_sp... | <|body_start_0|>
curve_data = self._data()
max_abs_y, _ = curve.guess.max_height(curve_data.y, absolute=True)
user_opt.bounds.set_if_empty(a=(-2 * max_abs_y, 2 * max_abs_y), sigma=(0, np.ptp(curve_data.x)), freq=(min(curve_data.x), max(curve_data.x)), b=(-max_abs_y, max_abs_y))
user_opt.... | A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\exp(-(x-f)^2/(2\\sigma^2)) + b Fit Parameters - :math:`a`: Peak height. - :math:`b`:... | ResonanceAnalysis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResonanceAnalysis:
"""A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\exp(-(x-f)^2/(2\\sigma^2)) + b Fit Para... | stack_v2_sparse_classes_75kplus_train_004601 | 5,335 | permissive | [
{
"docstring": "Compute the initial guesses. Args: user_opt: Fit options filled with user provided guess and bounds. Returns: List of fit options that are passed to the fitter function.",
"name": "_generate_fit_guesses",
"signature": "def _generate_fit_guesses(self, user_opt: curve.FitOptions) -> Union[... | 2 | stack_v2_sparse_classes_30k_test_001475 | Implement the Python class `ResonanceAnalysis` described below.
Class description:
A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\... | Implement the Python class `ResonanceAnalysis` described below.
Class description:
A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\... | 22b1598b290464e59a12853efa1eb99b1b36513a | <|skeleton|>
class ResonanceAnalysis:
"""A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\exp(-(x-f)^2/(2\\sigma^2)) + b Fit Para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResonanceAnalysis:
"""A class to analyze a resonance, typically seen as a peak. Overview This analysis takes only single series. This series is fit by the Gaussian function. Fit Model The fit is based on the following Gaussian function. .. math:: F(x) = a \\exp(-(x-f)^2/(2\\sigma^2)) + b Fit Parameters - :mat... | the_stack_v2_python_sparse | qiskit_experiments/curve_analysis/standard_analysis/resonance.py | huggingworld/qiskit-experiments | train | 0 |
e7ad6610a556b0cbb2715f8394a45880309113cf | [
"self.baud = baud\nself.timeout = timeout\nself.pid = pid\nself.port = '/dev/youbot/gripper'",
"try:\n self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)\nexcept Exception as a:\n rospy.logerr(a)\n rospy.logerr('Please check the port {}'.format(self.port))",
"self.board.flushInput()... | <|body_start_0|>
self.baud = baud
self.timeout = timeout
self.pid = pid
self.port = '/dev/youbot/gripper'
<|end_body_0|>
<|body_start_1|>
try:
self.board = serial.Serial(self.port, self.baud, timeout=self.timeout)
except Exception as a:
rospy.loge... | SerialInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_75kplus_train_004602 | 2,489 | no_license | [
{
"docstring": "This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the microcontroller @param timeout -- timeout after which... | 4 | stack_v2_sparse_classes_30k_val_002950 | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | Implement the Python class `SerialInterface` described below.
Class description:
Implement the SerialInterface class.
Method signatures and docstrings:
- def __init__(self, baud, timeout, pid): This module contains a component that communicates with the particular Teensy board and sends the message via serial port wi... | 8129cd48351159508cae3438a8b8b3d776c771ca | <|skeleton|>
class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SerialInterface:
def __init__(self, baud, timeout, pid):
"""This module contains a component that communicates with the particular Teensy board and sends the message via serial port with specified baudrate, timeout and pid of the microcontroller board. Keyword arguments: @param baud -- baudrate of the... | the_stack_v2_python_sparse | mir_manipulation/mir_gripper_controller/ros/scripts/serial_interface.py | b-it-bots/mas_industrial_robotics | train | 25 | |
01e3427781ed8033e95d9b54233100af3ac383da | [
"print('Output Class Started')\nmultiprocessing.Process.__init__(self, *args, **kw)\nself.queue = q\nself.workers = N\nself.sorting = sorting\nself.output = []",
"while self.workers:\n p = self.queue.get()\n if p is None:\n self.workers -= 1\n else:\n self.output.append(p)\nprint(''.join((c... | <|body_start_0|>
print('Output Class Started')
multiprocessing.Process.__init__(self, *args, **kw)
self.queue = q
self.workers = N
self.sorting = sorting
self.output = []
<|end_body_0|>
<|body_start_1|>
while self.workers:
p = self.queue.get()
... | OutThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutThread:
def __init__(self, N, q, sorting=True, *args, **kw):
"""Initialize process and save queue reference"""
<|body_0|>
def run(self):
"""Extracts items from the output queue and print untill all are done"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_004603 | 1,724 | no_license | [
{
"docstring": "Initialize process and save queue reference",
"name": "__init__",
"signature": "def __init__(self, N, q, sorting=True, *args, **kw)"
},
{
"docstring": "Extracts items from the output queue and print untill all are done",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051351 | Implement the Python class `OutThread` described below.
Class description:
Implement the OutThread class.
Method signatures and docstrings:
- def __init__(self, N, q, sorting=True, *args, **kw): Initialize process and save queue reference
- def run(self): Extracts items from the output queue and print untill all are ... | Implement the Python class `OutThread` described below.
Class description:
Implement the OutThread class.
Method signatures and docstrings:
- def __init__(self, N, q, sorting=True, *args, **kw): Initialize process and save queue reference
- def run(self): Extracts items from the output queue and print untill all are ... | 7306581d542d6d045a9b2e6377ade0fc5ab8bc0e | <|skeleton|>
class OutThread:
def __init__(self, N, q, sorting=True, *args, **kw):
"""Initialize process and save queue reference"""
<|body_0|>
def run(self):
"""Extracts items from the output queue and print untill all are done"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutThread:
def __init__(self, N, q, sorting=True, *args, **kw):
"""Initialize process and save queue reference"""
print('Output Class Started')
multiprocessing.Process.__init__(self, *args, **kw)
self.queue = q
self.workers = N
self.sorting = sorting
sel... | the_stack_v2_python_sparse | PythonHomeWork/Py4/Py4_Lesson12/src/output.py | rduvalwa5/OReillyPy | train | 0 | |
f8e274a291b754904ab01f3bea241515df8796f3 | [
"wheres = ''\nif data.data_type == 1:\n index_path = models.SSADataTag.objects.get(id=data.data_tag)\nelif data.data_type == 2:\n index_path = models.SECDataTag.objects.get(id=data.data_tag)\n wheres = 'where {} = {}'.format('event_source', data.data_tag)\nelse:\n return {}\nif not index_path:\n retu... | <|body_start_0|>
wheres = ''
if data.data_type == 1:
index_path = models.SSADataTag.objects.get(id=data.data_tag)
elif data.data_type == 2:
index_path = models.SECDataTag.objects.get(id=data.data_tag)
wheres = 'where {} = {}'.format('event_source', data.data_t... | 报告元素 | ReportCellList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportCellList:
"""报告元素"""
def get_custom_data(self, userinfo, data):
"""封装自定义图表数据"""
<|body_0|>
def post(self, request):
"""报告元素"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wheres = ''
if data.data_type == 1:
index_path ... | stack_v2_sparse_classes_75kplus_train_004604 | 18,475 | no_license | [
{
"docstring": "封装自定义图表数据",
"name": "get_custom_data",
"signature": "def get_custom_data(self, userinfo, data)"
},
{
"docstring": "报告元素",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000333 | Implement the Python class `ReportCellList` described below.
Class description:
报告元素
Method signatures and docstrings:
- def get_custom_data(self, userinfo, data): 封装自定义图表数据
- def post(self, request): 报告元素 | Implement the Python class `ReportCellList` described below.
Class description:
报告元素
Method signatures and docstrings:
- def get_custom_data(self, userinfo, data): 封装自定义图表数据
- def post(self, request): 报告元素
<|skeleton|>
class ReportCellList:
"""报告元素"""
def get_custom_data(self, userinfo, data):
"""封装... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class ReportCellList:
"""报告元素"""
def get_custom_data(self, userinfo, data):
"""封装自定义图表数据"""
<|body_0|>
def post(self, request):
"""报告元素"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportCellList:
"""报告元素"""
def get_custom_data(self, userinfo, data):
"""封装自定义图表数据"""
wheres = ''
if data.data_type == 1:
index_path = models.SSADataTag.objects.get(id=data.data_tag)
elif data.data_type == 2:
index_path = models.SECDataTag.objects.g... | the_stack_v2_python_sparse | soc_ssa/views/report_views.py | sundw2015/841 | train | 4 |
1211a3d811b0f0712860e84325250f25467a26ea | [
"error_formated = 'Database conecction error.'\nerror_formated += '\\nPlease check your credentials.\\n'\nlog.update_status(error_formated)\nglobals.loading = False\nlog.error(err)",
"try:\n self.connection.cursor()\nexcept AttributeError:\n try:\n self.connection = psycopg2.connect(host=self.server,... | <|body_start_0|>
error_formated = 'Database conecction error.'
error_formated += '\nPlease check your credentials.\n'
log.update_status(error_formated)
globals.loading = False
log.error(err)
<|end_body_0|>
<|body_start_1|>
try:
self.connection.cursor()
... | PostgreSQL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostgreSQL:
def credentials_error(self, err):
"""Print credential error and update status"""
<|body_0|>
def get_cursor_connector(self):
"""Connect to postgresql database and return cursor"""
<|body_1|>
def run_sql(self, sql):
"""Exceute sql code ... | stack_v2_sparse_classes_75kplus_train_004605 | 1,971 | no_license | [
{
"docstring": "Print credential error and update status",
"name": "credentials_error",
"signature": "def credentials_error(self, err)"
},
{
"docstring": "Connect to postgresql database and return cursor",
"name": "get_cursor_connector",
"signature": "def get_cursor_connector(self)"
},... | 3 | stack_v2_sparse_classes_30k_train_045031 | Implement the Python class `PostgreSQL` described below.
Class description:
Implement the PostgreSQL class.
Method signatures and docstrings:
- def credentials_error(self, err): Print credential error and update status
- def get_cursor_connector(self): Connect to postgresql database and return cursor
- def run_sql(se... | Implement the Python class `PostgreSQL` described below.
Class description:
Implement the PostgreSQL class.
Method signatures and docstrings:
- def credentials_error(self, err): Print credential error and update status
- def get_cursor_connector(self): Connect to postgresql database and return cursor
- def run_sql(se... | 721e1a2fca36c378206462a36cecc9f403d11c86 | <|skeleton|>
class PostgreSQL:
def credentials_error(self, err):
"""Print credential error and update status"""
<|body_0|>
def get_cursor_connector(self):
"""Connect to postgresql database and return cursor"""
<|body_1|>
def run_sql(self, sql):
"""Exceute sql code ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostgreSQL:
def credentials_error(self, err):
"""Print credential error and update status"""
error_formated = 'Database conecction error.'
error_formated += '\nPlease check your credentials.\n'
log.update_status(error_formated)
globals.loading = False
log.error(... | the_stack_v2_python_sparse | DeepREI/Data Collection/crimedatascraper/database/postgresql.py | dangoML/Project-Portfolio | train | 5 | |
71ada0c804873f38ddcb119d25fab939ee71bce6 | [
"super().__init__()\nself.n_channels = n_channels\nself.const = nn.Parameter(torch.ones(1, n_channels, 4, 4))\nself.epilogue_1 = Epilogue(n_channels, latent_size)\nself.conv = ScaledConv2d(n_channels, n_channels, kernel_size=3, padding=1)\nself.epilogue_2 = Epilogue(n_channels, latent_size)",
"batch_size = w.size... | <|body_start_0|>
super().__init__()
self.n_channels = n_channels
self.const = nn.Parameter(torch.ones(1, n_channels, 4, 4))
self.epilogue_1 = Epilogue(n_channels, latent_size)
self.conv = ScaledConv2d(n_channels, n_channels, kernel_size=3, padding=1)
self.epilogue_2 = Epi... | StyleGANGenInitialBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleGANGenInitialBlock:
def __init__(self, n_channels: int, latent_size: int):
"""Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image latent_size: Dimensionality of the latent space"""
<|body_0|>
def forward(self, w: Tensor, seed: int=... | stack_v2_sparse_classes_75kplus_train_004606 | 11,982 | no_license | [
{
"docstring": "Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image latent_size: Dimensionality of the latent space",
"name": "__init__",
"signature": "def __init__(self, n_channels: int, latent_size: int)"
},
{
"docstring": "Passes the latent vector w thro... | 2 | stack_v2_sparse_classes_30k_train_049238 | Implement the Python class `StyleGANGenInitialBlock` described below.
Class description:
Implement the StyleGANGenInitialBlock class.
Method signatures and docstrings:
- def __init__(self, n_channels: int, latent_size: int): Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image la... | Implement the Python class `StyleGANGenInitialBlock` described below.
Class description:
Implement the StyleGANGenInitialBlock class.
Method signatures and docstrings:
- def __init__(self, n_channels: int, latent_size: int): Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image la... | e7388d5bac4451b0c72ece5c3c2cd399b08048e6 | <|skeleton|>
class StyleGANGenInitialBlock:
def __init__(self, n_channels: int, latent_size: int):
"""Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image latent_size: Dimensionality of the latent space"""
<|body_0|>
def forward(self, w: Tensor, seed: int=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StyleGANGenInitialBlock:
def __init__(self, n_channels: int, latent_size: int):
"""Initial block of the StyleGAN generator. Args: n_channels: Number of channels of the image latent_size: Dimensionality of the latent space"""
super().__init__()
self.n_channels = n_channels
self.... | the_stack_v2_python_sparse | networks/modules/stylegan.py | mcschmitz/duck_and_cover | train | 0 | |
070083b455a5de1bd498dbbaf9ee619796450eb4 | [
"super().__init__()\nself.c_in = c_in\nself.c_out = c_out\nself.A = A\nself.conv = nn.Conv2d(self.c_in, self.c_out, kernel_size=(1, 1))\nself.activation = getattr(nn, activation)()",
"if A is None:\n A = self.A\nX = self.conv(X)\nX = torch.einsum('nctv,vw->nctw', (X, A))\nreturn X.contiguous()"
] | <|body_start_0|>
super().__init__()
self.c_in = c_in
self.c_out = c_out
self.A = A
self.conv = nn.Conv2d(self.c_in, self.c_out, kernel_size=(1, 1))
self.activation = getattr(nn, activation)()
<|end_body_0|>
<|body_start_1|>
if A is None:
A = self.A
... | Implementation of the spectral convolution. | SpectralConvolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation functio... | stack_v2_sparse_classes_75kplus_train_004607 | 12,878 | no_license | [
{
"docstring": "Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation function for the final output. Not used yet. A: torch.Tensor Adjacency matrix.",
"name": "__init__",
"signature": "def __init__(self, c_in: int, c_out: int=2, activation: str='Leaky... | 2 | stack_v2_sparse_classes_30k_train_042073 | Implement the Python class `SpectralConvolution` described below.
Class description:
Implementation of the spectral convolution.
Method signatures and docstrings:
- def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None): Args: c_in: int Number of input channels. c_out: int Numb... | Implement the Python class `SpectralConvolution` described below.
Class description:
Implementation of the spectral convolution.
Method signatures and docstrings:
- def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None): Args: c_in: int Number of input channels. c_out: int Numb... | 1bdfe7eabcdff257524ae773bcb806ca33700372 | <|skeleton|>
class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation functio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation function for the fin... | the_stack_v2_python_sparse | model/tig.py | j-huthmacher/Temporal-Info-Graph | train | 0 |
f502e1458a2372b927aaccd64e4a9575cd39ac14 | [
"try:\n value = self[key]\nexcept KeyError:\n if default is self.__marker:\n raise\n return default\nelse:\n del self[key]\n return value",
"try:\n key = next(iter(self))\nexcept StopIteration:\n raise KeyError\nvalue = self[key]\ndel self[key]\nreturn (key, value)",
"try:\n while... | <|body_start_0|>
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
<|end_body_0|>
<|body_start_1|>
try:
key = next(iter(self))... | MutableMapping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MutableMapping:
def pop(self, key, default=__marker):
"""D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised."""
<|body_0|>
def popitem(self):
"""D.popitem() => (k, v), ... | stack_v2_sparse_classes_75kplus_train_004608 | 4,598 | permissive | [
{
"docstring": "D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.",
"name": "pop",
"signature": "def pop(self, key, default=__marker)"
},
{
"docstring": "D.popitem() => (k, v), remove and return ... | 5 | stack_v2_sparse_classes_30k_train_023935 | Implement the Python class `MutableMapping` described below.
Class description:
Implement the MutableMapping class.
Method signatures and docstrings:
- def pop(self, key, default=__marker): D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwi... | Implement the Python class `MutableMapping` described below.
Class description:
Implement the MutableMapping class.
Method signatures and docstrings:
- def pop(self, key, default=__marker): D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwi... | 486e2e9332553240bcbd80e100d26bff58071709 | <|skeleton|>
class MutableMapping:
def pop(self, key, default=__marker):
"""D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised."""
<|body_0|>
def popitem(self):
"""D.popitem() => (k, v), ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MutableMapping:
def pop(self, key, default=__marker):
"""D.pop(k[,d]) => v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised."""
try:
value = self[key]
except KeyError:
if default ... | the_stack_v2_python_sparse | src/compas/datastructures/_mutablemapping.py | compas-dev/compas | train | 286 | |
6abbf73930f39df1d48f300e17ef5f448ef025a8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedRoleAssignment()",
"from .app_scope import AppScope\nfrom .directory_object import DirectoryObject\nfrom .entity import Entity\nfrom .unified_role_definition import UnifiedRoleDefinition\nfrom .app_scope import AppScope\nfrom .d... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UnifiedRoleAssignment()
<|end_body_0|>
<|body_start_1|>
from .app_scope import AppScope
from .directory_object import DirectoryObject
from .entity import Entity
from .uni... | UnifiedRoleAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_75kplus_train_004609 | 5,634 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UnifiedRoleAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_test_002150 | Implement the Python class `UnifiedRoleAssignment` described below.
Class description:
Implement the UnifiedRoleAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment: Creates a new instance of the appropriate class base... | Implement the Python class `UnifiedRoleAssignment` described below.
Class description:
Implement the UnifiedRoleAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/unified_role_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
7afb26e3e36c78a81fa66fe49253244b4f0bac3b | [
"config = ConfigParser.ConfigParser()\nconfig.read(cfg)\nfor section in config.sections():\n setattr(self, section, Dictionary())\n for name, raw_value in config.items(section):\n try:\n if config.get(section, name) in ['0', '1']:\n raise ValueError\n value = config... | <|body_start_0|>
config = ConfigParser.ConfigParser()
config.read(cfg)
for section in config.sections():
setattr(self, section, Dictionary())
for name, raw_value in config.items(section):
try:
if config.get(section, name) in ['0', '1']:... | Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, cfg='config.conf'):
"""@param file_name: file name without extension. @param cfg: configuration file path."""
<|body_0|>
def get(self, section):
"""Get option. @param section: section to fetch. @return: option value."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004610 | 1,928 | permissive | [
{
"docstring": "@param file_name: file name without extension. @param cfg: configuration file path.",
"name": "__init__",
"signature": "def __init__(self, cfg='config.conf')"
},
{
"docstring": "Get option. @param section: section to fetch. @return: option value.",
"name": "get",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_046048 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path.
- def get(self, section): Get option. @param section: secti... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path.
- def get(self, section): Get option. @param section: secti... | cec3f47692bc77fbdcb397ad7ec21c994328fc00 | <|skeleton|>
class Config:
def __init__(self, cfg='config.conf'):
"""@param file_name: file name without extension. @param cfg: configuration file path."""
<|body_0|>
def get(self, section):
"""Get option. @param section: section to fetch. @return: option value."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
def __init__(self, cfg='config.conf'):
"""@param file_name: file name without extension. @param cfg: configuration file path."""
config = ConfigParser.ConfigParser()
config.read(cfg)
for section in config.sections():
setattr(self, section, Dictionary())
... | the_stack_v2_python_sparse | deeploader/dataset/config.py | cnzeki/DeepLoader | train | 1 | |
ab731e3351915641e18e4cab0fa76b0fbf23af55 | [
"from h5py import File as h5\nfrom MDclt import parse_states\nself.coord_path, self.coord_address = coord\nself.inputs = [(self.coord_path, self.coord_address)]\nwith h5(self.coord_path) as coord_h5:\n coord_shape = coord_h5[self.coord_address].shape\nself.i = 0\nif len(coord_shape) > 1:\n self.n_molecule_1 =... | <|body_start_0|>
from h5py import File as h5
from MDclt import parse_states
self.coord_path, self.coord_address = coord
self.inputs = [(self.coord_path, self.coord_address)]
with h5(self.coord_path) as coord_h5:
coord_shape = coord_h5[self.coord_address].shape
... | Generator class that prepares blocks of analysis | Assign_Block_Generator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Assign_Block_Generator:
"""Generator class that prepares blocks of analysis"""
def __init__(self, coord, states, output, **kwargs):
"""Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output*: Tuple including path to h5 file and address within h5 ... | stack_v2_sparse_classes_75kplus_train_004611 | 15,407 | permissive | [
{
"docstring": "Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output*: Tuple including path to h5 file and address within h5 file :*force*: Run analysis even if no new data is present",
"name": "__init__",
"signature": "def __init__(self, coord, states, output, **... | 2 | null | Implement the Python class `Assign_Block_Generator` described below.
Class description:
Generator class that prepares blocks of analysis
Method signatures and docstrings:
- def __init__(self, coord, states, output, **kwargs): Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output... | Implement the Python class `Assign_Block_Generator` described below.
Class description:
Generator class that prepares blocks of analysis
Method signatures and docstrings:
- def __init__(self, coord, states, output, **kwargs): Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output... | 9e86e996ed7958a348012c053fa957d94729be8a | <|skeleton|>
class Assign_Block_Generator:
"""Generator class that prepares blocks of analysis"""
def __init__(self, coord, states, output, **kwargs):
"""Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output*: Tuple including path to h5 file and address within h5 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Assign_Block_Generator:
"""Generator class that prepares blocks of analysis"""
def __init__(self, coord, states, output, **kwargs):
"""Initializes generator **Arguments:** :*coord*: Coordinates used to make assignments :*output*: Tuple including path to h5 file and address within h5 file :*force*... | the_stack_v2_python_sparse | secondary/assign.py | KarlTDebiec/MDclt | train | 0 |
de9e8a130b9f4b595996a1d8448f286e4418f9c9 | [
"self._io = io\n'\\n The IO object.\\n\\n :type: cleo.styles.output_style.OutputStyle\\n '\nself._parent = parent\n'\\n The formatter for the parent node.\\n\\n :type: sdoc.sdoc2.formatter.Formatter.Formatter\\n '\nself._errors = 0\n'\\n The error count.\\n :t... | <|body_start_0|>
self._io = io
'\n The IO object.\n\n :type: cleo.styles.output_style.OutputStyle\n '
self._parent = parent
'\n The formatter for the parent node.\n\n :type: sdoc.sdoc2.formatter.Formatter.Formatter\n '
self._errors = 0
... | Abstract parent class for all formatters for generating the output of nodes in a requested format. | Formatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io, parent):
"""Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter pa... | stack_v2_sparse_classes_75kplus_train_004612 | 3,149 | permissive | [
{
"docstring": "Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter parent: The formatter for the parent node.",
"name": "__init__",
"signature": "def __init__(self, io, parent)"
},
{
"docstring": "Getter for the erro... | 4 | stack_v2_sparse_classes_30k_train_008736 | Implement the Python class `Formatter` described below.
Class description:
Abstract parent class for all formatters for generating the output of nodes in a requested format.
Method signatures and docstrings:
- def __init__(self, io, parent): Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO o... | Implement the Python class `Formatter` described below.
Class description:
Abstract parent class for all formatters for generating the output of nodes in a requested format.
Method signatures and docstrings:
- def __init__(self, io, parent): Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO o... | 0e201a00673277f390fc7d3a5af2bc018f4a6083 | <|skeleton|>
class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io, parent):
"""Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Formatter:
"""Abstract parent class for all formatters for generating the output of nodes in a requested format."""
def __init__(self, io, parent):
"""Object constructor. :param cleo.styles.output_style.OutputStyle io: The IO object. :param sdoc.sdoc2.formatter.Formatter.Formatter parent: The for... | the_stack_v2_python_sparse | sdoc/sdoc2/formatter/Formatter.py | OlegKlimenko/py-sdoc | train | 1 |
5f149ca45fd6be17ab8a68c8f981ecd76e593a9c | [
"try:\n error = response.json()['error']\n self._message = error['message']\n self.code = error['code']\n self.type = error['type']\nexcept:\n self._message = response.reason\n self.code = response.status_code\n self.type = PINN_ERROR_CODE_MAP[response.status_code]\nsuper(PinnError, self).__ini... | <|body_start_0|>
try:
error = response.json()['error']
self._message = error['message']
self.code = error['code']
self.type = error['type']
except:
self._message = response.reason
self.code = response.status_code
self.ty... | Base exception class for a Pinn API Error. | PinnError | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
<|body_0|>
def from_response(response):
"""Create an error of the right PinnError subclass from an API res... | stack_v2_sparse_classes_75kplus_train_004613 | 4,553 | permissive | [
{
"docstring": "Create a PinnError object with a response dictionary object.",
"name": "__init__",
"signature": "def __init__(self, response)"
},
{
"docstring": "Create an error of the right PinnError subclass from an API response.",
"name": "from_response",
"signature": "def from_respon... | 2 | stack_v2_sparse_classes_30k_train_007751 | Implement the Python class `PinnError` described below.
Class description:
Base exception class for a Pinn API Error.
Method signatures and docstrings:
- def __init__(self, response): Create a PinnError object with a response dictionary object.
- def from_response(response): Create an error of the right PinnError sub... | Implement the Python class `PinnError` described below.
Class description:
Base exception class for a Pinn API Error.
Method signatures and docstrings:
- def __init__(self, response): Create a PinnError object with a response dictionary object.
- def from_response(response): Create an error of the right PinnError sub... | d7d3f2d2a4cdc3eb01ae85a117c0e3d8bc1732bd | <|skeleton|>
class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
<|body_0|>
def from_response(response):
"""Create an error of the right PinnError subclass from an API res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PinnError:
"""Base exception class for a Pinn API Error."""
def __init__(self, response):
"""Create a PinnError object with a response dictionary object."""
try:
error = response.json()['error']
self._message = error['message']
self.code = error['code']... | the_stack_v2_python_sparse | pinn/errors.py | pinntech/pinn-python | train | 2 |
f5209629a1feeb4fa359c22fd1ba9dec48c679fe | [
"confirm = await helpers.yes_no(ctx, ctx.bot)\nif not confirm:\n return\nif ctx.invoked_with == 'kys':\n message = 'Dead! x.x'\nelse:\n message = 'Bot is going for halt NOW!'\nlogger.warning(message)\nawait ctx.send(message)\nawait ctx.bot.logout()\nsettings.save()",
"confirm = await helpers.yes_no(ctx, ... | <|body_start_0|>
confirm = await helpers.yes_no(ctx, ctx.bot)
if not confirm:
return
if ctx.invoked_with == 'kys':
message = 'Dead! x.x'
else:
message = 'Bot is going for halt NOW!'
logger.warning(message)
await ctx.send(message)
... | Commands that affect the bot's running process. | Process | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Process:
"""Commands that affect the bot's running process."""
async def halt(self, ctx):
"""Halt the bot. Only the bot owner can use this."""
<|body_0|>
async def restart(self, ctx):
"""Restart the bot. Only the bot owner can use this."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_004614 | 1,457 | permissive | [
{
"docstring": "Halt the bot. Only the bot owner can use this.",
"name": "halt",
"signature": "async def halt(self, ctx)"
},
{
"docstring": "Restart the bot. Only the bot owner can use this.",
"name": "restart",
"signature": "async def restart(self, ctx)"
}
] | 2 | null | Implement the Python class `Process` described below.
Class description:
Commands that affect the bot's running process.
Method signatures and docstrings:
- async def halt(self, ctx): Halt the bot. Only the bot owner can use this.
- async def restart(self, ctx): Restart the bot. Only the bot owner can use this. | Implement the Python class `Process` described below.
Class description:
Commands that affect the bot's running process.
Method signatures and docstrings:
- async def halt(self, ctx): Halt the bot. Only the bot owner can use this.
- async def restart(self, ctx): Restart the bot. Only the bot owner can use this.
<|sk... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Process:
"""Commands that affect the bot's running process."""
async def halt(self, ctx):
"""Halt the bot. Only the bot owner can use this."""
<|body_0|>
async def restart(self, ctx):
"""Restart the bot. Only the bot owner can use this."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Process:
"""Commands that affect the bot's running process."""
async def halt(self, ctx):
"""Halt the bot. Only the bot owner can use this."""
confirm = await helpers.yes_no(ctx, ctx.bot)
if not confirm:
return
if ctx.invoked_with == 'kys':
message ... | the_stack_v2_python_sparse | cogs/process.py | sokcheng/Kitsuchan-NG | train | 1 |
062aee282d5b2386fc0a1fbf538b80ae45fcf5c7 | [
"super().__init__(grid)\nsuper().initialize_output_fields()\nself._dist = grid.at_node['distance_to_divide']\nself.profiler = ChannelProfiler(grid, **kwds)\nself._save_full_df = save_full_df",
"if hasattr(self, '_df'):\n return self._df\nelse:\n raise RuntimeError('The hack_coefficient_dataframe does not ye... | <|body_start_0|>
super().__init__(grid)
super().initialize_output_fields()
self._dist = grid.at_node['distance_to_divide']
self.profiler = ChannelProfiler(grid, **kwds)
self._save_full_df = save_full_df
<|end_body_0|>
<|body_start_1|>
if hasattr(self, '_df'):
... | This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :math:`h` are parameters. The HackCalculator uses a ChannelProfiler to determine the... | HackCalculator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HackCalculator:
"""This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :math:`h` are parameters. The HackCalculat... | stack_v2_sparse_classes_75kplus_train_004615 | 11,823 | permissive | [
{
"docstring": "Parameters ---------- grid : Landlab Model Grid instance, required save_full_df: bool Flag indicating whether to create the ``full_hack_dataframe``. **kwds : Values to pass to the ChannelProfiler.",
"name": "__init__",
"signature": "def __init__(self, grid, save_full_df=False, **kwds)"
... | 4 | stack_v2_sparse_classes_30k_train_003795 | Implement the Python class `HackCalculator` described below.
Class description:
This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :ma... | Implement the Python class `HackCalculator` described below.
Class description:
This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :ma... | 1cd72e5832ece1aa922cd1b239e2e94ed0f11f8b | <|skeleton|>
class HackCalculator:
"""This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :math:`h` are parameters. The HackCalculat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HackCalculator:
"""This component calculates Hack's law parameters for drainage basins. Hacks law is given as ..:math: L = C * A**h Where :math:`L` is the distance to the drainage divide along the channel, :math:`A` is the drainage area, and :math:`C`and :math:`h` are parameters. The HackCalculator uses a Cha... | the_stack_v2_python_sparse | landlab/components/hack_calculator/hack_calculator.py | landlab/landlab | train | 326 |
0ab0b0c37a84d9b350b48acb1b70954d5714ac12 | [
"foo_path = str(tmpdir.join('foo'))\nos.mkdir(foo_path)\nargs.configure_mock(source=foo_path, name=None, destination=str(tmpdir))\nassert (foo_path, str(tmpdir.join('foo.docset'))) == main.setup_paths(args)\nabs_foo = os.path.abspath(foo_path)\nargs.source = abs_foo\nassert (abs_foo, str(tmpdir.join('foo.docset')) ... | <|body_start_0|>
foo_path = str(tmpdir.join('foo'))
os.mkdir(foo_path)
args.configure_mock(source=foo_path, name=None, destination=str(tmpdir))
assert (foo_path, str(tmpdir.join('foo.docset'))) == main.setup_paths(args)
abs_foo = os.path.abspath(foo_path)
args.source = ab... | TestSetupPaths | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSetupPaths:
def test_works(self, args, monkeypatch, tmpdir):
"""Integration test with mocked-out parser."""
<|body_0|>
def test_A_overrides_destination(self, args, monkeypatch):
"""Passing A computes the destination and overrides an argument."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_004616 | 35,122 | no_license | [
{
"docstring": "Integration test with mocked-out parser.",
"name": "test_works",
"signature": "def test_works(self, args, monkeypatch, tmpdir)"
},
{
"docstring": "Passing A computes the destination and overrides an argument.",
"name": "test_A_overrides_destination",
"signature": "def tes... | 5 | stack_v2_sparse_classes_30k_train_030656 | Implement the Python class `TestSetupPaths` described below.
Class description:
Implement the TestSetupPaths class.
Method signatures and docstrings:
- def test_works(self, args, monkeypatch, tmpdir): Integration test with mocked-out parser.
- def test_A_overrides_destination(self, args, monkeypatch): Passing A compu... | Implement the Python class `TestSetupPaths` described below.
Class description:
Implement the TestSetupPaths class.
Method signatures and docstrings:
- def test_works(self, args, monkeypatch, tmpdir): Integration test with mocked-out parser.
- def test_A_overrides_destination(self, args, monkeypatch): Passing A compu... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class TestSetupPaths:
def test_works(self, args, monkeypatch, tmpdir):
"""Integration test with mocked-out parser."""
<|body_0|>
def test_A_overrides_destination(self, args, monkeypatch):
"""Passing A computes the destination and overrides an argument."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSetupPaths:
def test_works(self, args, monkeypatch, tmpdir):
"""Integration test with mocked-out parser."""
foo_path = str(tmpdir.join('foo'))
os.mkdir(foo_path)
args.configure_mock(source=foo_path, name=None, destination=str(tmpdir))
assert (foo_path, str(tmpdir.jo... | the_stack_v2_python_sparse | repoData/hynek-doc2dash/allPythonContent.py | aCoffeeYin/pyreco | train | 0 | |
648e15b6487cc782000f151226a1ee7152d7f27d | [
"super(LightSpider, self).__init__()\nself._memory_db = MemoryDB()\nself._item_cache = ItemCache(redis_key='light_spider')\nself._redis_parser_name = []\nself._redis_cache = None\nself._parser_controller = []\nfor k, v in self.__class__.__common_settings__.items():\n setattr(common, k, v)\nself._thread_count = c... | <|body_start_0|>
super(LightSpider, self).__init__()
self._memory_db = MemoryDB()
self._item_cache = ItemCache(redis_key='light_spider')
self._redis_parser_name = []
self._redis_cache = None
self._parser_controller = []
for k, v in self.__class__.__common_settings... | LightSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightSpider:
def __init__(self, thread_count=None):
"""初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict"""
<|body_0|>
def add_task(self):
"""将 start_requests 中的任务Request对象存储到内存队列中 注意: 如果 start_requests执行的是死循环, 则 redis 无法记录心跳数据 :return: None"""
<|body... | stack_v2_sparse_classes_75kplus_train_004617 | 3,696 | permissive | [
{
"docstring": "初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict",
"name": "__init__",
"signature": "def __init__(self, thread_count=None)"
},
{
"docstring": "将 start_requests 中的任务Request对象存储到内存队列中 注意: 如果 start_requests执行的是死循环, 则 redis 无法记录心跳数据 :return: None",
"name": "add_task",
... | 4 | stack_v2_sparse_classes_30k_val_002304 | Implement the Python class `LightSpider` described below.
Class description:
Implement the LightSpider class.
Method signatures and docstrings:
- def __init__(self, thread_count=None): 初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict
- def add_task(self): 将 start_requests 中的任务Request对象存储到内存队列中 注意: 如果 start_r... | Implement the Python class `LightSpider` described below.
Class description:
Implement the LightSpider class.
Method signatures and docstrings:
- def __init__(self, thread_count=None): 初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict
- def add_task(self): 将 start_requests 中的任务Request对象存储到内存队列中 注意: 如果 start_r... | 464ba47176c005ed97005a79c5c4eee0bf0740b6 | <|skeleton|>
class LightSpider:
def __init__(self, thread_count=None):
"""初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict"""
<|body_0|>
def add_task(self):
"""将 start_requests 中的任务Request对象存储到内存队列中 注意: 如果 start_requests执行的是死循环, 则 redis 无法记录心跳数据 :return: None"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LightSpider:
def __init__(self, thread_count=None):
"""初始化配置 用户可自定义settings配置, 配置变量为__common_settings__, 类型为dict"""
super(LightSpider, self).__init__()
self._memory_db = MemoryDB()
self._item_cache = ItemCache(redis_key='light_spider')
self._redis_parser_name = []
... | the_stack_v2_python_sparse | fastspider/core/spiders/light_spider.py | 361keji/fastspider | train | 0 | |
62dcdd28680909f43f41ce88adf75be500b71e41 | [
"args = search_parser.parse_args(request)\ntry:\n query = args.get('query') or '[]'\n page = args.get('page')\n per_page = args.get('per_page')\n data = json.loads(query)\n res = facade.list_collections('document', data, page, per_page)\nexcept JSONDecodeError:\n raise gmap_exc.SearchException('Pa... | <|body_start_0|>
args = search_parser.parse_args(request)
try:
query = args.get('query') or '[]'
page = args.get('page')
per_page = args.get('per_page')
data = json.loads(query)
res = facade.list_collections('document', data, page, per_page)
... | Collections | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collections:
def get(self):
"""List all collections of kind document from DB."""
<|body_0|>
def post(self):
"""Create collection of kind document in DB."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = search_parser.parse_args(request)
... | stack_v2_sparse_classes_75kplus_train_004618 | 13,039 | permissive | [
{
"docstring": "List all collections of kind document from DB.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create collection of kind document in DB.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027906 | Implement the Python class `Collections` described below.
Class description:
Implement the Collections class.
Method signatures and docstrings:
- def get(self): List all collections of kind document from DB.
- def post(self): Create collection of kind document in DB. | Implement the Python class `Collections` described below.
Class description:
Implement the Collections class.
Method signatures and docstrings:
- def get(self): List all collections of kind document from DB.
- def post(self): Create collection of kind document in DB.
<|skeleton|>
class Collections:
def get(self... | 2fbbe96db9f6a1d34a6c886662383a42534a6a1a | <|skeleton|>
class Collections:
def get(self):
"""List all collections of kind document from DB."""
<|body_0|>
def post(self):
"""Create collection of kind document in DB."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collections:
def get(self):
"""List all collections of kind document from DB."""
args = search_parser.parse_args(request)
try:
query = args.get('query') or '[]'
page = args.get('page')
per_page = args.get('per_page')
data = json.loads(que... | the_stack_v2_python_sparse | globomap_api/api/v2/endpoints/collections.py | globocom/globomap-api | train | 16 | |
cd9b5f8dcd286dfd43ee4a0d73d79bbb7fd15e1d | [
"QDialog.__init__(self, parent)\nself.setupUi(self)\nself.method = method\nif method == 0:\n self.label_4.setText(u'默认模型')\nelif method == 1:\n self.label_4.setText(u'CNN')\nelse:\n pass\nself.imgPath = None\nself.resultPath = None",
"self.imgPath = QtGui.QFileDialog.getOpenFileName(self, u'选择图片', '/', u... | <|body_start_0|>
QDialog.__init__(self, parent)
self.setupUi(self)
self.method = method
if method == 0:
self.label_4.setText(u'默认模型')
elif method == 1:
self.label_4.setText(u'CNN')
else:
pass
self.imgPath = None
self.res... | Class documentation goes here. | FaceDetectDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceDetectDialog:
"""Class documentation goes here."""
def __init__(self, method=0, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_clicked(self):
"""打开图片"""
<|body_1|>
def on_pushButton_2_clicked(self):
"""人脸检测"""
<|body... | stack_v2_sparse_classes_75kplus_train_004619 | 3,210 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, method=0, parent=None)"
},
{
"docstring": "打开图片",
"name": "on_pushButton_clicked",
"signature": "def on_pushButton_clicked(self)"
},
{
"docstring": "人脸检测",
"name": "on_pushButton_2_clicked",
... | 3 | stack_v2_sparse_classes_30k_train_054086 | Implement the Python class `FaceDetectDialog` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, method=0, parent=None): Constructor
- def on_pushButton_clicked(self): 打开图片
- def on_pushButton_2_clicked(self): 人脸检测 | Implement the Python class `FaceDetectDialog` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, method=0, parent=None): Constructor
- def on_pushButton_clicked(self): 打开图片
- def on_pushButton_2_clicked(self): 人脸检测
<|skeleton|>
class FaceDetectDi... | c3cb07f83642873a3460ffe489c82505923c3c1a | <|skeleton|>
class FaceDetectDialog:
"""Class documentation goes here."""
def __init__(self, method=0, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_clicked(self):
"""打开图片"""
<|body_1|>
def on_pushButton_2_clicked(self):
"""人脸检测"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FaceDetectDialog:
"""Class documentation goes here."""
def __init__(self, method=0, parent=None):
"""Constructor"""
QDialog.__init__(self, parent)
self.setupUi(self)
self.method = method
if method == 0:
self.label_4.setText(u'默认模型')
elif method ... | the_stack_v2_python_sparse | dlib_face_detection/gui/FaceDetectGui.py | rickding/HelloPython | train | 2 |
eeaea2fcb6afaf96c58e4ecf938f6d982261cb57 | [
"if color is None:\n color = next(self.default_graph_colors_cycle)\nif x_min is None:\n x_min = self.x_min\nif x_max is None:\n x_max = self.x_max\n\ndef parameterized_function(alpha):\n x = interpolate(x_min, x_max, alpha)\n y = func(x)\n return self.coords_to_point(x, y)\ngraph = NewParametricFu... | <|body_start_0|>
if color is None:
color = next(self.default_graph_colors_cycle)
if x_min is None:
x_min = self.x_min
if x_max is None:
x_max = self.x_max
def parameterized_function(alpha):
x = interpolate(x_min, x_max, alpha)
... | NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) - 绘制函数图像 draw function graph >>> self.add_function_graph( lambda x: x**x, animat... | NewGraphScene | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewGraphScene:
"""NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) - 绘制函数图像 draw function graph >>> self.a... | stack_v2_sparse_classes_75kplus_train_004620 | 7,209 | permissive | [
{
"docstring": "向场景中添加函数图像。 Add a function graph to scene.",
"name": "add_function_graph",
"signature": "def add_function_graph(self, func, animate=False, color=None, x_min=None, x_max=None, **kwargs)"
},
{
"docstring": "向场景中添加参数方程。 Add a parametric function graph to scene.",
"name": "add_pa... | 3 | stack_v2_sparse_classes_30k_train_028677 | Implement the Python class `NewGraphScene` described below.
Class description:
NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) ... | Implement the Python class `NewGraphScene` described below.
Class description:
NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) ... | f7dae90f25389b40f8c28f3eb7b6201170e54c97 | <|skeleton|>
class NewGraphScene:
"""NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) - 绘制函数图像 draw function graph >>> self.a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewGraphScene:
"""NewGraphScene by GZTime. To use: - 更新函数展示区域,定义域和坐标轴位置同GraphScene,此项设置需要在setup_axes前完成。 >>> self.graph_origin = ORIGIN >>> self.x_min, self.x_max = -5,5 >>> self.y_min, self.y_max = -5,5 - 新建坐标轴 create axes >>> self.setup_axes(animate=True) - 绘制函数图像 draw function graph >>> self.add_function_g... | the_stack_v2_python_sparse | utils/scenes/NewGraphScene.py | manim-kindergarten/manim_sandbox | train | 439 |
02873659d7bdabbbbad78f84c585c91fc56abfd0 | [
"self.title = title\nself.description = jsondata.get('description', '')\n_verbose(\" Pod '{}': {}\".format(self.title, self.description))\nself.servers = [Server(data) for data in jsondata.get('servers', [])]\nfor ctr, server in enumerate(self.servers):\n _verbose(' Server: {}'.format(server.sockname))\n ... | <|body_start_0|>
self.title = title
self.description = jsondata.get('description', '')
_verbose(" Pod '{}': {}".format(self.title, self.description))
self.servers = [Server(data) for data in jsondata.get('servers', [])]
for ctr, server in enumerate(self.servers):
_ve... | Model object that represents an L{Pod}. | Pod | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
<|body_0|>
def sendSock(self):
"""Update the data for each L{Server} in this L{Pod}."""
... | stack_v2_sparse_classes_75kplus_train_004621 | 14,800 | permissive | [
{
"docstring": "Parse the pod details from the JSON data and create the list of L{Server}'s.",
"name": "__init__",
"signature": "def __init__(self, title, jsondata)"
},
{
"docstring": "Update the data for each L{Server} in this L{Pod}.",
"name": "sendSock",
"signature": "def sendSock(sel... | 3 | stack_v2_sparse_classes_30k_train_036303 | Implement the Python class `Pod` described below.
Class description:
Model object that represents an L{Pod}.
Method signatures and docstrings:
- def __init__(self, title, jsondata): Parse the pod details from the JSON data and create the list of L{Server}'s.
- def sendSock(self): Update the data for each L{Server} in... | Implement the Python class `Pod` described below.
Class description:
Model object that represents an L{Pod}.
Method signatures and docstrings:
- def __init__(self, title, jsondata): Parse the pod details from the JSON data and create the list of L{Server}'s.
- def sendSock(self): Update the data for each L{Server} in... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
<|body_0|>
def sendSock(self):
"""Update the data for each L{Server} in this L{Pod}."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pod:
"""Model object that represents an L{Pod}."""
def __init__(self, title, jsondata):
"""Parse the pod details from the JSON data and create the list of L{Server}'s."""
self.title = title
self.description = jsondata.get('description', '')
_verbose(" Pod '{}': {}".format... | the_stack_v2_python_sparse | calendarserver/tools/dashcollect.py | ass-a2s/ccs-calendarserver | train | 2 |
20deb9b033922f28158bbe6025d0e67d8ae19838 | [
"self.input_path = input_path\npath = Path(input_path)\nself.gen_path = path.parent\njsonfile = 'organized.json'\nobj_props = lab2mat.load(os.path.join(self.gen_path, jsonfile))\nself.rawdata_path = os.path.join(self.gen_path, 'filt_data')\nverpred_path = 'verified_predictions'\nobj_props.update({'verpred_path': ve... | <|body_start_0|>
self.input_path = input_path
path = Path(input_path)
self.gen_path = path.parent
jsonfile = 'organized.json'
obj_props = lab2mat.load(os.path.join(self.gen_path, jsonfile))
self.rawdata_path = os.path.join(self.gen_path, 'filt_data')
verpred_path ... | Class for User verification of detected seizures | UserVerify | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
<|body_0|>
def get_feature_pred(self, file_id):
"""get_feature_pred(self, file_id... | stack_v2_sparse_classes_75kplus_train_004622 | 10,529 | permissive | [
{
"docstring": "lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.",
"name": "__init__",
"signature": "def __init__(self, input_path)"
},
{
"docstring": "get_feature_pred(self, file_id) Parameters ---------- file_id : Str Returns ------- data : 3d Numpy Array (1D = segm... | 5 | stack_v2_sparse_classes_30k_train_049168 | Implement the Python class `UserVerify` described below.
Class description:
Class for User verification of detected seizures
Method signatures and docstrings:
- def __init__(self, input_path): lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.
- def get_feature_pred(self, file_id): get_featu... | Implement the Python class `UserVerify` described below.
Class description:
Class for User verification of detected seizures
Method signatures and docstrings:
- def __init__(self, input_path): lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data.
- def get_feature_pred(self, file_id): get_featu... | fd238749a8b80af1bd0902f737bc9017c4e29756 | <|skeleton|>
class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
<|body_0|>
def get_feature_pred(self, file_id):
"""get_feature_pred(self, file_id... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserVerify:
"""Class for User verification of detected seizures"""
def __init__(self, input_path):
"""lab2mat(main_path) Parameters ---------- input_path : Str, Path to raw data."""
self.input_path = input_path
path = Path(input_path)
self.gen_path = path.parent
js... | the_stack_v2_python_sparse | user_gui/UserVerify_instant.py | bhargavaganti/logic_seizedetect | train | 0 |
ff46e3c92c76254a545f79bbd6d3cd1d66f4ab95 | [
"super().__init__(network_name, checkpoint_timestamp, wm_timestamp)\nself.batch_size = batch_size\nself.latent_size = 32\nself.hidden_size = 256\nself.gaussian_size = 8\nself.main_net = GraphAENetwork(edge_model_layer_size=edge_model_layer_size, node_model_layer_size=node_model_layer_size, global_layer_size=self.la... | <|body_start_0|>
super().__init__(network_name, checkpoint_timestamp, wm_timestamp)
self.batch_size = batch_size
self.latent_size = 32
self.hidden_size = 256
self.gaussian_size = 8
self.main_net = GraphAENetwork(edge_model_layer_size=edge_model_layer_size, node_model_laye... | MBAgentV2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBAgentV2:
def __init__(self, batch_size, num_actions, num_locations=100, reducer=tf.math.unsorted_segment_sum, pi_learning_rate=0.001, vf_learning_rate=0.001, message_passing_steps=5, edge_model_layer_size=8, num_edge_layers=2, node_model_layer_size=8, num_node_layers=2, global_layer_size=8, nu... | stack_v2_sparse_classes_75kplus_train_004623 | 25,720 | no_license | [
{
"docstring": "Args: num_actions (int): Number of discrete actions to choose from. num_locations (int): Number of discrete locations to choose from for each xfer reducer (Union[tf.unsorted_segment_sum, tf.unsorted_segment_mean, tf.unsorted_segment_max, tf.unsorted_segment_min, tf.unsorted_segment_prod, tf.unso... | 3 | stack_v2_sparse_classes_30k_train_040975 | Implement the Python class `MBAgentV2` described below.
Class description:
Implement the MBAgentV2 class.
Method signatures and docstrings:
- def __init__(self, batch_size, num_actions, num_locations=100, reducer=tf.math.unsorted_segment_sum, pi_learning_rate=0.001, vf_learning_rate=0.001, message_passing_steps=5, ed... | Implement the Python class `MBAgentV2` described below.
Class description:
Implement the MBAgentV2 class.
Method signatures and docstrings:
- def __init__(self, batch_size, num_actions, num_locations=100, reducer=tf.math.unsorted_segment_sum, pi_learning_rate=0.001, vf_learning_rate=0.001, message_passing_steps=5, ed... | 826ce08113678aacf1c19228ae8096a0a69d52e7 | <|skeleton|>
class MBAgentV2:
def __init__(self, batch_size, num_actions, num_locations=100, reducer=tf.math.unsorted_segment_sum, pi_learning_rate=0.001, vf_learning_rate=0.001, message_passing_steps=5, edge_model_layer_size=8, num_edge_layers=2, node_model_layer_size=8, num_node_layers=2, global_layer_size=8, nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MBAgentV2:
def __init__(self, batch_size, num_actions, num_locations=100, reducer=tf.math.unsorted_segment_sum, pi_learning_rate=0.001, vf_learning_rate=0.001, message_passing_steps=5, edge_model_layer_size=8, num_edge_layers=2, node_model_layer_size=8, num_node_layers=2, global_layer_size=8, num_global_layer... | the_stack_v2_python_sparse | xflowrl/agents/mb_agent.py | seanjparker/rlflow | train | 0 | |
ea8ad6ff1c8eb443684dcf7e4ba8e560c1242348 | [
"lender = self.rate_quote_request.get_par_lender(term, amortization)\nscenarios = self.rate_quote_request.get_scenarios(term, amortization)\npar_lender = self.serializer(lender).data\ndata = self.serializer(scenarios, many=True).data\nresults = {'par_lender': par_lender if par_lender else None, 'request_uuid': self... | <|body_start_0|>
lender = self.rate_quote_request.get_par_lender(term, amortization)
scenarios = self.rate_quote_request.get_scenarios(term, amortization)
par_lender = self.serializer(lender).data
data = self.serializer(scenarios, many=True).data
results = {'par_lender': par_lend... | Returns rate quote request and rate quote view results. | RateQuoteMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateQuoteMixin:
"""Returns rate quote request and rate quote view results."""
def get_results(self, term=None, amortization=None):
"""Returns rate quote results. Every result object includes the par_lender and matching scenarios. :param term: str, term :param amortization: str, amort... | stack_v2_sparse_classes_75kplus_train_004624 | 14,021 | no_license | [
{
"docstring": "Returns rate quote results. Every result object includes the par_lender and matching scenarios. :param term: str, term :param amortization: str, amortization :return: rate quotes :rtype: `dict`",
"name": "get_results",
"signature": "def get_results(self, term=None, amortization=None)"
... | 2 | stack_v2_sparse_classes_30k_train_039401 | Implement the Python class `RateQuoteMixin` described below.
Class description:
Returns rate quote request and rate quote view results.
Method signatures and docstrings:
- def get_results(self, term=None, amortization=None): Returns rate quote results. Every result object includes the par_lender and matching scenario... | Implement the Python class `RateQuoteMixin` described below.
Class description:
Returns rate quote request and rate quote view results.
Method signatures and docstrings:
- def get_results(self, term=None, amortization=None): Returns rate quote results. Every result object includes the par_lender and matching scenario... | f1a8cd8268d032ea8321e1588e226da09925b7aa | <|skeleton|>
class RateQuoteMixin:
"""Returns rate quote request and rate quote view results."""
def get_results(self, term=None, amortization=None):
"""Returns rate quote results. Every result object includes the par_lender and matching scenarios. :param term: str, term :param amortization: str, amort... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RateQuoteMixin:
"""Returns rate quote request and rate quote view results."""
def get_results(self, term=None, amortization=None):
"""Returns rate quote results. Every result object includes the par_lender and matching scenarios. :param term: str, term :param amortization: str, amortization :retu... | the_stack_v2_python_sparse | website/apps/mortgage_profiles/views.py | protoprojects/worksample | train | 0 |
680b3b451cef16c3dc0ebe3fee2a2574722effb6 | [
"point_map = zip(range(len(height)), height)\nmax_area = 0\nfor a, b in itertools.combinations(point_map, 2):\n area = abs(a[0] - b[0]) * min(a[1], b[1])\n max_area = area if area > max_area else max_area\nreturn max_area",
"left = ans = 0\nright = len(height) - 1\nwhile left < right:\n ans = max(ans, (r... | <|body_start_0|>
point_map = zip(range(len(height)), height)
max_area = 0
for a, b in itertools.combinations(point_map, 2):
area = abs(a[0] - b[0]) * min(a[1], b[1])
max_area = area if area > max_area else max_area
return max_area
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
point_map = zip(range(len(height)), height)
... | stack_v2_sparse_classes_75kplus_train_004625 | 1,768 | permissive | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "_maxArea",
"signature": "def _maxArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006489 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def _maxArea(s... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _maxArea(self, height):
""":type height: List[int] :rtype: int"""
point_map = zip(range(len(height)), height)
max_area = 0
for a, b in itertools.combinations(point_map, 2):
area = abs(a[0] - b[0]) * min(a[1], b[1])
max_area = area if area >... | the_stack_v2_python_sparse | 11.container-with-most-water.py | windard/leeeeee | train | 0 | |
1bc07a6437a36aa4e4fb099fcf8dfeca68d30917 | [
"self.web_address = ip\nself.web_port = port\nself.httpd = None\nself.bind_url = url",
"HttpServers.signal.signal(HttpServers.signal.SIGINT, self.shutdown)\nself.httpd = HttpServers.Server((self.web_address, self.web_port), SimpleHTTPRequestHandler)\nif not self.bind_url:\n self.bind_url = 'http://' + self.web... | <|body_start_0|>
self.web_address = ip
self.web_port = port
self.httpd = None
self.bind_url = url
<|end_body_0|>
<|body_start_1|>
HttpServers.signal.signal(HttpServers.signal.SIGINT, self.shutdown)
self.httpd = HttpServers.Server((self.web_address, self.web_port), Simple... | HttpServers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpServers:
def __init__(self, ip='localhost', port=8000, url=''):
"""http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url"""
<|body_0|>
def start(self):
"""开启http服务 Start the HTTP service :return: None"""
<|bo... | stack_v2_sparse_classes_75kplus_train_004626 | 1,716 | permissive | [
{
"docstring": "http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url",
"name": "__init__",
"signature": "def __init__(self, ip='localhost', port=8000, url='')"
},
{
"docstring": "开启http服务 Start the HTTP service :return: None",
"name": "start",
... | 3 | stack_v2_sparse_classes_30k_train_040439 | Implement the Python class `HttpServers` described below.
Class description:
Implement the HttpServers class.
Method signatures and docstrings:
- def __init__(self, ip='localhost', port=8000, url=''): http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url
- def start(self... | Implement the Python class `HttpServers` described below.
Class description:
Implement the HttpServers class.
Method signatures and docstrings:
- def __init__(self, ip='localhost', port=8000, url=''): http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url
- def start(self... | 93df83dbdccd9b2bb3e64c870b4a00c7073f1cc9 | <|skeleton|>
class HttpServers:
def __init__(self, ip='localhost', port=8000, url=''):
"""http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url"""
<|body_0|>
def start(self):
"""开启http服务 Start the HTTP service :return: None"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpServers:
def __init__(self, ip='localhost', port=8000, url=''):
"""http服务类初始化 HTTP service class initialization :param ip: 绑定的ip :param port: 端口 :param url: 对外显示的访问url"""
self.web_address = ip
self.web_port = port
self.httpd = None
self.bind_url = url
def start... | the_stack_v2_python_sparse | QuickStart_Rhy/NetTools/HttpServer.py | Slian22/QuickStart | train | 0 | |
e094adcc06d95287efec38b54ea8121981a9f329 | [
"return_data = []\nfor minion_id in minions:\n try:\n history = salt_returns.objects.filter(id=minion_id)\n for job in history:\n full_ret = job.full_ret\n return_data.append({'id': job.id, 'full_ret': full_ret, 'fun': job.fun, 'jid': job.jid, 'comment': job.return_value, 'suc... | <|body_start_0|>
return_data = []
for minion_id in minions:
try:
history = salt_returns.objects.filter(id=minion_id)
for job in history:
full_ret = job.full_ret
return_data.append({'id': job.id, 'full_ret': full_ret, 'fu... | API to retrieve data from salt_returns for a group of minions | JobHistoryListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobHistoryListView:
"""API to retrieve data from salt_returns for a group of minions"""
def get_minion_job_history(self, minions, page_number):
"""Loop through minions and get their job history. Then parse it a bit."""
<|body_0|>
def list(self, request, *args, **kwargs):... | stack_v2_sparse_classes_75kplus_train_004627 | 47,872 | no_license | [
{
"docstring": "Loop through minions and get their job history. Then parse it a bit.",
"name": "get_minion_job_history",
"signature": "def get_minion_job_history(self, minions, page_number)"
},
{
"docstring": "Since we have two different front ends sending data, we need some awkward logic to see... | 2 | stack_v2_sparse_classes_30k_train_034928 | Implement the Python class `JobHistoryListView` described below.
Class description:
API to retrieve data from salt_returns for a group of minions
Method signatures and docstrings:
- def get_minion_job_history(self, minions, page_number): Loop through minions and get their job history. Then parse it a bit.
- def list(... | Implement the Python class `JobHistoryListView` described below.
Class description:
API to retrieve data from salt_returns for a group of minions
Method signatures and docstrings:
- def get_minion_job_history(self, minions, page_number): Loop through minions and get their job history. Then parse it a bit.
- def list(... | 122a172caea82ef660e81a9dfc6377afd731f9cb | <|skeleton|>
class JobHistoryListView:
"""API to retrieve data from salt_returns for a group of minions"""
def get_minion_job_history(self, minions, page_number):
"""Loop through minions and get their job history. Then parse it a bit."""
<|body_0|>
def list(self, request, *args, **kwargs):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobHistoryListView:
"""API to retrieve data from salt_returns for a group of minions"""
def get_minion_job_history(self, minions, page_number):
"""Loop through minions and get their job history. Then parse it a bit."""
return_data = []
for minion_id in minions:
try:
... | the_stack_v2_python_sparse | sso/files/gui/sse/job/views.py | nofxrok/headless | train | 1 |
3c447cac5f483a621659155edeb80757ecd02d84 | [
"n = len(nums)\nk = k % n\nif not nums or k == 0:\n return\nnums[:] = nums[n - k:] + nums[:n - k]",
"def swap(a, b):\n nums[a], nums[b] = (nums[b], nums[a])\n\ndef reverse_nums(left, right):\n n = len(nums)\n while right < n and left < right:\n swap(left, right)\n left += 1\n righ... | <|body_start_0|>
n = len(nums)
k = k % n
if not nums or k == 0:
return
nums[:] = nums[n - k:] + nums[:n - k]
<|end_body_0|>
<|body_start_1|>
def swap(a, b):
nums[a], nums[b] = (nums[b], nums[a])
def reverse_nums(left, right):
n = len(... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 15.2 MB, less than 5.09% of Python3 online submissions for Rotate Array."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004628 | 1,646 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 15.2 MB, less than 5.09% of Python3 online submissions for Rotate Array.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 1... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 1... | 9d7759bea1f44673c2de4f25a94b27368928a59f | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 15.2 MB, less than 5.09% of Python3 online submissions for Rotate Array."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead Runtime: 68 ms, faster than 93.41% of Python3 online submissions for Rotate Array. Memory Usage: 15.2 MB, less than 5.09% of Python3 online submissions for Rotate Array."""
n = len(nums)
k = k ... | the_stack_v2_python_sparse | leetcode/easy_top_interview_question/array/rotate_array.py | pagsamo/google-tech-dev-guide | train | 0 | |
1893342d63e85da32ea66977453292a0a8a8c60f | [
"super().__init__(env)\nobs_space = env.observation_space\nif isinstance(obs_space, gym.spaces.tuple.Tuple):\n self.observation_space = gym.spaces.Box(low=np.min(obs_space[0].low), high=np.max(obs_space[0].high), shape=(len(obs_space), obs_space[0].shape[2], obs_space[0].shape[0], obs_space[0].shape[1]), dtype=o... | <|body_start_0|>
super().__init__(env)
obs_space = env.observation_space
if isinstance(obs_space, gym.spaces.tuple.Tuple):
self.observation_space = gym.spaces.Box(low=np.min(obs_space[0].low), high=np.max(obs_space[0].high), shape=(len(obs_space), obs_space[0].shape[2], obs_space[0].... | Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space`` | ObsTransposeWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObsTransposeWrapper:
"""Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space``"""
def __init__(self, env):
"""Overview: Initial... | stack_v2_sparse_classes_75kplus_train_004629 | 34,056 | permissive | [
{
"docstring": "Overview: Initialize ``self.`` See ``help(type(self))`` for accurate signature; setup the properties. Arguments: - env (:obj:`gym.Env`): the environment to wrap.",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": "Overview: Returns the transposed obser... | 3 | null | Implement the Python class `ObsTransposeWrapper` described below.
Class description:
Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space``
Method signatures and... | Implement the Python class `ObsTransposeWrapper` described below.
Class description:
Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space``
Method signatures and... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ObsTransposeWrapper:
"""Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space``"""
def __init__(self, env):
"""Overview: Initial... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObsTransposeWrapper:
"""Overview: Wrapper to transpose env, usually used in atari environments Interface: ``__init__``, ``observation``, ``new_shape`` Properties: - env (:obj:`gym.Env`): the environment to wrap. - ``observation_space``"""
def __init__(self, env):
"""Overview: Initialize ``self.``... | the_stack_v2_python_sparse | ding/envs/env_wrappers/env_wrappers.py | shengxuesun/DI-engine | train | 1 |
82b4d39cdc62dbc3220b474fde0ff1d0991773f2 | [
"super().__init__()\nself.register_class(Http)\nself.register_class(PathMapper)",
"try:\n next(self.query_rule('allow', actor, action, resource))\n return True\nexcept StopIteration:\n return False"
] | <|body_start_0|>
super().__init__()
self.register_class(Http)
self.register_class(PathMapper)
<|end_body_0|>
<|body_start_1|>
try:
next(self.query_rule('allow', actor, action, resource))
return True
except StopIteration:
return False
<|end_bod... | The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100> | Oso | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Oso:
"""The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100>"""
def __init__(self):
"""Create an oso object."""
<|body_0|>
def is_allowed(self, actor, action, resource) -> bool:
... | stack_v2_sparse_classes_75kplus_train_004630 | 1,582 | permissive | [
{
"docstring": "Create an oso object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Evaluate whether ``actor`` is allowed to perform ``action`` on ``resource``. Uses allow rules in the Polar policy to determine whether a request is permitted. ``actor`` and ``resource... | 2 | null | Implement the Python class `Oso` described below.
Class description:
The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100>
Method signatures and docstrings:
- def __init__(self): Create an oso object.
- def is_allowed(self, actor... | Implement the Python class `Oso` described below.
Class description:
The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100>
Method signatures and docstrings:
- def __init__(self): Create an oso object.
- def is_allowed(self, actor... | e421c9e74273eaaceed66e177661349ab2155e56 | <|skeleton|>
class Oso:
"""The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100>"""
def __init__(self):
"""Create an oso object."""
<|body_0|>
def is_allowed(self, actor, action, resource) -> bool:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Oso:
"""The central object to manage application policy state, e.g. the policy data, and verify requests. >>> Oso() <oso.Oso object at 0x7fad57305100>"""
def __init__(self):
"""Create an oso object."""
super().__init__()
self.register_class(Http)
self.register_class(PathMa... | the_stack_v2_python_sparse | .venv/lib/python3.8/site-packages/oso/oso.py | SandroRMio/curso-flask-1 | train | 1 |
69ec0e59d8dcbe48569a36647d1bf781e9181daf | [
"model = self._meta.verbose_name.title()\ntitle = self.title or str(_('Empty title'))\nreturn f'{model:s}: {title:s}'",
"if self.__class__.objects.filter(master__draft_course_run__translations__pk=self.pk, language_code=self.language_code).exclude(title=self.title).exists():\n self.master.direct_course.extende... | <|body_start_0|>
model = self._meta.verbose_name.title()
title = self.title or str(_('Empty title'))
return f'{model:s}: {title:s}'
<|end_body_0|>
<|body_start_1|>
if self.__class__.objects.filter(master__draft_course_run__translations__pk=self.pk, language_code=self.language_code).excl... | CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields. | CourseRunTranslation | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
<|body_0|>
def save(self, *args, **kwargs):
"""Mark rel... | stack_v2_sparse_classes_75kplus_train_004631 | 42,905 | permissive | [
{
"docstring": "Human representation of a course run translation.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Mark related course page dirty if the title has changed compared to the public version.",
"name": "save",
"signature": "def save(self, *args, **kwarg... | 2 | stack_v2_sparse_classes_30k_test_000895 | Implement the Python class `CourseRunTranslation` described below.
Class description:
CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields.
Method signatures and docstrings:
- def __str__(self): Human representation of a course run translation.
- def save(self, *args... | Implement the Python class `CourseRunTranslation` described below.
Class description:
CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields.
Method signatures and docstrings:
- def __str__(self): Human representation of a course run translation.
- def save(self, *args... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
<|body_0|>
def save(self, *args, **kwargs):
"""Mark rel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CourseRunTranslation:
"""CourseRun Translation model. Django parler model linked to the CourseRun to internationalize the fields."""
def __str__(self):
"""Human representation of a course run translation."""
model = self._meta.verbose_name.title()
title = self.title or str(_('Empt... | the_stack_v2_python_sparse | src/richie/apps/courses/models/course.py | openfun/richie | train | 238 |
07880d63e4fdeb2d0abd19fc2bc6bf2ec8b55f5c | [
"parts_regex = re.compile('\\\\#(?P<id>\\\\d+)' + ' *@ *' + '(?P<from_left>\\\\d+)' + ' *, *' + '(?P<from_top>\\\\d+)' + ' *: *' + '(?P<width>\\\\d+)x(?P<height>\\\\d+)')\nresult = parts_regex.match(str_)\nif not result:\n raise ValueError(f'String {str_} does not look like a claim string.')\ngroups = {k: int(v)... | <|body_start_0|>
parts_regex = re.compile('\\#(?P<id>\\d+)' + ' *@ *' + '(?P<from_left>\\d+)' + ' *, *' + '(?P<from_top>\\d+)' + ' *: *' + '(?P<width>\\d+)x(?P<height>\\d+)')
result = parts_regex.match(str_)
if not result:
raise ValueError(f'String {str_} does not look like a claim s... | Represents an individual Elf's claim to the fabric. | Claim | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Claim:
"""Represents an individual Elf's claim to the fabric."""
def from_string(cls, str_):
"""Returns a claim object corresponding to the given string."""
<|body_0|>
def squares_occupied(self):
"""Returns a generator of the coordinates of all squares occupied b... | stack_v2_sparse_classes_75kplus_train_004632 | 1,921 | permissive | [
{
"docstring": "Returns a claim object corresponding to the given string.",
"name": "from_string",
"signature": "def from_string(cls, str_)"
},
{
"docstring": "Returns a generator of the coordinates of all squares occupied by this claim.",
"name": "squares_occupied",
"signature": "def sq... | 2 | null | Implement the Python class `Claim` described below.
Class description:
Represents an individual Elf's claim to the fabric.
Method signatures and docstrings:
- def from_string(cls, str_): Returns a claim object corresponding to the given string.
- def squares_occupied(self): Returns a generator of the coordinates of a... | Implement the Python class `Claim` described below.
Class description:
Represents an individual Elf's claim to the fabric.
Method signatures and docstrings:
- def from_string(cls, str_): Returns a claim object corresponding to the given string.
- def squares_occupied(self): Returns a generator of the coordinates of a... | 9e380f48dbddb1bc689718125cada76782bed6ca | <|skeleton|>
class Claim:
"""Represents an individual Elf's claim to the fabric."""
def from_string(cls, str_):
"""Returns a claim object corresponding to the given string."""
<|body_0|>
def squares_occupied(self):
"""Returns a generator of the coordinates of all squares occupied b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Claim:
"""Represents an individual Elf's claim to the fabric."""
def from_string(cls, str_):
"""Returns a claim object corresponding to the given string."""
parts_regex = re.compile('\\#(?P<id>\\d+)' + ' *@ *' + '(?P<from_left>\\d+)' + ' *, *' + '(?P<from_top>\\d+)' + ' *: *' + '(?P<width... | the_stack_v2_python_sparse | python/2018/3/common.py | naiveai/adventofcode | train | 1 |
a9c397df79e7bb4099eaf8e16e37f19846379faf | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessPackageAssignment()",
"from .access_package import AccessPackage\nfrom .access_package_assignment_policy import AccessPackageAssignmentPolicy\nfrom .access_package_assignment_state import AccessPackageAssignmentState\nfrom .acces... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessPackageAssignment()
<|end_body_0|>
<|body_start_1|>
from .access_package import AccessPackage
from .access_package_assignment_policy import AccessPackageAssignmentPolicy
fr... | AccessPackageAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPackageAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_75kplus_train_004633 | 6,146 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AccessPackageAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_000187 | Implement the Python class `AccessPackageAssignment` described below.
Class description:
Implement the AccessPackageAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignment: Creates a new instance of the appropriate clas... | Implement the Python class `AccessPackageAssignment` described below.
Class description:
Implement the AccessPackageAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignment: Creates a new instance of the appropriate clas... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessPackageAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccessPackageAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | the_stack_v2_python_sparse | msgraph/generated/models/access_package_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
51a6953a99c64b1472d9f7ff294731f487515edc | [
"result = OCR().baidu_ocr(img_path)\nwords_result = result['words_result']\nif not words_result:\n result = OCR().python_ocr(img_path)\nreturn result",
"result = {}\nif platform == 'baidu':\n baidu_api = Images(pre_img, rear_img)\n res_add = baidu_api.baidu_save_image()\n cont_sign = res_add.get('cont... | <|body_start_0|>
result = OCR().baidu_ocr(img_path)
words_result = result['words_result']
if not words_result:
result = OCR().python_ocr(img_path)
return result
<|end_body_0|>
<|body_start_1|>
result = {}
if platform == 'baidu':
baidu_api = Images... | 1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)(未使用) https://cloud.tencent.com/developer/news/193546 | ImageRecognition | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageRecognition:
"""1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)(未使用) https://cloud.tencent.com/develop... | stack_v2_sparse_classes_75kplus_train_004634 | 2,836 | no_license | [
{
"docstring": "免费10000次 先调用百度,次数消耗完成后使用python库 :return:",
"name": "imgOCR",
"signature": "def imgOCR(img_path)"
},
{
"docstring": "检索相似每天五百次",
"name": "imgSimilar",
"signature": "def imgSimilar(pre_img, rear_img, platform='baidu')"
}
] | 2 | null | Implement the Python class `ImageRecognition` described below.
Class description:
1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)... | Implement the Python class `ImageRecognition` described below.
Class description:
1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)... | 14665e78c61f0357f1206da913ae74f435ac6655 | <|skeleton|>
class ImageRecognition:
"""1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)(未使用) https://cloud.tencent.com/develop... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageRecognition:
"""1. 返回ocr结果 -- 百度文字识别接口,一天一万次免费(测试已足够) -- python 自带第三方库,需另外做训练 2. 返回图片相似度匹配结果 -- 百度图像相似度检索接口(存图--检索--清理),存取免费一天一万次,识别一天500次上限 -- 图像相似度识别算法 - 1. 直方图 - 2. 图像指纹(平均哈希法(aHash),感知哈希算法(pHash),差异哈希算法(phash)) -- 余弦相似度(cosin)(未使用) -- 图片SSIM(结构相似度量)(未使用) https://cloud.tencent.com/developer/news/19354... | the_stack_v2_python_sparse | app_test_linux/services/ImageRecognition.py | Grand-zio/app-test | train | 0 |
64cabcd57b39ea8d750ea2473398f92a4f10e68b | [
"token = token_generator.make_token(user)\nurl = create_email_confirm_url(user.pk, token)\nsubject = 'Подтвердите регистрацию аккаунта'\nbody = render_to_string('kip_api/email/confirm.html', {'url': url})\nmail.send_mail(subject, body, settings.INFORMER_EMAIL, [user.email], fail_silently=False)",
"if settings.DEB... | <|body_start_0|>
token = token_generator.make_token(user)
url = create_email_confirm_url(user.pk, token)
subject = 'Подтвердите регистрацию аккаунта'
body = render_to_string('kip_api/email/confirm.html', {'url': url})
mail.send_mail(subject, body, settings.INFORMER_EMAIL, [user.e... | Работа с электронной почтой | EmailMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailMixin:
"""Работа с электронной почтой"""
def send_test_email(user):
"""Отправка тестового сообщения в локальный ящик"""
<|body_0|>
def send_email_for_confirm(self, user):
"""Отправка письма с ссылкой для подтверждения почты :param user: Объект пользователя""... | stack_v2_sparse_classes_75kplus_train_004635 | 4,552 | no_license | [
{
"docstring": "Отправка тестового сообщения в локальный ящик",
"name": "send_test_email",
"signature": "def send_test_email(user)"
},
{
"docstring": "Отправка письма с ссылкой для подтверждения почты :param user: Объект пользователя",
"name": "send_email_for_confirm",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_053098 | Implement the Python class `EmailMixin` described below.
Class description:
Работа с электронной почтой
Method signatures and docstrings:
- def send_test_email(user): Отправка тестового сообщения в локальный ящик
- def send_email_for_confirm(self, user): Отправка письма с ссылкой для подтверждения почты :param user: ... | Implement the Python class `EmailMixin` described below.
Class description:
Работа с электронной почтой
Method signatures and docstrings:
- def send_test_email(user): Отправка тестового сообщения в локальный ящик
- def send_email_for_confirm(self, user): Отправка письма с ссылкой для подтверждения почты :param user: ... | 8c0e8fa16588fc384979b9514d3d716713c6ea83 | <|skeleton|>
class EmailMixin:
"""Работа с электронной почтой"""
def send_test_email(user):
"""Отправка тестового сообщения в локальный ящик"""
<|body_0|>
def send_email_for_confirm(self, user):
"""Отправка письма с ссылкой для подтверждения почты :param user: Объект пользователя""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailMixin:
"""Работа с электронной почтой"""
def send_test_email(user):
"""Отправка тестового сообщения в локальный ящик"""
token = token_generator.make_token(user)
url = create_email_confirm_url(user.pk, token)
subject = 'Подтвердите регистрацию аккаунта'
body = ... | the_stack_v2_python_sparse | kip_api/mixins.py | skushnerchuk/kip | train | 0 |
dc82ddf62b30c74dd03f2fccb985af9bae859d9c | [
"local_part, domain = email_utils.split_mailbox(value)\ndomain = admin_models.Domain.objects.filter(name=domain).first()\nuser = self.context['request'].user\nif domain and (not user.can_access(domain)):\n raise serializers.ValidationError(_(\"You don't have access to this domain.\"))\nreturn value",
"user = s... | <|body_start_0|>
local_part, domain = email_utils.split_mailbox(value)
domain = admin_models.Domain.objects.filter(name=domain).first()
user = self.context['request'].user
if domain and (not user.can_access(domain)):
raise serializers.ValidationError(_("You don't have access ... | Base Alias serializer. | SenderAddressSerializer | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenderAddressSerializer:
"""Base Alias serializer."""
def validate_address(self, value):
"""Check domain."""
<|body_0|>
def validate_mailbox(self, value):
"""Check permission."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
local_part, domain = ... | stack_v2_sparse_classes_75kplus_train_004636 | 18,871 | permissive | [
{
"docstring": "Check domain.",
"name": "validate_address",
"signature": "def validate_address(self, value)"
},
{
"docstring": "Check permission.",
"name": "validate_mailbox",
"signature": "def validate_mailbox(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001421 | Implement the Python class `SenderAddressSerializer` described below.
Class description:
Base Alias serializer.
Method signatures and docstrings:
- def validate_address(self, value): Check domain.
- def validate_mailbox(self, value): Check permission. | Implement the Python class `SenderAddressSerializer` described below.
Class description:
Base Alias serializer.
Method signatures and docstrings:
- def validate_address(self, value): Check domain.
- def validate_mailbox(self, value): Check permission.
<|skeleton|>
class SenderAddressSerializer:
"""Base Alias ser... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class SenderAddressSerializer:
"""Base Alias serializer."""
def validate_address(self, value):
"""Check domain."""
<|body_0|>
def validate_mailbox(self, value):
"""Check permission."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SenderAddressSerializer:
"""Base Alias serializer."""
def validate_address(self, value):
"""Check domain."""
local_part, domain = email_utils.split_mailbox(value)
domain = admin_models.Domain.objects.filter(name=domain).first()
user = self.context['request'].user
i... | the_stack_v2_python_sparse | modoboa/admin/api/v1/serializers.py | modoboa/modoboa | train | 2,201 |
0e138686262634c5d7bda6cb913d346c9e8de2a6 | [
"try:\n self.threadOn = True\n self.costumer_key = access_credentials['costumer_key']\n self.customer_secret = access_credentials['customer_secret']\n self.oauth_token = access_credentials['oauth_token']\n self.oauth_token_secret = access_credentials['oauth_token_secret']\n auth = twitter.oauth.OA... | <|body_start_0|>
try:
self.threadOn = True
self.costumer_key = access_credentials['costumer_key']
self.customer_secret = access_credentials['customer_secret']
self.oauth_token = access_credentials['oauth_token']
self.oauth_token_secret = access_credent... | :Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twitter and extract information from there. Besides the connection and streaming process, th... | NetworkAnalysisTwitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkAnalysisTwitter:
""":Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twitter and extract information from there... | stack_v2_sparse_classes_75kplus_train_004637 | 5,142 | no_license | [
{
"docstring": ":Date: 2017-05-10 :Version: 0.2 :Author: CAOBA - Pontificia Universidad Javeriana This is the constructor method for the class in which the database and queue connection is made. It also the authorization object for Twitter authentication purposes. :param access_credentials: needed credentials f... | 3 | stack_v2_sparse_classes_30k_train_035776 | Implement the Python class `NetworkAnalysisTwitter` described below.
Class description:
:Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twi... | Implement the Python class `NetworkAnalysisTwitter` described below.
Class description:
:Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twi... | da82127fcc5681cee67e53123cfe4754c8efc831 | <|skeleton|>
class NetworkAnalysisTwitter:
""":Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twitter and extract information from there... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkAnalysisTwitter:
""":Date: 2017-06-18 :Version: 0.3 :Author: CAOBA -Pontificia Universidad Javeriana :Copyright: To define :Organization: Centro de Excelencia y Apropiación de Big Data y Data Analytics - CAOBA This class generates a connection to Twitter and extract information from there. Besides the... | the_stack_v2_python_sparse | extraction/twitter_extraction.py | katherine110992/FoodDetection | train | 0 |
e883bfdb1f4a15131c819b93e74b2c85909a434f | [
"if not matrix:\n return 0\nn = len(matrix)\nm = len(matrix[0])\ndp = [[0 for _ in xrange(m)] for _ in xrange(n)]\nmax_length = 0\nfor i in xrange(n):\n for j in xrange(m):\n if i == 0 or j == 0:\n dp[i][j] = int(matrix[i][j])\n elif matrix[i][j] == '1':\n dp[i][j] = min(dp... | <|body_start_0|>
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
max_length = 0
for i in xrange(n):
for j in xrange(m):
if i == 0 or j == 0:
dp[i][j] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
<|body_0|>
def maximalSquareNCubic(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
return 0
... | stack_v2_sparse_classes_75kplus_train_004638 | 2,983 | no_license | [
{
"docstring": "DP solution.",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquareNCubic",
"signature": "def maximalSquareNCubic(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017820 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): DP solution.
- def maximalSquareNCubic(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): DP solution.
- def maximalSquareNCubic(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
def maximalSqu... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
<|body_0|>
def maximalSquareNCubic(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalSquare(self, matrix):
"""DP solution."""
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
max_length = 0
for i in xrange(n):
for j in xrange(m):
... | the_stack_v2_python_sparse | dynamic_programming/leetcode_Maximum_Square.py | monkeylyf/interviewjam | train | 59 | |
fa6deecde967815892cac53b61d6d4438ea78f10 | [
"def helper(node):\n if node == None:\n return '#'\n return str(node.val) + '*' + helper(node.left) + helper(node.right)\nreturn helper(root)",
"def helper(index):\n if data[index] == '#':\n return (None, index)\n word = ''\n while data[index] != '*':\n word += data[index]\n ... | <|body_start_0|>
def helper(node):
if node == None:
return '#'
return str(node.val) + '*' + helper(node.left) + helper(node.right)
return helper(root)
<|end_body_0|>
<|body_start_1|>
def helper(index):
if data[index] == '#':
re... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004639 | 4,399 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_046629 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 00fd1397b65c68a303fcf963db3e28cd35c1c003 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def helper(node):
if node == None:
return '#'
return str(node.val) + '*' + helper(node.left) + helper(node.right)
return helper(root)
... | the_stack_v2_python_sparse | leetcode/449. Serialize and Deserialize BST.py | cuiy0006/Algorithms | train | 0 | |
922fe60f64bd19a6d717e4175ba7463bb7d7f526 | [
"super().__init__(drug_sensitivity_filepath=drug_sensitivity_filepath, smi_filepath=smi_filepath, gene_expression_filepath=gene_expression_filepath, column_names=column_names[:2] + [column_names[-1]], drug_sensitivity_min_max=False, drug_sensitivity_processing_parameters={}, smiles_language=smiles_language, iterate... | <|body_start_0|>
super().__init__(drug_sensitivity_filepath=drug_sensitivity_filepath, smi_filepath=smi_filepath, gene_expression_filepath=gene_expression_filepath, column_names=column_names[:2] + [column_names[-1]], drug_sensitivity_min_max=False, drug_sensitivity_processing_parameters={}, smiles_language=smil... | Drug sensitivity dose dataset implementation. | DrugSensitivityDoseDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrugSensitivityDoseDataset:
"""Drug sensitivity dose dataset implementation."""
def __init__(self, drug_sensitivity_filepath: str, smi_filepath: str, gene_expression_filepath: str, smiles_language: SMILESTokenizer, column_names: Tuple[str]=['drug', 'cell_line', 'dose', 'viability'], dose_tra... | stack_v2_sparse_classes_75kplus_train_004640 | 5,544 | permissive | [
{
"docstring": "Initialize a drug sensitivity dose dataset. Args: drug_sensitivity_filepath (str): path to drug sensitivity .csv file. Currently, the only supported format is .csv, with an index and three header columns named as specified in the column_names argument. smi_filepath (str): path to .smi file. gene... | 2 | stack_v2_sparse_classes_30k_val_002214 | Implement the Python class `DrugSensitivityDoseDataset` described below.
Class description:
Drug sensitivity dose dataset implementation.
Method signatures and docstrings:
- def __init__(self, drug_sensitivity_filepath: str, smi_filepath: str, gene_expression_filepath: str, smiles_language: SMILESTokenizer, column_na... | Implement the Python class `DrugSensitivityDoseDataset` described below.
Class description:
Drug sensitivity dose dataset implementation.
Method signatures and docstrings:
- def __init__(self, drug_sensitivity_filepath: str, smi_filepath: str, gene_expression_filepath: str, smiles_language: SMILESTokenizer, column_na... | 27ca3f8c5b5463cd081be5abdea04f5bfa076f39 | <|skeleton|>
class DrugSensitivityDoseDataset:
"""Drug sensitivity dose dataset implementation."""
def __init__(self, drug_sensitivity_filepath: str, smi_filepath: str, gene_expression_filepath: str, smiles_language: SMILESTokenizer, column_names: Tuple[str]=['drug', 'cell_line', 'dose', 'viability'], dose_tra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DrugSensitivityDoseDataset:
"""Drug sensitivity dose dataset implementation."""
def __init__(self, drug_sensitivity_filepath: str, smi_filepath: str, gene_expression_filepath: str, smiles_language: SMILESTokenizer, column_names: Tuple[str]=['drug', 'cell_line', 'dose', 'viability'], dose_transform: Calla... | the_stack_v2_python_sparse | pytoda/datasets/drug_sensitivity_dose_dataset.py | PaccMann/paccmann_datasets | train | 22 |
938ce690330520ec7c5069c205f9e6ed3a2f9aac | [
"super(SparqlBasedDeductionEngineExtended, self).__init__()\nself.relation = relation\nself.query_executer = kg_query_interface\nself.quality = quality\nself.quality_aggregation = quality_aggregation\nself.labels_indexer = Indexer(store=kg_query_interface.type, endpoint=kg_query_interface.endpoint, graph=kg_query_i... | <|body_start_0|>
super(SparqlBasedDeductionEngineExtended, self).__init__()
self.relation = relation
self.query_executer = kg_query_interface
self.quality = quality
self.quality_aggregation = quality_aggregation
self.labels_indexer = Indexer(store=kg_query_interface.type,... | Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions | SparqlBasedDeductionEngineExtended | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, qua... | stack_v2_sparse_classes_75kplus_train_004641 | 10,782 | permissive | [
{
"docstring": ":param kg_query_interface: interface for the KG. :param relation: the relation used in the predicted triple (optional) :param quality: objective quality measure for ranking the predictions (optional) by default the exclusive coverage of the rules is used :param quality_aggregation: the methd use... | 5 | stack_v2_sparse_classes_30k_train_037292 | Implement the Python class `SparqlBasedDeductionEngineExtended` described below.
Class description:
Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions
Method signatures and docstrings:
- def __init__(self, kg_query_int... | Implement the Python class `SparqlBasedDeductionEngineExtended` described below.
Class description:
Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions
Method signatures and docstrings:
- def __init__(self, kg_query_int... | 09e943a23207381de3c3a9e6f70015882b8ec4af | <|skeleton|>
class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, qua... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparqlBasedDeductionEngineExtended:
"""Deduction engine that converts the rules to sparql and fire them over the KG. The rule-based_deduction takes care of consolidating similar predictions"""
def __init__(self, kg_query_interface: KGQueryInterfaceExtended, relation=DEFUALT_AUX_RELATION, quality='x_cover... | the_stack_v2_python_sparse | excut/feedback/rulebased_deduction/deduction_engine_extended.py | mhmgad/ExCut | train | 9 |
9dc70d2f0804af2bafa3c0e5873b1f2714d54b22 | [
"self.driver.get(home_url)\nhome_page_title_actual = self.driver.get_title()\nhome_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网'\ntt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % (home_page_title_expected, home_page_title_actual))",
"self.driver.get(home_url)\nads = ... | <|body_start_0|>
self.driver.get(home_url)
home_page_title_actual = self.driver.get_title()
home_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网'
tt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % (home_page_title_expected, home_page_title_actual... | AD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AD:
def test_title(self):
"""测试首页Title显示是否正确"""
<|body_0|>
def test_ad_displayed(self):
"""测试广告位图片请求是否正常"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.driver.get(home_url)
home_page_title_actual = self.driver.get_title()
home_... | stack_v2_sparse_classes_75kplus_train_004642 | 2,686 | no_license | [
{
"docstring": "测试首页Title显示是否正确",
"name": "test_title",
"signature": "def test_title(self)"
},
{
"docstring": "测试广告位图片请求是否正常",
"name": "test_ad_displayed",
"signature": "def test_ad_displayed(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041440 | Implement the Python class `AD` described below.
Class description:
Implement the AD class.
Method signatures and docstrings:
- def test_title(self): 测试首页Title显示是否正确
- def test_ad_displayed(self): 测试广告位图片请求是否正常 | Implement the Python class `AD` described below.
Class description:
Implement the AD class.
Method signatures and docstrings:
- def test_title(self): 测试首页Title显示是否正确
- def test_ad_displayed(self): 测试广告位图片请求是否正常
<|skeleton|>
class AD:
def test_title(self):
"""测试首页Title显示是否正确"""
<|body_0|>
de... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class AD:
def test_title(self):
"""测试首页Title显示是否正确"""
<|body_0|>
def test_ad_displayed(self):
"""测试广告位图片请求是否正常"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AD:
def test_title(self):
"""测试首页Title显示是否正确"""
self.driver.get(home_url)
home_page_title_actual = self.driver.get_title()
home_page_title_expected = '二手车市场_二手车交易市场_二手车平台-淘车网'
tt_check.assertEqual(home_page_title_actual, home_page_title_expected, '页面title期望是%s,实际是%s' % ... | the_stack_v2_python_sparse | mc/taochePC/test_homepage/test_ad.py | boeai/mc | train | 0 | |
46692a96e0f31433821ea622d366179306bb7cbc | [
"torch.nn.Module.__init__(self)\nif hidden_size % num_heads:\n raise ValueError('hidden size must be a multiple of the number of attention heads')\nself.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range=initializer_range)\nself.dense = torch.n... | <|body_start_0|>
torch.nn.Module.__init__(self)
if hidden_size % num_heads:
raise ValueError('hidden size must be a multiple of the number of attention heads')
self.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range... | TransformerEncoder | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ... | stack_v2_sparse_classes_75kplus_train_004643 | 6,126 | permissive | [
{
"docstring": "hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - dropout probability (0. means \"no dropout\") initializer_range - stddev for random weight matrix initialization",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_006320 | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of... | 84c1c9507b3b1bffd2a08a86efaf9bc9955271e0 | <|skeleton|>
class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - drop... | the_stack_v2_python_sparse | tbert/transformer.py | qianrenjian/tbert | train | 0 | |
2b9bbc633f8fbd3416c15bb34b906592ca9e7f5a | [
"self._ccb = ccb\nself.entity_description = description\nself._attr_name = f'{ccb.name} {description.name}'\nself._attr_unique_id = f'{ccb.unique_id}-{description.key}'",
"_LOGGER.debug('Registering for sensor %s (%d)', self.entity_description.key, self.entity_description.sensor_id)\nself.async_on_remove(async_di... | <|body_start_0|>
self._ccb = ccb
self.entity_description = description
self._attr_name = f'{ccb.name} {description.name}'
self._attr_unique_id = f'{ccb.unique_id}-{description.key}'
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug('Registering for sensor %s (%d)', self.entity_descr... | Representation of a ComfoConnect sensor. | ComfoConnectSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComfoConnectSensor:
"""Representation of a ComfoConnect sensor."""
def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None:
"""Initialize the ComfoConnect sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_75kplus_train_004644 | 11,767 | permissive | [
{
"docstring": "Initialize the ComfoConnect sensor.",
"name": "__init__",
"signature": "def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None"
},
{
"docstring": "Register for sensor updates.",
"name": "async_added_to_hass",
"signature": "as... | 3 | null | Implement the Python class `ComfoConnectSensor` described below.
Class description:
Representation of a ComfoConnect sensor.
Method signatures and docstrings:
- def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None: Initialize the ComfoConnect sensor.
- async def async_... | Implement the Python class `ComfoConnectSensor` described below.
Class description:
Representation of a ComfoConnect sensor.
Method signatures and docstrings:
- def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None: Initialize the ComfoConnect sensor.
- async def async_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ComfoConnectSensor:
"""Representation of a ComfoConnect sensor."""
def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None:
"""Initialize the ComfoConnect sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComfoConnectSensor:
"""Representation of a ComfoConnect sensor."""
def __init__(self, ccb: ComfoConnectBridge, description: ComfoconnectSensorEntityDescription) -> None:
"""Initialize the ComfoConnect sensor."""
self._ccb = ccb
self.entity_description = description
self._a... | the_stack_v2_python_sparse | homeassistant/components/comfoconnect/sensor.py | home-assistant/core | train | 35,501 |
141b0f482d83f59d0ce0cd3876554b1174f53c6c | [
"self.reactions = tuple()\nfor app_name in app_names:\n a = __import__('apps.%s' % app_name, globals(), locals(), ['controller'], -1)\n self.reactions += a.controller.reactions\nself.app_names = app_names",
"for msg in msg_set:\n for test, response in self.reactions:\n if test(msg):\n r... | <|body_start_0|>
self.reactions = tuple()
for app_name in app_names:
a = __import__('apps.%s' % app_name, globals(), locals(), ['controller'], -1)
self.reactions += a.controller.reactions
self.app_names = app_names
<|end_body_0|>
<|body_start_1|>
for msg in msg_s... | a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true. | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
"""a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true."""
def __init__(self, app_names):... | stack_v2_sparse_classes_75kplus_train_004645 | 1,097 | no_license | [
{
"docstring": "Instantiate a controller. Argument: app_names -- the names of apps to manage (corresponding to dirs in the apps subdir)",
"name": "__init__",
"signature": "def __init__(self, app_names)"
},
{
"docstring": "Run all apps' tests on each message, call associated response if test pass... | 2 | stack_v2_sparse_classes_30k_val_002045 | Implement the Python class `Controller` described below.
Class description:
a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true.... | Implement the Python class `Controller` described below.
Class description:
a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true.... | 67a08382182804413e31992d38e2303038359ad7 | <|skeleton|>
class Controller:
"""a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true."""
def __init__(self, app_names):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
"""a Controller instance is initialized with the names of the apps which it manages using its control() method, which takes a message set and runs each apps tests on each message on the set, performing the app's response if the test returns true."""
def __init__(self, app_names):
"""I... | the_stack_v2_python_sparse | core/controller.py | gabeos/python-samosa | train | 0 |
0c447bd28d463052a928d0a430c14baae4fb1ff0 | [
"index_info = dict()\nfor index, s in enumerate(S):\n index_info[s] = index\nstart, end = (0, 0)\nres = []\nwhile end < len(S) - 1:\n i = start\n end = index_info[S[i]]\n while i < end:\n i += 1\n end = max(index_info[S[i], end])\n res.append(end - start + 1)\n start = i + 1\nreturn ... | <|body_start_0|>
index_info = dict()
for index, s in enumerate(S):
index_info[s] = index
start, end = (0, 0)
res = []
while end < len(S) - 1:
i = start
end = index_info[S[i]]
while i < end:
i += 1
end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partitionLabels(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def partitionLabels2(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
index_info = dict()
for index, s in enum... | stack_v2_sparse_classes_75kplus_train_004646 | 2,171 | no_license | [
{
"docstring": ":type S: str :rtype: List[int]",
"name": "partitionLabels",
"signature": "def partitionLabels(self, S)"
},
{
"docstring": ":type S: str :rtype: List[int]",
"name": "partitionLabels2",
"signature": "def partitionLabels2(self, S)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionLabels(self, S): :type S: str :rtype: List[int]
- def partitionLabels2(self, S): :type S: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionLabels(self, S): :type S: str :rtype: List[int]
- def partitionLabels2(self, S): :type S: str :rtype: List[int]
<|skeleton|>
class Solution:
def partitionLabel... | 416fed6e441612e1ad82467d07ee1b5570386a94 | <|skeleton|>
class Solution:
def partitionLabels(self, S):
""":type S: str :rtype: List[int]"""
<|body_0|>
def partitionLabels2(self, S):
""":type S: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def partitionLabels(self, S):
""":type S: str :rtype: List[int]"""
index_info = dict()
for index, s in enumerate(S):
index_info[s] = index
start, end = (0, 0)
res = []
while end < len(S) - 1:
i = start
end = index_in... | the_stack_v2_python_sparse | src/python/greedy_algorithm/partition_labels.py | liadbiz/Leetcode-Solutions | train | 1 | |
46e9bccabda90b55a81ca1b8dae84645425c2c53 | [
"self.entry = entry\nself.id = entry.id\nself.title = entry.title\nself.date = entry.date\nself.time_spent = entry.time_spent\nself.learned = entry.learned\n_resources = self.entry.get_resources()\n_tags = self.entry.get_tags()\nself.resources = [(resource.id, resource.title) for resource in list(_resources)]\nself... | <|body_start_0|>
self.entry = entry
self.id = entry.id
self.title = entry.title
self.date = entry.date
self.time_spent = entry.time_spent
self.learned = entry.learned
_resources = self.entry.get_resources()
_tags = self.entry.get_tags()
self.resour... | helper class that is not stored in the database it is used to update an entry along with its tags and resources | EntryWithResourcesandTags | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
<|body_0|>
def updat... | stack_v2_sparse_classes_75kplus_train_004647 | 10,083 | no_license | [
{
"docstring": "the combined record is initilized in the way it exists before the update",
"name": "__init__",
"signature": "def __init__(self, entry)"
},
{
"docstring": "the update is performed",
"name": "update",
"signature": "def update(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022925 | Implement the Python class `EntryWithResourcesandTags` described below.
Class description:
helper class that is not stored in the database it is used to update an entry along with its tags and resources
Method signatures and docstrings:
- def __init__(self, entry): the combined record is initilized in the way it exis... | Implement the Python class `EntryWithResourcesandTags` described below.
Class description:
helper class that is not stored in the database it is used to update an entry along with its tags and resources
Method signatures and docstrings:
- def __init__(self, entry): the combined record is initilized in the way it exis... | 8bfbba09132b405f7c68cbfd9a0e7596223c3a53 | <|skeleton|>
class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
<|body_0|>
def updat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
self.entry = entry
self.id = e... | the_stack_v2_python_sparse | project05_flask_learningjournal/learning_journal/models.py | sabinem/treehouse-python-techdegree | train | 3 |
6d558800961fe228ed3b6499296d30c9516d12ad | [
"desired_operator: Union[MathematicalOperator, None] = None\nfor operation in MathematicalOperator.__members__.values():\n if operation.symbol == given_symbol:\n desired_operator = operation\n break\nreturn desired_operator",
"first_operator = await MathematicalOperator.get_by_symbol(symbol_one)\... | <|body_start_0|>
desired_operator: Union[MathematicalOperator, None] = None
for operation in MathematicalOperator.__members__.values():
if operation.symbol == given_symbol:
desired_operator = operation
break
return desired_operator
<|end_body_0|>
<|bo... | This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and the type of associativity it bears. | MathematicalOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MathematicalOperator:
"""This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and the type of associativity it bears."""
... | stack_v2_sparse_classes_75kplus_train_004648 | 9,452 | no_license | [
{
"docstring": "This method retrieves an operator from MathematicalOperator based on its symbol. :param str given_symbol: the symbol which the desired MathematicalOperator should have. :return MathematicalOperator: the operator corresponding to the given symbol.",
"name": "get_by_symbol",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_010785 | Implement the Python class `MathematicalOperator` described below.
Class description:
This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and t... | Implement the Python class `MathematicalOperator` described below.
Class description:
This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and t... | d8c2dc4a9aa21d5861f465b5cc4b02df44df0360 | <|skeleton|>
class MathematicalOperator:
"""This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and the type of associativity it bears."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MathematicalOperator:
"""This enumeration concerns mathematical operators for essential symbolic mathematical calculations. It has four components: the value of the Enum, the symbol it represents, the precedence it has when compared to other operators, and the type of associativity it bears."""
async def... | the_stack_v2_python_sparse | Bot/Cogs/Helpers/Enumerators/tabulator.py | Mythologos/Smorg | train | 0 |
77948fd0f40b7bc2cdc08edd44e66349428f8467 | [
"study_id = filter_params.pop('study_id', None)\nq = Phenotype.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nif study_id:\n q = q.join(Participant.phenotypes).filter(Participant.study_id == study_id)\nreturn PhenotypeSchema(many=True).jsonify(Pagination(q, after, l... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
q = Phenotype.query.filter_by(**filter_params)
from dataservice.api.participant.models import Participant
if study_id:
q = q.join(Participant.phenotypes).filter(Participant.study_id == study_id)
return Ph... | Phenotype REST API | PhenotypeListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhenotypeListAPI:
"""Phenotype REST API"""
def get(self, filter_params, after, limit):
"""Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype"""
<|body_0|>
def post(self):
"""Create a new phenotype -... | stack_v2_sparse_classes_75kplus_train_004649 | 4,652 | permissive | [
{
"docstring": "Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new phenotype --- template: path: new_resource.yml properties... | 2 | stack_v2_sparse_classes_30k_train_017063 | Implement the Python class `PhenotypeListAPI` described below.
Class description:
Phenotype REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype
- def post(self): Cre... | Implement the Python class `PhenotypeListAPI` described below.
Class description:
Phenotype REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype
- def post(self): Cre... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class PhenotypeListAPI:
"""Phenotype REST API"""
def get(self, filter_params, after, limit):
"""Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype"""
<|body_0|>
def post(self):
"""Create a new phenotype -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhenotypeListAPI:
"""Phenotype REST API"""
def get(self, filter_params, after, limit):
"""Get all phenotypes --- description: Get all phenotypes template: path: get_list.yml properties: resource: Phenotype"""
study_id = filter_params.pop('study_id', None)
q = Phenotype.query.filte... | the_stack_v2_python_sparse | dataservice/api/phenotype/resources.py | kids-first/kf-api-dataservice | train | 9 |
a2d85349d9da835a7c5e9188fc5f9ed53174f2b1 | [
"if type(y_train) == list:\n y_train = np.array(y_train).astype(float)\nX_train = X_train.astype(float)\ndtrain = xgb.DMatrix(X_train, y_train)\nif params is None:\n params = {'objective': 'binary:logistic', 'eval_metric': 'logloss', 'max_depth': 5, 'min_child_weight': 1, 'gamma': 0, 'subsample': 0.8, 'colsam... | <|body_start_0|>
if type(y_train) == list:
y_train = np.array(y_train).astype(float)
X_train = X_train.astype(float)
dtrain = xgb.DMatrix(X_train, y_train)
if params is None:
params = {'objective': 'binary:logistic', 'eval_metric': 'logloss', 'max_depth': 5, 'min_... | XGBoost | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoost:
def train(self, X_train, y_train, output_path='', params=None, num_rounds=100, feature_names=[]):
"""Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features], float y_train: numpy array or python list of shape [n_samples], int/float output_path: string, ... | stack_v2_sparse_classes_75kplus_train_004650 | 4,921 | permissive | [
{
"docstring": "Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features], float y_train: numpy array or python list of shape [n_samples], int/float output_path: string, path to save the XGBoost model params: dict, parameters of XGBoost num_rounds: int, number of epochs num_class: int, n... | 4 | null | Implement the Python class `XGBoost` described below.
Class description:
Implement the XGBoost class.
Method signatures and docstrings:
- def train(self, X_train, y_train, output_path='', params=None, num_rounds=100, feature_names=[]): Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features],... | Implement the Python class `XGBoost` described below.
Class description:
Implement the XGBoost class.
Method signatures and docstrings:
- def train(self, X_train, y_train, output_path='', params=None, num_rounds=100, feature_names=[]): Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features],... | e6156663e7e8040c40f6a2bfac393bdfa0bfdaba | <|skeleton|>
class XGBoost:
def train(self, X_train, y_train, output_path='', params=None, num_rounds=100, feature_names=[]):
"""Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features], float y_train: numpy array or python list of shape [n_samples], int/float output_path: string, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XGBoost:
def train(self, X_train, y_train, output_path='', params=None, num_rounds=100, feature_names=[]):
"""Train xgboost model. Input: X_train: numpy array of shape [n_samples, n_features], float y_train: numpy array or python list of shape [n_samples], int/float output_path: string, path to save t... | the_stack_v2_python_sparse | textgo/classifier/xgboost.py | Brelliothe/textgo | train | 0 | |
5b0466dd96eec35ecbcc0ba34c03a8f2a01188a3 | [
"self.generator = random_number_generator\nself.length = length\nself.num_generated_numbers = None",
"if self.num_generated_numbers is not None:\n raise RuntimeError\nself.num_generated_numbers = 0\nreturn self",
"if self.num_generated_numbers is None:\n raise RuntimeError\nif self.length is not None:\n ... | <|body_start_0|>
self.generator = random_number_generator
self.length = length
self.num_generated_numbers = None
<|end_body_0|>
<|body_start_1|>
if self.num_generated_numbers is not None:
raise RuntimeError
self.num_generated_numbers = 0
return self
<|end_bod... | RandIter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandIter:
def __init__(self, random_number_generator, length=None):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate Defaults to Non... | stack_v2_sparse_classes_75kplus_train_004651 | 3,292 | no_license | [
{
"docstring": "Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate Defaults to None and gives an infinite sequence",
"name": "__init__",
"signature": "de... | 3 | null | Implement the Python class `RandIter` described below.
Class description:
Implement the RandIter class.
Method signatures and docstrings:
- def __init__(self, random_number_generator, length=None): Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments a... | Implement the Python class `RandIter` described below.
Class description:
Implement the RandIter class.
Method signatures and docstrings:
- def __init__(self, random_number_generator, length=None): Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments a... | 8d0c3288235254ca4fd0f5558ee84adc1824f28c | <|skeleton|>
class RandIter:
def __init__(self, random_number_generator, length=None):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate Defaults to Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandIter:
def __init__(self, random_number_generator, length=None):
"""Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate Defaults to None and gives an... | the_stack_v2_python_sparse | src/petter_bøe_hørtvedt_ex/ex05/myrand.py | petterho/INF200-2019-Exersices | train | 0 | |
f49b411c48ddbcec6da43817fa4dbe8626b1d754 | [
"if not b:\n return None\ni = 0\nj = 0\nwhile m > 0 and n > 0:\n if a[i] > b[j]:\n self.insert_shift_arr(i, j, a, b)\n j += 1\n n -= 1\n else:\n m -= 1\n i += 1\nwhile n > 0:\n a[i] = b[j]\n n -= 1\n i += 1\n j += 1\nreturn None",
"p = b[j]\nfor x in range(i, le... | <|body_start_0|>
if not b:
return None
i = 0
j = 0
while m > 0 and n > 0:
if a[i] > b[j]:
self.insert_shift_arr(i, j, a, b)
j += 1
n -= 1
else:
m -= 1
i += 1
while n > ... | Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place | Solution1 | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
"""Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place"""
def merge_sort_arr(self, a, m, b, n):
"""Combines and sorts elements from both input arrays in... | stack_v2_sparse_classes_75kplus_train_004652 | 4,235 | permissive | [
{
"docstring": "Combines and sorts elements from both input arrays in-place. :param list[int] a: first array of integer values :param int m: number of elements in first array :param list[int] b: second array of integer values :param int n: number of elements in second array :return: None :rtype: None",
"nam... | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place
Method signatures and docstrings:
- def merge_sort_arr(self, a, m, b, ... | Implement the Python class `Solution1` described below.
Class description:
Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place
Method signatures and docstrings:
- def merge_sort_arr(self, a, m, b, ... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution1:
"""Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place"""
def merge_sort_arr(self, a, m, b, n):
"""Combines and sorts elements from both input arrays in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
"""Iterative traversal of first input array. Time complexity: O(n + m) - Amortized traverse first and second list elements Space complexity: O(1) - Update first array in-place"""
def merge_sort_arr(self, a, m, b, n):
"""Combines and sorts elements from both input arrays in-place. :para... | the_stack_v2_python_sparse | 0088_merge_sorted_array/python_source.py | arthurdysart/LeetCode | train | 0 |
b758e1eff7ad1851631ba4dd6fa7d8cd1742881b | [
"super().__init__(api, coordinator, name, server_unique_id)\nself.entity_description = description\nself._attr_unique_id = f'{self._server_unique_id}/{description.key}'\nself._attr_title = description.title",
"if isinstance(self.api.versions, dict):\n return self.entity_description.installed_version(self.api.v... | <|body_start_0|>
super().__init__(api, coordinator, name, server_unique_id)
self.entity_description = description
self._attr_unique_id = f'{self._server_unique_id}/{description.key}'
self._attr_title = description.title
<|end_body_0|>
<|body_start_1|>
if isinstance(self.api.vers... | Representation of a Pi-hole update entity. | PiHoleUpdateEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiHoleUpdateEntity:
"""Representation of a Pi-hole update entity."""
def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None:
"""Initialize a Pi-hole update entity."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004653 | 4,341 | permissive | [
{
"docstring": "Initialize a Pi-hole update entity.",
"name": "__init__",
"signature": "def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None"
},
{
"docstring": "Version installed and in use.",
... | 4 | stack_v2_sparse_classes_30k_train_030921 | Implement the Python class `PiHoleUpdateEntity` described below.
Class description:
Representation of a Pi-hole update entity.
Method signatures and docstrings:
- def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None: In... | Implement the Python class `PiHoleUpdateEntity` described below.
Class description:
Representation of a Pi-hole update entity.
Method signatures and docstrings:
- def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None: In... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PiHoleUpdateEntity:
"""Representation of a Pi-hole update entity."""
def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None:
"""Initialize a Pi-hole update entity."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PiHoleUpdateEntity:
"""Representation of a Pi-hole update entity."""
def __init__(self, api: Hole, coordinator: DataUpdateCoordinator, name: str, server_unique_id: str, description: PiHoleUpdateEntityDescription) -> None:
"""Initialize a Pi-hole update entity."""
super().__init__(api, coo... | the_stack_v2_python_sparse | homeassistant/components/pi_hole/update.py | home-assistant/core | train | 35,501 |
6ebd1dc15c59fb4f5ed681520de79e52cef60200 | [
"super(BasePage, self).__init__(driver)\nself.driver = driver\nself.util = Util()",
"try:\n actual_title = self.get_title()\n return self.util.verify_text_contains(actual_title, title_of_page)\nexcept Exception as err:\n self.automation_logger.error('Failed to get page title: ' + str(err))"
] | <|body_start_0|>
super(BasePage, self).__init__(driver)
self.driver = driver
self.util = Util()
<|end_body_0|>
<|body_start_1|>
try:
actual_title = self.get_title()
return self.util.verify_text_contains(actual_title, title_of_page)
except Exception as err... | BasePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
<|body_0|>
def verify_page_title(self, title_of_page):
"""Verify the title of current page. :param title_of_page: Title of current page that needs to be... | stack_v2_sparse_classes_75kplus_train_004654 | 856 | no_license | [
{
"docstring": "Initializes the BasePage class. :param driver: Instance of the driver.",
"name": "__init__",
"signature": "def __init__(self, driver)"
},
{
"docstring": "Verify the title of current page. :param title_of_page: Title of current page that needs to be verified. :return: True / False... | 2 | stack_v2_sparse_classes_30k_train_021937 | Implement the Python class `BasePage` described below.
Class description:
Implement the BasePage class.
Method signatures and docstrings:
- def __init__(self, driver): Initializes the BasePage class. :param driver: Instance of the driver.
- def verify_page_title(self, title_of_page): Verify the title of current page.... | Implement the Python class `BasePage` described below.
Class description:
Implement the BasePage class.
Method signatures and docstrings:
- def __init__(self, driver): Initializes the BasePage class. :param driver: Instance of the driver.
- def verify_page_title(self, title_of_page): Verify the title of current page.... | 0eb90797548d405c619017d65f8b8fbd06113f09 | <|skeleton|>
class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
<|body_0|>
def verify_page_title(self, title_of_page):
"""Verify the title of current page. :param title_of_page: Title of current page that needs to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasePage:
def __init__(self, driver):
"""Initializes the BasePage class. :param driver: Instance of the driver."""
super(BasePage, self).__init__(driver)
self.driver = driver
self.util = Util()
def verify_page_title(self, title_of_page):
"""Verify the title of curr... | the_stack_v2_python_sparse | Base/base_page.py | LiuKang1080/Selenium-Frameworks | train | 1 | |
e0c9f7d012343611c3c322118427951536e8a57a | [
"super().__init__(model=pref_model)\nself.add_module('outcome_model', outcome_model)\nself.num_samples = num_samples\nself.std_noise = std_noise\nself.std_normal = Normal(0, 1)",
"Y = X if self.outcome_model is None else self.outcome_model(X)\npref_posterior = self.model.posterior(Y)\npref_mean = pref_posterior.m... | <|body_start_0|>
super().__init__(model=pref_model)
self.add_module('outcome_model', outcome_model)
self.num_samples = num_samples
self.std_noise = std_noise
self.std_normal = Normal(0, 1)
<|end_body_0|>
<|body_start_1|>
Y = X if self.outcome_model is None else self.outc... | MC Bayesian Active Learning by Disagreement | PairwiseBayesianActiveLearningByDisagreement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairwiseBayesianActiveLearningByDisagreement:
"""MC Bayesian Active Learning by Disagreement"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, num_samples: Optional[int]=1024, std_noise: Optional[float]=0.0, **kwargs: Any) -> None:
"""Monte Ca... | stack_v2_sparse_classes_75kplus_train_004655 | 7,676 | permissive | [
{
"docstring": "Monte Carlo implementation of Bayesian Active Learning by Disagreement (BALD) proposed in [Houlsby2011bald]_. Args: pref_model: The preference model that maps the outcomes (i.e., Y) to scalar-valued utility. outcome_model: A deterministic model that maps parameters (i.e., X) to outcomes (i.e., Y... | 2 | stack_v2_sparse_classes_30k_train_042681 | Implement the Python class `PairwiseBayesianActiveLearningByDisagreement` described below.
Class description:
MC Bayesian Active Learning by Disagreement
Method signatures and docstrings:
- def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, num_samples: Optional[int]=1024, std_noi... | Implement the Python class `PairwiseBayesianActiveLearningByDisagreement` described below.
Class description:
MC Bayesian Active Learning by Disagreement
Method signatures and docstrings:
- def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, num_samples: Optional[int]=1024, std_noi... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class PairwiseBayesianActiveLearningByDisagreement:
"""MC Bayesian Active Learning by Disagreement"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, num_samples: Optional[int]=1024, std_noise: Optional[float]=0.0, **kwargs: Any) -> None:
"""Monte Ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PairwiseBayesianActiveLearningByDisagreement:
"""MC Bayesian Active Learning by Disagreement"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, num_samples: Optional[int]=1024, std_noise: Optional[float]=0.0, **kwargs: Any) -> None:
"""Monte Carlo implement... | the_stack_v2_python_sparse | botorch/acquisition/preference.py | pytorch/botorch | train | 2,891 |
57580475ce1d52dc771dc3c9a1dfbf5e8ce72100 | [
"self.max_h = list()\nself.min_h = list()\nheapify(self.max_h)\nheapify(self.min_h)",
"heappush(self.min_h, num)\nheappush(self.max_h, -heappop(self.min_h))\nif len(self.max_h) > len(self.min_h):\n heappush(self.min_h, -heappop(self.max_h))",
"max_len = len(self.max_h)\nmin_len = len(self.min_h)\nif max_len ... | <|body_start_0|>
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
<|end_body_0|>
<|body_start_1|>
heappush(self.min_h, num)
heappush(self.max_h, -heappop(self.min_h))
if len(self.max_h) > len(self.min_h):
heappush(self.m... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_004656 | 2,010 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_041276 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | ce8b12735aa181a223eb3b8d6c6993cbafc2e467 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
def addNum(self, num):
""":type num: int :rtype: None"""
heappush(self.min_h, num)
h... | the_stack_v2_python_sparse | 295. 数据流的中位数.py | hanzhenlei767/leetcode | train | 3 | |
69d9360b5b699c482cd3425f415b31c746d57d4d | [
"word = Word.get_by_id(value.title())\nif not word:\n return ({'Error': 'Parola non trovata'}, 404)\nword_dict = {'Parola': word.correct, 'Numero occorrenze': word.counter, 'Errori associati': word.errors}\nreturn (word_dict, 200)",
"word = Word.get_by_id(value.title())\nif not word:\n return ({'Error': 'Pa... | <|body_start_0|>
word = Word.get_by_id(value.title())
if not word:
return ({'Error': 'Parola non trovata'}, 404)
word_dict = {'Parola': word.correct, 'Numero occorrenze': word.counter, 'Errori associati': word.errors}
return (word_dict, 200)
<|end_body_0|>
<|body_start_1|>
... | Words | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Words:
def get(self, value):
"""Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:"""
<|body_0|>
def post(self, value):
"""Aggiunge una lista di errori noti per la parola indicata. I... | stack_v2_sparse_classes_75kplus_train_004657 | 3,672 | no_license | [
{
"docstring": "Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:",
"name": "get",
"signature": "def get(self, value)"
},
{
"docstring": "Aggiunge una lista di errori noti per la parola indicata. In particolare... | 2 | stack_v2_sparse_classes_30k_train_005732 | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def get(self, value): Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:
- def post(self, value): A... | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def get(self, value): Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:
- def post(self, value): A... | 63ab4789a80af5927153e110d80af8a8c05449bb | <|skeleton|>
class Words:
def get(self, value):
"""Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:"""
<|body_0|>
def post(self, value):
"""Aggiunge una lista di errori noti per la parola indicata. I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Words:
def get(self, value):
"""Ritorna tutte le correzioni scelte in precedenza dagli utenti tramite l'interfaccia web per la parola selezionata :param word: :return:"""
word = Word.get_by_id(value.title())
if not word:
return ({'Error': 'Parola non trovata'}, 404)
... | the_stack_v2_python_sparse | 08. RESTful API Web/02. Sentence Corrector/app/api/api.py | ZippoCode/SAR | train | 0 | |
23555928dbbda0e70df14c3b82e8466310aa3776 | [
"cls._verify_message(raw_message)\nassert struct.calcsize(cls._data['struct']) == cls.length\nraw_values = struct.unpack(cls._data['struct'], raw_message)\nassert len(cls._raw_keys) == len(raw_values), '%s != %s' % (len(cls._raw_keys), len(raw_values))\nraw = dict(zip(cls._raw_keys, raw_values))\nmessage = cls._raw... | <|body_start_0|>
cls._verify_message(raw_message)
assert struct.calcsize(cls._data['struct']) == cls.length
raw_values = struct.unpack(cls._data['struct'], raw_message)
assert len(cls._raw_keys) == len(raw_values), '%s != %s' % (len(cls._raw_keys), len(raw_values))
raw = dict(zip... | Sungrow inverter status page | StatusPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusPage:
"""Sungrow inverter status page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
<|body_0|>
def to_bytes(self):
"""Produce native-format bytestring from message"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_004658 | 5,926 | permissive | [
{
"docstring": "Create message from native-format bytestring",
"name": "from_bytes",
"signature": "def from_bytes(cls, raw_message)"
},
{
"docstring": "Produce native-format bytestring from message",
"name": "to_bytes",
"signature": "def to_bytes(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010391 | Implement the Python class `StatusPage` described below.
Class description:
Sungrow inverter status page
Method signatures and docstrings:
- def from_bytes(cls, raw_message): Create message from native-format bytestring
- def to_bytes(self): Produce native-format bytestring from message | Implement the Python class `StatusPage` described below.
Class description:
Sungrow inverter status page
Method signatures and docstrings:
- def from_bytes(cls, raw_message): Create message from native-format bytestring
- def to_bytes(self): Produce native-format bytestring from message
<|skeleton|>
class StatusPage... | 482707c82aa813c6e6f951d28e836d70df6cf56c | <|skeleton|>
class StatusPage:
"""Sungrow inverter status page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
<|body_0|>
def to_bytes(self):
"""Produce native-format bytestring from message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatusPage:
"""Sungrow inverter status page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
cls._verify_message(raw_message)
assert struct.calcsize(cls._data['struct']) == cls.length
raw_values = struct.unpack(cls._data['struct'], ra... | the_stack_v2_python_sparse | sungrow-0.1b7/sungrow/sungrow_inverter.py | ottermegazord/mit_peatflux | train | 0 |
3aeb877815f49077258d06a08324ea1f55f1f285 | [
"try:\n data = get_requested_data()\n digest = get_digest_result(data['ledger_name'])\n return digest\nexcept Exception as e:\n logger.exception('Unable to get a ledger digest!')\n return fail_response('Unable to delete the ledger. Please try again.', HTTPStatus.UNPROCESSABLE_ENTITY)",
"try:\n d... | <|body_start_0|>
try:
data = get_requested_data()
digest = get_digest_result(data['ledger_name'])
return digest
except Exception as e:
logger.exception('Unable to get a ledger digest!')
return fail_response('Unable to delete the ledger. Please ... | VerifiableServices | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifiableServices:
def get_digest_result(self):
"""Retrieving the digest of a particular ledger."""
<|body_0|>
def verify_block(self):
"""Get a journal block from a QLDB ledger. After getting the block, we get the digest of the ledger and validate the proof returned... | stack_v2_sparse_classes_75kplus_train_004659 | 2,049 | permissive | [
{
"docstring": "Retrieving the digest of a particular ledger.",
"name": "get_digest_result",
"signature": "def get_digest_result(self)"
},
{
"docstring": "Get a journal block from a QLDB ledger. After getting the block, we get the digest of the ledger and validate the proof returned in the getBl... | 2 | stack_v2_sparse_classes_30k_train_052217 | Implement the Python class `VerifiableServices` described below.
Class description:
Implement the VerifiableServices class.
Method signatures and docstrings:
- def get_digest_result(self): Retrieving the digest of a particular ledger.
- def verify_block(self): Get a journal block from a QLDB ledger. After getting the... | Implement the Python class `VerifiableServices` described below.
Class description:
Implement the VerifiableServices class.
Method signatures and docstrings:
- def get_digest_result(self): Retrieving the digest of a particular ledger.
- def verify_block(self): Get a journal block from a QLDB ledger. After getting the... | dff793c6981ae5d300bfdf8b6531ca459b484a12 | <|skeleton|>
class VerifiableServices:
def get_digest_result(self):
"""Retrieving the digest of a particular ledger."""
<|body_0|>
def verify_block(self):
"""Get a journal block from a QLDB ledger. After getting the block, we get the digest of the ledger and validate the proof returned... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VerifiableServices:
def get_digest_result(self):
"""Retrieving the digest of a particular ledger."""
try:
data = get_requested_data()
digest = get_digest_result(data['ledger_name'])
return digest
except Exception as e:
logger.exception('U... | the_stack_v2_python_sparse | hash_chain/app/modules/ledger/verifiable/services.py | ledgerfoundation/flask-qldb-boilerplate | train | 0 | |
7f6e9a802ff772a286c01c2cd62c30c714ca38a6 | [
"r = Cryptomkt.get_orderbook(ordertype, market)\nlast_orders = []\nif r is not None:\n for elem in r['data'][0:n]:\n last_orders.append({'price': elem['price'], 'amount': elem['amount']})\nreturn last_orders",
"market = market.replace('-', '')\norder = Cryptomkt.order_dict[ordertype]\npayload = {'market... | <|body_start_0|>
r = Cryptomkt.get_orderbook(ordertype, market)
last_orders = []
if r is not None:
for elem in r['data'][0:n]:
last_orders.append({'price': elem['price'], 'amount': elem['amount']})
return last_orders
<|end_body_0|>
<|body_start_1|>
ma... | Cryptomkt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cryptomkt:
def get_n_last_orders(ordertype, market, n):
""":param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', 'price': '400.1'},...]"""
<|body_0|>
def get_orderbook(ordertype, market):
""... | stack_v2_sparse_classes_75kplus_train_004660 | 2,221 | no_license | [
{
"docstring": ":param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', 'price': '400.1'},...]",
"name": "get_n_last_orders",
"signature": "def get_n_last_orders(ordertype, market, n)"
},
{
"docstring": "returns bids or a... | 3 | stack_v2_sparse_classes_30k_train_014215 | Implement the Python class `Cryptomkt` described below.
Class description:
Implement the Cryptomkt class.
Method signatures and docstrings:
- def get_n_last_orders(ordertype, market, n): :param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', ... | Implement the Python class `Cryptomkt` described below.
Class description:
Implement the Cryptomkt class.
Method signatures and docstrings:
- def get_n_last_orders(ordertype, market, n): :param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', ... | c7d6a9bc550e05c84260ef5b9a2b74d91124bf3b | <|skeleton|>
class Cryptomkt:
def get_n_last_orders(ordertype, market, n):
""":param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', 'price': '400.1'},...]"""
<|body_0|>
def get_orderbook(ordertype, market):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cryptomkt:
def get_n_last_orders(ordertype, market, n):
""":param ordertype: <str> 'bids' or 'asks' :param market: <str> e.g. 'etheur' or 'eth-eur' :return: <list> e.g. [{'amount': '0.067', 'price': '400.1'},...]"""
r = Cryptomkt.get_orderbook(ordertype, market)
last_orders = []
... | the_stack_v2_python_sparse | pyarboto/cryptomkt.py | chainimpact/arboto | train | 0 | |
d5ad142f7959ffb73796181a9cc8e597cd24028a | [
"_ChromosomeComponent.__init__(self)\nself._name = chromosome_name\nself.start_x_position = -1\nself.end_x_position = -1\nself.start_y_position = -1\nself.end_y_position = -1\nself.title_size = 20\nself.scale_num = None",
"total_sub = 0\nfor sub_component in self._sub_components:\n total_sub += sub_component.s... | <|body_start_0|>
_ChromosomeComponent.__init__(self)
self._name = chromosome_name
self.start_x_position = -1
self.end_x_position = -1
self.start_y_position = -1
self.end_y_position = -1
self.title_size = 20
self.scale_num = None
<|end_body_0|>
<|body_star... | Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism. | Chromosome | [
"Apache-2.0",
"LicenseRef-scancode-biopython"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chromosome:
"""Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism."""
def __init__(self, chromosome_name):
... | stack_v2_sparse_classes_75kplus_train_004661 | 17,083 | permissive | [
{
"docstring": "Initialize a Chromosome for drawing. Arguments: o chromosome_name - The label for the chromosome. Attributes: o start_x_position, end_x_position - The x positions on the page where the chromosome should be drawn. This allows multiple chromosomes to be drawn on a single page. o start_y_position, ... | 4 | stack_v2_sparse_classes_30k_train_011145 | Implement the Python class `Chromosome` described below.
Class description:
Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism.
Method s... | Implement the Python class `Chromosome` described below.
Class description:
Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism.
Method s... | 0fa264903414ac0b552d363d139746ead198f06a | <|skeleton|>
class Chromosome:
"""Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism."""
def __init__(self, chromosome_name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chromosome:
"""Class for drawing a chromosome of an organism. This organizes the drawing of a single organisms chromosome. This class can be instantiated directly, but the draw method makes the most sense to be called in the context of an organism."""
def __init__(self, chromosome_name):
"""Initi... | the_stack_v2_python_sparse | scripts/mp-scripts/Bio/Graphics/BasicChromosome.py | dbmi-pitt/DIKB-Micropublication | train | 6 |
6cefd24cf05b727ad38b80d1ce155a168445cf9a | [
"self.bucketer = Bucketer()\nself.bucket_count = self.bucketer.get_bucket_count()\nself.equity_matrix = arguments.Tensor(self.bucket_count, self.bucket_count).zero_()\nboards = card_tools.get_second_round_boards()\nself.board_count = boards.size(0)\nself.terminal_equity = TerminalEquity()\nfor i in range(self.board... | <|body_start_0|>
self.bucketer = Bucketer()
self.bucket_count = self.bucketer.get_bucket_count()
self.equity_matrix = arguments.Tensor(self.bucket_count, self.bucket_count).zero_()
boards = card_tools.get_second_round_boards()
self.board_count = boards.size(0)
self.termin... | MockNnTerminal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockNnTerminal:
def __init__(self):
"""Constructor. Creates an equity matrix with entries for every possible pair of buckets."""
<|body_0|>
def get_value(self, inputs, outputs):
"""Gives the expected showdown equity of the two players' ranges. Params: inputs: An NxI ... | stack_v2_sparse_classes_75kplus_train_004662 | 2,379 | no_license | [
{
"docstring": "Constructor. Creates an equity matrix with entries for every possible pair of buckets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Gives the expected showdown equity of the two players' ranges. Params: inputs: An NxI tensor containing N instances of... | 2 | stack_v2_sparse_classes_30k_train_054738 | Implement the Python class `MockNnTerminal` described below.
Class description:
Implement the MockNnTerminal class.
Method signatures and docstrings:
- def __init__(self): Constructor. Creates an equity matrix with entries for every possible pair of buckets.
- def get_value(self, inputs, outputs): Gives the expected ... | Implement the Python class `MockNnTerminal` described below.
Class description:
Implement the MockNnTerminal class.
Method signatures and docstrings:
- def __init__(self): Constructor. Creates an equity matrix with entries for every possible pair of buckets.
- def get_value(self, inputs, outputs): Gives the expected ... | 32ee307e022ee4656c416e7b35da4426f7cea5ea | <|skeleton|>
class MockNnTerminal:
def __init__(self):
"""Constructor. Creates an equity matrix with entries for every possible pair of buckets."""
<|body_0|>
def get_value(self, inputs, outputs):
"""Gives the expected showdown equity of the two players' ranges. Params: inputs: An NxI ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MockNnTerminal:
def __init__(self):
"""Constructor. Creates an equity matrix with entries for every possible pair of buckets."""
self.bucketer = Bucketer()
self.bucket_count = self.bucketer.get_bucket_count()
self.equity_matrix = arguments.Tensor(self.bucket_count, self.bucket_... | the_stack_v2_python_sparse | Source/Nn/mock_nn_terminal.py | DongdongBai/PyDeepLeduc | train | 0 | |
f43bc2a49275bd2dbc69f1a44540384b1397321d | [
"super().__init__(parent, MenuList)\nself.parent = parent\nself.loadTitle(getResourcePath('assets/settings/colourTitle.png'))\nself.loadWidgets()",
"for key, item in maze.tileColours.items():\n tileName = key.name.replace('_', ' ').title()\n container = tk.Frame(self, width=200)\n container.grid(row=key.... | <|body_start_0|>
super().__init__(parent, MenuList)
self.parent = parent
self.loadTitle(getResourcePath('assets/settings/colourTitle.png'))
self.loadWidgets()
<|end_body_0|>
<|body_start_1|>
for key, item in maze.tileColours.items():
tileName = key.name.replace('_', ... | Class for the applications Colour Menu | ColourSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColourSettings:
"""Class for the applications Colour Menu"""
def __init__(self, parent):
"""Arguments: parent -- The parent tkinter object for this screen."""
<|body_0|>
def loadWidgets(self):
"""Method used to create menu's widgets"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus_train_004663 | 33,702 | no_license | [
{
"docstring": "Arguments: parent -- The parent tkinter object for this screen.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Method used to create menu's widgets",
"name": "loadWidgets",
"signature": "def loadWidgets(self)"
},
{
"docstring": ... | 4 | null | Implement the Python class `ColourSettings` described below.
Class description:
Class for the applications Colour Menu
Method signatures and docstrings:
- def __init__(self, parent): Arguments: parent -- The parent tkinter object for this screen.
- def loadWidgets(self): Method used to create menu's widgets
- def set... | Implement the Python class `ColourSettings` described below.
Class description:
Class for the applications Colour Menu
Method signatures and docstrings:
- def __init__(self, parent): Arguments: parent -- The parent tkinter object for this screen.
- def loadWidgets(self): Method used to create menu's widgets
- def set... | 25f7e36476ae7a6bcca739c371ed493445832cb0 | <|skeleton|>
class ColourSettings:
"""Class for the applications Colour Menu"""
def __init__(self, parent):
"""Arguments: parent -- The parent tkinter object for this screen."""
<|body_0|>
def loadWidgets(self):
"""Method used to create menu's widgets"""
<|body_1|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColourSettings:
"""Class for the applications Colour Menu"""
def __init__(self, parent):
"""Arguments: parent -- The parent tkinter object for this screen."""
super().__init__(parent, MenuList)
self.parent = parent
self.loadTitle(getResourcePath('assets/settings/colourTitl... | the_stack_v2_python_sparse | application.py | FelixRandle/PathFinding | train | 0 |
e083d704b7969b667a9ad50be3fd6c3f202dfff0 | [
"parser.add_mutually_exclusive_group()\nparser.add_argument('--delete', action='store_true', help='Delete existing data')\nparser.add_argument('--preserve', action='store_true', help='Preserve existing data')",
"if not settings.DEBUG:\n raise Exception('Trying to seed in production.')\nassert not (delete and p... | <|body_start_0|>
parser.add_mutually_exclusive_group()
parser.add_argument('--delete', action='store_true', help='Delete existing data')
parser.add_argument('--preserve', action='store_true', help='Preserve existing data')
<|end_body_0|>
<|body_start_1|>
if not settings.DEBUG:
... | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
<|body_0|>
def handle(self, *args, delete: bool, preserve: bool, **options):
"""Handle the command and do the seeding"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_004664 | 24,783 | permissive | [
{
"docstring": "Add arguments to the argparser for the command",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Handle the command and do the seeding",
"name": "handle",
"signature": "def handle(self, *args, delete: bool, preserve: bool, **opti... | 2 | stack_v2_sparse_classes_30k_train_007232 | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the argparser for the command
- def handle(self, *args, delete: bool, preserve: bool, **options): Handle the command and do the se... | Implement the Python class `Command` described below.
Class description:
Implement the Command class.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the argparser for the command
- def handle(self, *args, delete: bool, preserve: bool, **options): Handle the command and do the se... | 5661cbea1011f8851a244ae3d72351fce647123f | <|skeleton|>
class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
<|body_0|>
def handle(self, *args, delete: bool, preserve: bool, **options):
"""Handle the command and do the seeding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
def add_arguments(self, parser):
"""Add arguments to the argparser for the command"""
parser.add_mutually_exclusive_group()
parser.add_argument('--delete', action='store_true', help='Delete existing data')
parser.add_argument('--preserve', action='store_true', help='Pr... | the_stack_v2_python_sparse | nablapps/core/management/commands/seed.py | Nabla-NTNU/nablaweb | train | 21 | |
69ae99204d06b7b710f712c8afec9167ba62c6c5 | [
"from collections import Counter\ncounter = Counter(nums)\nreturn [item[0] for item in counter.most_common(k)]",
"import heapq\nfreq_count = {}\nfor num in nums:\n freq_count[num] = freq_count.get(num, 0) + 1\nheap = [(count, num) for num, count in freq_count.items()]\nheapq.heapify(heap)\nreturn [item[1] for ... | <|body_start_0|>
from collections import Counter
counter = Counter(nums)
return [item[0] for item in counter.most_common(k)]
<|end_body_0|>
<|body_start_1|>
import heapq
freq_count = {}
for num in nums:
freq_count[num] = freq_count.get(num, 0) + 1
hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_004665 | 815 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent2",
"signature": "def topKFrequent2(self, nums, k)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
from collections import Counter
counter = Counter(nums)
return [item[0] for item in counter.most_common(k)]
def topKFrequent2(self, nums, k):
""":type nums: List[i... | the_stack_v2_python_sparse | py/leetcode_py/347.py | imsure/tech-interview-prep | train | 0 | |
8574490d445dad691dc8876ff62e146d544c468d | [
"def Node():\n return defaultdict(Node)\nself.root = Node()",
"self.dict = dict\nfor word in dict:\n cur = self.root\n for w in word:\n cur = cur[w]\n cur['#'] = True",
"def f(d, wd, modified):\n if len(wd) == 0 and d.get('#') and modified:\n return True\n for i, s in enumerate(w... | <|body_start_0|>
def Node():
return defaultdict(Node)
self.root = Node()
<|end_body_0|>
<|body_start_1|>
self.dict = dict
for word in dict:
cur = self.root
for w in word:
cur = cur[w]
cur['#'] = True
<|end_body_1|>
<|body_... | MagicDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
<|body_1|>
def search(self, word):
"""Return... | stack_v2_sparse_classes_75kplus_train_004666 | 2,930 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Build a dictionary through a list of words :type dict: List[str] :rtype: None",
"name": "buildDict",
"signature": "def buildDict(self, dict)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_051588 | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dict): Build a dictionary through a list of words :type dict: List[str] :rtype: None
... | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dict): Build a dictionary through a list of words :type dict: List[str] :rtype: None
... | 69cf9087d5ef48aef9126c8279502488e36f97e3 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
<|body_1|>
def search(self, word):
"""Return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
def Node():
return defaultdict(Node)
self.root = Node()
def buildDict(self, dict):
"""Build a dictionary through a list of words :type dict: List[str] :rtype: None"""
self.d... | the_stack_v2_python_sparse | 676.实现一个魔法字典.py | kailunfan/lcode | train | 0 | |
5529715989d1d82f82ecaae57184868ce8fdf701 | [
"if not is_loading:\n sys.stdout.write(os.linesep)\n print('[screenshot.py] Web page loading is complete')\n browser.GetMainFrame().GetSource(self._visitor)\n cef.PostTask(cef.TID_UI, exit_app, browser)",
"if not frame.IsMain():\n return\nprint('[screenshot.py] ERROR: Failed to load url: {url}'.for... | <|body_start_0|>
if not is_loading:
sys.stdout.write(os.linesep)
print('[screenshot.py] Web page loading is complete')
browser.GetMainFrame().GetSource(self._visitor)
cef.PostTask(cef.TID_UI, exit_app, browser)
<|end_body_0|>
<|body_start_1|>
if not frame... | LoadHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
<|body_0|>
def OnLoadError(self, browser, frame, error_code, failed_url, **_):
"""Called when the resource load for a navigation fails or is cancel... | stack_v2_sparse_classes_75kplus_train_004667 | 4,540 | no_license | [
{
"docstring": "Called when the loading state has changed.",
"name": "OnLoadingStateChange",
"signature": "def OnLoadingStateChange(self, browser, is_loading, **_)"
},
{
"docstring": "Called when the resource load for a navigation fails or is canceled.",
"name": "OnLoadError",
"signature... | 2 | stack_v2_sparse_classes_30k_train_023466 | Implement the Python class `LoadHandler` described below.
Class description:
Implement the LoadHandler class.
Method signatures and docstrings:
- def OnLoadingStateChange(self, browser, is_loading, **_): Called when the loading state has changed.
- def OnLoadError(self, browser, frame, error_code, failed_url, **_): C... | Implement the Python class `LoadHandler` described below.
Class description:
Implement the LoadHandler class.
Method signatures and docstrings:
- def OnLoadingStateChange(self, browser, is_loading, **_): Called when the loading state has changed.
- def OnLoadError(self, browser, frame, error_code, failed_url, **_): C... | 2a1b5c62a5fcdaf31bc961ee5a75fb9e640f3e93 | <|skeleton|>
class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
<|body_0|>
def OnLoadError(self, browser, frame, error_code, failed_url, **_):
"""Called when the resource load for a navigation fails or is cancel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadHandler:
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
sys.stdout.write(os.linesep)
print('[screenshot.py] Web page loading is complete')
browser.GetMainFrame().GetSource(sel... | the_stack_v2_python_sparse | cef_offscreen.py | adoregnu/scrapper | train | 1 | |
6ebfd978210dab4296d9d877c95bef168a8d3025 | [
"resource_args.AddTopicResourceArg(parser, 'to update.')\nlabels_util.AddUpdateLabelsFlags(parser)\nresource_args.AddResourceArgs(parser, [kms_resource_args.GetKmsKeyPresentationSpec('topic', flag_overrides=_KMS_FLAG_OVERRIDES, permission_info=_KMS_PERMISSION_INFO)])\nmsp_group = parser.add_group(mutex=True, help='... | <|body_start_0|>
resource_args.AddTopicResourceArg(parser, 'to update.')
labels_util.AddUpdateLabelsFlags(parser)
resource_args.AddResourceArgs(parser, [kms_resource_args.GetKmsKeyPresentationSpec('topic', flag_overrides=_KMS_FLAG_OVERRIDES, permission_info=_KMS_PERMISSION_INFO)])
msp_gr... | Updates an existing Cloud Pub/Sub topic. | Update | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Updates an existing Cloud Pub/Sub topic."""
def Args(parser):
"""Registers flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that... | stack_v2_sparse_classes_75kplus_train_004668 | 6,372 | permissive | [
{
"docstring": "Registers flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: A serializ... | 2 | null | Implement the Python class `Update` described below.
Class description:
Updates an existing Cloud Pub/Sub topic.
Method signatures and docstrings:
- def Args(parser): Registers flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. A... | Implement the Python class `Update` described below.
Class description:
Updates an existing Cloud Pub/Sub topic.
Method signatures and docstrings:
- def Args(parser): Registers flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. A... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Update:
"""Updates an existing Cloud Pub/Sub topic."""
def Args(parser):
"""Registers flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Update:
"""Updates an existing Cloud Pub/Sub topic."""
def Args(parser):
"""Registers flags for this command."""
resource_args.AddTopicResourceArg(parser, 'to update.')
labels_util.AddUpdateLabelsFlags(parser)
resource_args.AddResourceArgs(parser, [kms_resource_args.GetKms... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/pubsub/topics/update.py | bopopescu/socialliteapp | train | 0 |
8a299c426800f713d9c009179e5fedad20afa1fc | [
"train_data, eval_data = cifar10.load_data()\ntest_data = eval_data.split(0.5)\ncollaborator_count = kwargs['collaborator_count']\ntrain_data, eval_data, test_data = self.split_data(train_data, eval_data, test_data, int(data_path), collaborator_count)\nprint(f'train_data = {train_data}')\nprint(f'eval_data = {eval_... | <|body_start_0|>
train_data, eval_data = cifar10.load_data()
test_data = eval_data.split(0.5)
collaborator_count = kwargs['collaborator_count']
train_data, eval_data, test_data = self.split_data(train_data, eval_data, test_data, int(data_path), collaborator_count)
print(f'train_d... | TensorFlow Data Loader for MNIST Dataset. | FastEstimatorCifarInMemory | [
"LicenseRef-scancode-protobuf",
"MPL-2.0",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to su... | stack_v2_sparse_classes_75kplus_train_004669 | 3,070 | permissive | [
{
"docstring": "Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to super init and load_mnist_shard",
"name": "__init__",
"signature": "def __init__(self, data_path, batch_size, **kwargs)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_016653 | Implement the Python class `FastEstimatorCifarInMemory` described below.
Class description:
TensorFlow Data Loader for MNIST Dataset.
Method signatures and docstrings:
- def __init__(self, data_path, batch_size, **kwargs): Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the... | Implement the Python class `FastEstimatorCifarInMemory` described below.
Class description:
TensorFlow Data Loader for MNIST Dataset.
Method signatures and docstrings:
- def __init__(self, data_path, batch_size, **kwargs): Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the... | bd73b749a9ea1b92dbcdd07e639752101d769fc0 | <|skeleton|>
class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to su... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastEstimatorCifarInMemory:
"""TensorFlow Data Loader for MNIST Dataset."""
def __init__(self, data_path, batch_size, **kwargs):
"""Initialize. Args: data_path: File path for the dataset batch_size (int): The batch size for the data loader **kwargs: Additional arguments, passed to super init and ... | the_stack_v2_python_sparse | openfl-workspace/fe_tf_adversarial_cifar/src/fecifar_inmemory.py | PDuckworth/openfl | train | 0 |
34001ba497d873a432b2088ae5c025cac7017fbf | [
"pad = (pool_size - 1) // 2\nfmap_max = F.max_pool2d(fmap, pool_size, stride=1, padding=pad)\nkeep = (fmap_max == fmap).float()\nreturn fmap * keep",
"batch, channel, height, width = scores.shape\ntopk_scores, topk_inds = torch.topk(scores.reshape(batch, channel, -1), K)\ntopk_inds = topk_inds % (height * width)\... | <|body_start_0|>
pad = (pool_size - 1) // 2
fmap_max = F.max_pool2d(fmap, pool_size, stride=1, padding=pad)
keep = (fmap_max == fmap).float()
return fmap * keep
<|end_body_0|>
<|body_start_1|>
batch, channel, height, width = scores.shape
topk_scores, topk_inds = torch.to... | CenterNetDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterNetDecoder:
def pseudo_nms(fmap, pool_size=3):
"""apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-pooling"""
<|body_0|>
def topk_score(scores, K=40):
"""get top K point in score map"... | stack_v2_sparse_classes_75kplus_train_004670 | 6,338 | no_license | [
{
"docstring": "apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-pooling",
"name": "pseudo_nms",
"signature": "def pseudo_nms(fmap, pool_size=3)"
},
{
"docstring": "get top K point in score map",
"name": "topk_scor... | 2 | stack_v2_sparse_classes_30k_train_034323 | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def pseudo_nms(fmap, pool_size=3): apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-... | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def pseudo_nms(fmap, pool_size=3): apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-... | f92c0d3679b7b6793e62c72d7347b05763bcbf00 | <|skeleton|>
class CenterNetDecoder:
def pseudo_nms(fmap, pool_size=3):
"""apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-pooling"""
<|body_0|>
def topk_score(scores, K=40):
"""get top K point in score map"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterNetDecoder:
def pseudo_nms(fmap, pool_size=3):
"""apply max pooling to get the same effect of nms Args: fmap(Tensor): output tensor of previous step pool_size(int): size of max-pooling"""
pad = (pool_size - 1) // 2
fmap_max = F.max_pool2d(fmap, pool_size, stride=1, padding=pad)
... | the_stack_v2_python_sparse | det3d/models/dense_heads/centernet_utils.py | lianqing11/MonoJSG | train | 28 | |
cd0572fdfaebc235c2a4a529d64f9919b56be381 | [
"user_data = {'username': 'testuser', 'email': 'test@testuser.com', 'password': 'password', 'fullname': 'fullname', 'bio': 'my bio'}\nresponse = self.client.post(self.url, user_data)\nself.assertEqual(400, response.status_code)",
"user_data = {'username': 'testuser', 'email': 'test@testuser.com', 'password': 'lon... | <|body_start_0|>
user_data = {'username': 'testuser', 'email': 'test@testuser.com', 'password': 'password', 'fullname': 'fullname', 'bio': 'my bio'}
response = self.client.post(self.url, user_data)
self.assertEqual(400, response.status_code)
<|end_body_0|>
<|body_start_1|>
user_data = {... | RegistrAPIViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
<|body_0|>
def test_user_registration(self):
"""Test to verify that a post call with user valid data"""
<|body_1|>
def test_unique_usern... | stack_v2_sparse_classes_75kplus_train_004671 | 7,566 | no_license | [
{
"docstring": "Test to verify that a post call with invalid passwords",
"name": "test_invalid_password",
"signature": "def test_invalid_password(self)"
},
{
"docstring": "Test to verify that a post call with user valid data",
"name": "test_user_registration",
"signature": "def test_user... | 4 | null | Implement the Python class `RegistrAPIViewTestCase` described below.
Class description:
Implement the RegistrAPIViewTestCase class.
Method signatures and docstrings:
- def test_invalid_password(self): Test to verify that a post call with invalid passwords
- def test_user_registration(self): Test to verify that a post... | Implement the Python class `RegistrAPIViewTestCase` described below.
Class description:
Implement the RegistrAPIViewTestCase class.
Method signatures and docstrings:
- def test_invalid_password(self): Test to verify that a post call with invalid passwords
- def test_user_registration(self): Test to verify that a post... | 37886ca271a08a61dfe5923c439fa9b37ba74de6 | <|skeleton|>
class RegistrAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
<|body_0|>
def test_user_registration(self):
"""Test to verify that a post call with user valid data"""
<|body_1|>
def test_unique_usern... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrAPIViewTestCase:
def test_invalid_password(self):
"""Test to verify that a post call with invalid passwords"""
user_data = {'username': 'testuser', 'email': 'test@testuser.com', 'password': 'password', 'fullname': 'fullname', 'bio': 'my bio'}
response = self.client.post(self.url... | the_stack_v2_python_sparse | core/user/tests.py | Semilock/AxasKhone-BackEnd | train | 2 | |
8a9c0b68b6eda7ede3d9894e7e0e1fe5fd5d836b | [
"primes = [2, 3, 5, 7, 13, 17, 19, 31]\nfor p in primes:\n euclid = (1 << p - 1) * ((1 << p) - 1)\n if euclid == num:\n break\nreturn euclid == num",
"if num < 1:\n return False\ntotal = 0\nfor i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n total += i\n if i * i != num:\... | <|body_start_0|>
primes = [2, 3, 5, 7, 13, 17, 19, 31]
for p in primes:
euclid = (1 << p - 1) * ((1 << p) - 1)
if euclid == num:
break
return euclid == num
<|end_body_0|>
<|body_start_1|>
if num < 1:
return False
total = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool Using Euclid-Euler Theorem"""
<|body_0|>
def checkPerfectNumber2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
primes = [2, 3, 5... | stack_v2_sparse_classes_75kplus_train_004672 | 1,214 | no_license | [
{
"docstring": ":type num: int :rtype: bool Using Euclid-Euler Theorem",
"name": "checkPerfectNumber",
"signature": "def checkPerfectNumber(self, num)"
},
{
"docstring": ":type num: int :rtype: bool",
"name": "checkPerfectNumber2",
"signature": "def checkPerfectNumber2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030415 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPerfectNumber(self, num): :type num: int :rtype: bool Using Euclid-Euler Theorem
- def checkPerfectNumber2(self, num): :type num: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPerfectNumber(self, num): :type num: int :rtype: bool Using Euclid-Euler Theorem
- def checkPerfectNumber2(self, num): :type num: int :rtype: bool
<|skeleton|>
class So... | b7e92f9a7c4d6652d4901b189f51063ce5520653 | <|skeleton|>
class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool Using Euclid-Euler Theorem"""
<|body_0|>
def checkPerfectNumber2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool Using Euclid-Euler Theorem"""
primes = [2, 3, 5, 7, 13, 17, 19, 31]
for p in primes:
euclid = (1 << p - 1) * ((1 << p) - 1)
if euclid == num:
break
return euclid ... | the_stack_v2_python_sparse | leetcode/easy/perfect_number.py | abkunal/Data-Structures-and-Algorithms | train | 2 | |
103da01cb620c292ada4a2cc4561e06713d7ed7b | [
"super(Run, self).__init__()\nself.tree = tree if tree else tmt.Tree('.')\nself._workdir_init(id_)\nself.debug(f\"Using tree '{self.tree.root}'.\")\nself._plans = None",
"if self._plans is None:\n self._plans = self.tree.plans(run=self)\nreturn self._plans",
"self.info(self.workdir, color='magenta')\nif self... | <|body_start_0|>
super(Run, self).__init__()
self.tree = tree if tree else tmt.Tree('.')
self._workdir_init(id_)
self.debug(f"Using tree '{self.tree.root}'.")
self._plans = None
<|end_body_0|>
<|body_start_1|>
if self._plans is None:
self._plans = self.tree.p... | Test run, a container of plans | Run | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Run:
"""Test run, a container of plans"""
def __init__(self, id_=None, tree=None):
"""Initialize tree, workdir and plans"""
<|body_0|>
def plans(self):
"""Test plans for execution"""
<|body_1|>
def go(self):
"""Go and do test steps for select... | stack_v2_sparse_classes_75kplus_train_004673 | 19,514 | permissive | [
{
"docstring": "Initialize tree, workdir and plans",
"name": "__init__",
"signature": "def __init__(self, id_=None, tree=None)"
},
{
"docstring": "Test plans for execution",
"name": "plans",
"signature": "def plans(self)"
},
{
"docstring": "Go and do test steps for selected plans... | 3 | stack_v2_sparse_classes_30k_train_033946 | Implement the Python class `Run` described below.
Class description:
Test run, a container of plans
Method signatures and docstrings:
- def __init__(self, id_=None, tree=None): Initialize tree, workdir and plans
- def plans(self): Test plans for execution
- def go(self): Go and do test steps for selected plans | Implement the Python class `Run` described below.
Class description:
Test run, a container of plans
Method signatures and docstrings:
- def __init__(self, id_=None, tree=None): Initialize tree, workdir and plans
- def plans(self): Test plans for execution
- def go(self): Go and do test steps for selected plans
<|ske... | 83f699d7ba580ada07f114182503d492402cf6a8 | <|skeleton|>
class Run:
"""Test run, a container of plans"""
def __init__(self, id_=None, tree=None):
"""Initialize tree, workdir and plans"""
<|body_0|>
def plans(self):
"""Test plans for execution"""
<|body_1|>
def go(self):
"""Go and do test steps for select... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Run:
"""Test run, a container of plans"""
def __init__(self, id_=None, tree=None):
"""Initialize tree, workdir and plans"""
super(Run, self).__init__()
self.tree = tree if tree else tmt.Tree('.')
self._workdir_init(id_)
self.debug(f"Using tree '{self.tree.root}'.")... | the_stack_v2_python_sparse | tmt/base.py | TomasTomecek/tmt | train | 0 |
edc4e3898b45535f17f5ca3b5c2f51e5fd98273a | [
"self.status = AnalysisStatusCode.IN_PROGRESS\nself.url = url\nself.result = None\nself.name = name\nself._api = IntezerApi(api or get_global_api())",
"if self.status != AnalysisStatusCode.FINISHED:\n if not self.check_status():\n raise errors.OperationStillRunningError(self.name)\nreturn self.result",
... | <|body_start_0|>
self.status = AnalysisStatusCode.IN_PROGRESS
self.url = url
self.result = None
self.name = name
self._api = IntezerApi(api or get_global_api())
<|end_body_0|>
<|body_start_1|>
if self.status != AnalysisStatusCode.FINISHED:
if not self.check_s... | The Operation class is used to represent an asynchronous operation with the Intezer API. | Operation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Operation:
"""The Operation class is used to represent an asynchronous operation with the Intezer API."""
def __init__(self, url: str, name: str, api: IntezerApiClient=None):
"""Initializes the Operation instance with the given url, name, and api (defaults to the global API instance ... | stack_v2_sparse_classes_75kplus_train_004674 | 2,930 | permissive | [
{
"docstring": "Initializes the Operation instance with the given url, name, and api (defaults to the global API instance if not specified). :param url: The URL of the operation that will be used to query the result. :param name: The name of the operation. :param api: The API connection to Intezer.",
"name"... | 4 | stack_v2_sparse_classes_30k_train_028313 | Implement the Python class `Operation` described below.
Class description:
The Operation class is used to represent an asynchronous operation with the Intezer API.
Method signatures and docstrings:
- def __init__(self, url: str, name: str, api: IntezerApiClient=None): Initializes the Operation instance with the given... | Implement the Python class `Operation` described below.
Class description:
The Operation class is used to represent an asynchronous operation with the Intezer API.
Method signatures and docstrings:
- def __init__(self, url: str, name: str, api: IntezerApiClient=None): Initializes the Operation instance with the given... | ad7bee79976ae7936caba9e9f3f1ebacae31c1c1 | <|skeleton|>
class Operation:
"""The Operation class is used to represent an asynchronous operation with the Intezer API."""
def __init__(self, url: str, name: str, api: IntezerApiClient=None):
"""Initializes the Operation instance with the given url, name, and api (defaults to the global API instance ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Operation:
"""The Operation class is used to represent an asynchronous operation with the Intezer API."""
def __init__(self, url: str, name: str, api: IntezerApiClient=None):
"""Initializes the Operation instance with the given url, name, and api (defaults to the global API instance if not specif... | the_stack_v2_python_sparse | intezer_sdk/operation.py | intezer/analyze-python-sdk | train | 26 |
dd42226d1c076aad0097d809e3d1f11601a6a6e7 | [
"with open('polkadots/initial_game_state.json') as file:\n data = json.load(file)\nself.game = game.Game(data)\nself.colour = colour\nself.agent = agent.Agent(colour)\nself.turn_num = 1\nself.token_num = 12\nself.past_states = []\nself.state_score = {}",
"import math\nc = 3600\nb = 5 * self.token_num\nsearch_d... | <|body_start_0|>
with open('polkadots/initial_game_state.json') as file:
data = json.load(file)
self.game = game.Game(data)
self.colour = colour
self.agent = agent.Agent(colour)
self.turn_num = 1
self.token_num = 12
self.past_states = []
self.s... | ExamplePlayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamplePlayer:
def __init__(self, colour):
"""This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to ... | stack_v2_sparse_classes_75kplus_train_004675 | 4,034 | no_license | [
{
"docstring": "This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter c... | 3 | null | Implement the Python class `ExamplePlayer` described below.
Class description:
Implement the ExamplePlayer class.
Method signatures and docstrings:
- def __init__(self, colour): This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own intern... | Implement the Python class `ExamplePlayer` described below.
Class description:
Implement the ExamplePlayer class.
Method signatures and docstrings:
- def __init__(self, colour): This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own intern... | eef589a9012933b2278a95e64086a2a36846fbc0 | <|skeleton|>
class ExamplePlayer:
def __init__(self, colour):
"""This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExamplePlayer:
def __init__(self, colour):
"""This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for t... | the_stack_v2_python_sparse | polkadots/player.py | yunwaiho/comp30024-project-b | train | 0 | |
c0fb32a3d153b2837410af667ac7864f6f55d844 | [
"if not cls.WORD.fullmatch(value):\n value = f'({value})'\nreturn value",
"if cls.QUERY.match(value):\n value = f'({value})'\nreturn value"
] | <|body_start_0|>
if not cls.WORD.fullmatch(value):
value = f'({value})'
return value
<|end_body_0|>
<|body_start_1|>
if cls.QUERY.match(value):
value = f'({value})'
return value
<|end_body_1|>
| Helper class for lexical manipulation. | Wrap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wrap:
"""Helper class for lexical manipulation."""
def word(cls, value: str) -> str:
"""Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string."""
<|body_0|>
def subquery(cls, value: str) -... | stack_v2_sparse_classes_75kplus_train_004676 | 12,351 | permissive | [
{
"docstring": "Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string.",
"name": "word",
"signature": "def word(cls, value: str) -> str"
},
{
"docstring": "If the value is a SELECT statement, it will be wrapped in... | 2 | stack_v2_sparse_classes_30k_train_037973 | Implement the Python class `Wrap` described below.
Class description:
Helper class for lexical manipulation.
Method signatures and docstrings:
- def word(cls, value: str) -> str: Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string.
-... | Implement the Python class `Wrap` described below.
Class description:
Helper class for lexical manipulation.
Method signatures and docstrings:
- def word(cls, value: str) -> str: Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string.
-... | 7a63ef9031c0b5ac567462782d2241f7fd51a11a | <|skeleton|>
class Wrap:
"""Helper class for lexical manipulation."""
def word(cls, value: str) -> str:
"""Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string."""
<|body_0|>
def subquery(cls, value: str) -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Wrap:
"""Helper class for lexical manipulation."""
def word(cls, value: str) -> str:
"""Either a single word or any string within parentheses. Args: value: String to be forced to word. Returns: Word value of the input string."""
if not cls.WORD.fullmatch(value):
value = f'({va... | the_stack_v2_python_sparse | forml/io/dsl/parser/sql.py | hieuqtran/forml | train | 0 |
5bce473350076a4b36778b6a885ec49b6fd68e36 | [
"super(MPN, self).__init__()\nself.args = args\nself.atom_fdim = atom_fdim or get_atom_fdim(args)\nself.bond_fdim = bond_fdim or get_bond_fdim(args) + (not args.atom_messages) * self.atom_fdim\nself.graph_input = graph_input\nself.encoder = MPNEncoder(self.args, self.atom_fdim, self.bond_fdim)",
"if not self.grap... | <|body_start_0|>
super(MPN, self).__init__()
self.args = args
self.atom_fdim = atom_fdim or get_atom_fdim(args)
self.bond_fdim = bond_fdim or get_bond_fdim(args) + (not args.atom_messages) * self.atom_fdim
self.graph_input = graph_input
self.encoder = MPNEncoder(self.args... | A message passing neural network for encoding a molecule. | MPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bo... | stack_v2_sparse_classes_75kplus_train_004677 | 26,669 | no_license | [
{
"docstring": "Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bond features dimension. :param graph_input: If true, expects BatchMolGraph as input. Otherwise expects a list of smiles strings as input.",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_027195 | Implement the Python class `MPN` described below.
Class description:
A message passing neural network for encoding a molecule.
Method signatures and docstrings:
- def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False): Initializes the MPN. :param args: Arguments. :param... | Implement the Python class `MPN` described below.
Class description:
A message passing neural network for encoding a molecule.
Method signatures and docstrings:
- def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False): Initializes the MPN. :param args: Arguments. :param... | 1851765edfd77f4a1ebd1702b32a11a6e8e8f01d | <|skeleton|>
class MPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MPN:
"""A message passing neural network for encoding a molecule."""
def __init__(self, args: Namespace, atom_fdim: int=None, bond_fdim: int=None, graph_input: bool=False):
"""Initializes the MPN. :param args: Arguments. :param atom_fdim: Atom features dimension. :param bond_fdim: Bond features d... | the_stack_v2_python_sparse | MIRACLE/models/mpn.py | aabbccgithub/MIRACLE | train | 0 |
e2913d34c1486f9ffb1e1b906d7804fe6548c880 | [
"Process.__init__(self)\nself.conf = conf\nself.frameshift = frameshift\nself.out_path = out_path\nself.logger = logging.getLogger('DNNParamPreparation')\nself.preserve = preserve\nself.queue = queue",
"result = ''\nwith open(input_dur_path) as f:\n total_state = self.conf.nb_emitting_states\n id_state = 1\... | <|body_start_0|>
Process.__init__(self)
self.conf = conf
self.frameshift = frameshift
self.out_path = out_path
self.logger = logging.getLogger('DNNParamPreparation')
self.preserve = preserve
self.queue = queue
<|end_body_0|>
<|body_start_1|>
result = ''
... | Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration | DNNParamPreparation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNNParamPreparation:
"""Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration"""
def __init__(self, conf, frameshift, out_path, preserve, queue):
"""Constructor :param conf: the user configuration ob... | stack_v2_sparse_classes_75kplus_train_004678 | 12,806 | no_license | [
{
"docstring": "Constructor :param conf: the user configuration object :param frameshift: the default frameshift :param out_path: path of the directory which is going to contain the input feature vector files :param preserve: switch to not delete intermediate produced files :param queue: the queue which is goin... | 4 | stack_v2_sparse_classes_30k_train_014957 | Implement the Python class `DNNParamPreparation` described below.
Class description:
Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration
Method signatures and docstrings:
- def __init__(self, conf, frameshift, out_path, preserve, q... | Implement the Python class `DNNParamPreparation` described below.
Class description:
Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration
Method signatures and docstrings:
- def __init__(self, conf, frameshift, out_path, preserve, q... | c537a391f4547fcc48aa34ca7ddd949c3ebdc441 | <|skeleton|>
class DNNParamPreparation:
"""Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration"""
def __init__(self, conf, frameshift, out_path, preserve, queue):
"""Constructor :param conf: the user configuration ob... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DNNParamPreparation:
"""Helper class to prepare the DNN input feature vectors considering the given labels, the duration produced by HTS and a given configuration"""
def __init__(self, conf, frameshift, out_path, preserve, queue):
"""Constructor :param conf: the user configuration object :param f... | the_stack_v2_python_sparse | generation/utils/dnnparamgeneration.py | seblemaguer/pyhts | train | 1 |
2d086cbf7e2003d3a23d9df7e15a53a8f84d58dd | [
"from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing\nfrom sage.combinat.permutation import Permutations\nm = self.parent()\nnames = ['{}{}{}'.format(letter, i, j) for i in range(n) for j in range(n)]\nR = PolynomialRing(m.base_ring(), n * n, names)\nx = [[R.gens()[i * n + j] for j in range... | <|body_start_0|>
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.combinat.permutation import Permutations
m = self.parent()
names = ['{}{}{}'.format(letter, i, j) for i in range(n) for j in range(n)]
R = PolynomialRing(m.base_ring(), n * n, ... | An element in the `\\mathbf{w}` basis. | Element | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Element:
"""An element in the `\\mathbf{w}` basis."""
def expand(self, n, letter='x'):
"""Expand ``self`` written in the `\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`. The expansion of an element of the `\\ma... | stack_v2_sparse_classes_75kplus_train_004679 | 23,467 | no_license | [
{
"docstring": "Expand ``self`` written in the `\\\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`. The expansion of an element of the `\\\\mathbf{w}` basis is given by equations (26) and (55) in [HNT06]_. INPUT: - ``n`` -- an integer - ``l... | 3 | stack_v2_sparse_classes_30k_train_007392 | Implement the Python class `Element` described below.
Class description:
An element in the `\\mathbf{w}` basis.
Method signatures and docstrings:
- def expand(self, n, letter='x'): Expand ``self`` written in the `\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i... | Implement the Python class `Element` described below.
Class description:
An element in the `\\mathbf{w}` basis.
Method signatures and docstrings:
- def expand(self, n, letter='x'): Expand ``self`` written in the `\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class Element:
"""An element in the `\\mathbf{w}` basis."""
def expand(self, n, letter='x'):
"""Expand ``self`` written in the `\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`. The expansion of an element of the `\\ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Element:
"""An element in the `\\mathbf{w}` basis."""
def expand(self, n, letter='x'):
"""Expand ``self`` written in the `\\mathbf{w}` basis in `n^2` commuting variables which satisfy the relation `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`. The expansion of an element of the `\\mathbf{w}` basi... | the_stack_v2_python_sparse | sage/src/sage/combinat/ncsym/dual.py | bopopescu/geosci | train | 0 |
abf5133460b9adaba7261c7da5a626bbce69329b | [
"self.object = self.get_object()\nif user.staffjournalist.newsorganization == self.object:\n return True\nraise PermissionDenied()",
"context = super(NewsOrganizationUpdateView, self).get_context_data(**kwargs)\ncontext['staff_team'] = self.object.get_staff_team()\nreturn context"
] | <|body_start_0|>
self.object = self.get_object()
if user.staffjournalist.newsorganization == self.object:
return True
raise PermissionDenied()
<|end_body_0|>
<|body_start_1|>
context = super(NewsOrganizationUpdateView, self).get_context_data(**kwargs)
context['staff_... | Update the basic information of a NewsOrganization. | NewsOrganizationUpdateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsOrganizationUpdateView:
"""Update the basic information of a NewsOrganization."""
def test_user(self, user):
"""User must be affiliated with this news organization to view the dashboard."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Include team."""
... | stack_v2_sparse_classes_75kplus_train_004680 | 3,704 | no_license | [
{
"docstring": "User must be affiliated with this news organization to view the dashboard.",
"name": "test_user",
"signature": "def test_user(self, user)"
},
{
"docstring": "Include team.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | null | Implement the Python class `NewsOrganizationUpdateView` described below.
Class description:
Update the basic information of a NewsOrganization.
Method signatures and docstrings:
- def test_user(self, user): User must be affiliated with this news organization to view the dashboard.
- def get_context_data(self, **kwarg... | Implement the Python class `NewsOrganizationUpdateView` described below.
Class description:
Update the basic information of a NewsOrganization.
Method signatures and docstrings:
- def test_user(self, user): User must be affiliated with this news organization to view the dashboard.
- def get_context_data(self, **kwarg... | d748e6f85907fa50d1d88ee003999c3d875b812b | <|skeleton|>
class NewsOrganizationUpdateView:
"""Update the basic information of a NewsOrganization."""
def test_user(self, user):
"""User must be affiliated with this news organization to view the dashboard."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Include team."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewsOrganizationUpdateView:
"""Update the basic information of a NewsOrganization."""
def test_user(self, user):
"""User must be affiliated with this news organization to view the dashboard."""
self.object = self.get_object()
if user.staffjournalist.newsorganization == self.object... | the_stack_v2_python_sparse | facet/entity/views/organization_news.py | ProjectFacet/multifacet | train | 3 |
5f59f185f20f6372044506753631cdd6adc94a27 | [
"for num in nums:\n num = abs(num)\n if nums[num] < 0:\n return num\n else:\n nums[num] = -nums[num]",
"store = [0] * len(nums)\nfor i, num in enumerate(nums):\n if store[num] == num:\n return num\n else:\n store[num] = num"
] | <|body_start_0|>
for num in nums:
num = abs(num)
if nums[num] < 0:
return num
else:
nums[num] = -nums[num]
<|end_body_0|>
<|body_start_1|>
store = [0] * len(nums)
for i, num in enumerate(nums):
if store[num] == num:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for num in nums:
num = abs(nu... | stack_v2_sparse_classes_75kplus_train_004681 | 1,159 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008113 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findDup... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
for num in nums:
num = abs(num)
if nums[num] < 0:
return num
else:
nums[num] = -nums[num]
def findDuplicate(self, nums):
""":type nu... | the_stack_v2_python_sparse | 287-find_the_duplicate_num.py | stevestar888/leetcode-problems | train | 2 | |
b961181792ef7090556b0f141e6c6eef1e0bdf8c | [
"self.project = project\nself.previously_indexed = []\nself.logger = logging.getLogger(__name__)\nself.project_logger = ProjectLogger(self.logger, project)",
"without_stops = []\nfor word in words:\n if word.word.lemma not in app.config['STOPWORDS']:\n without_stops.append(word)\nreturn without_stops",
... | <|body_start_0|>
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = ProjectLogger(self.logger, project)
<|end_body_0|>
<|body_start_1|>
without_stops = []
for word in words:
if word.word.lemma n... | Process given input into Sequences. | SequenceProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_75kplus_train_004682 | 9,006 | permissive | [
{
"docstring": "Set up local variables for the SequenceProcessor.",
"name": "__init__",
"signature": "def __init__(self, project)"
},
{
"docstring": "Remove every sort of stop from the sentences. :param list words: A list of WordInSentence objects. :return list: The list without stops.",
"na... | 4 | stack_v2_sparse_classes_30k_train_003078 | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | a45102c1848c93360d3815187783756dc5e16156 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = Pro... | the_stack_v2_python_sparse | app/preprocessor/sequenceprocessor.py | mkabbasi/wordseer | train | 0 |
3ffc0cea58c9e08502ae852eaffb7d839ba35784 | [
"if not isinstance(data, pd.DataFrame):\n data = self.peaks(data)\nif align:\n data = self.alignbead(data, ref=ref)\n ref = None\ndata = data.sort_values(['bead', trackorder, 'peakposition', 'avg'])\nassert 'resolution' in data.columns\nif ref is None:\n ref = 'identity' if 'identity' in data.columns el... | <|body_start_0|>
if not isinstance(data, pd.DataFrame):
data = self.peaks(data)
if align:
data = self.alignbead(data, ref=ref)
ref = None
data = data.sort_values(['bead', trackorder, 'peakposition', 'avg'])
assert 'resolution' in data.columns
i... | config for aligning peaks | PeaksAlignmentConfigMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
<|body_0|>
def showhpin(data, positions, ref=None, style=None, **args):
"""disp... | stack_v2_sparse_classes_75kplus_train_004683 | 10,299 | no_license | [
{
"docstring": "display the data",
"name": "showone",
"signature": "def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs)"
},
{
"docstring": "display hairpin positions",
"name": "showhpin",
"signature": "def showhpin(data, positions, ref=Non... | 3 | stack_v2_sparse_classes_30k_train_019731 | Implement the Python class `PeaksAlignmentConfigMixin` described below.
Class description:
config for aligning peaks
Method signatures and docstrings:
- def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs): display the data
- def showhpin(data, positions, ref=None, styl... | Implement the Python class `PeaksAlignmentConfigMixin` described below.
Class description:
config for aligning peaks
Method signatures and docstrings:
- def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs): display the data
- def showhpin(data, positions, ref=None, styl... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
<|body_0|>
def showhpin(data, positions, ref=None, style=None, **args):
"""disp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PeaksAlignmentConfigMixin:
"""config for aligning peaks"""
def showone(self, data, ref=None, align=True, trackorder='modification', scaling_factor=1.5, **seqs):
"""display the data"""
if not isinstance(data, pd.DataFrame):
data = self.peaks(data)
if align:
... | the_stack_v2_python_sparse | src/scripting/aligningexperiments/_view.py | depixusgenome/trackanalysis | train | 0 |
ae22676a5b448bea1e1112357f2dd2f0e42d1c0b | [
"LazyConfigure.__init__(self)\nself.url = None\nself.user = None\nself.password = None",
"LazyConfigure.configure(self)\nos.makedirs(CACHE_DIR, exist_ok=True)\ncache_name = os.path.join(CACHE_DIR, __name__)\nrequests_cache.CachedSession.__init__(self, cache_name=cache_name, expire_after=None)\nif url == '':\n ... | <|body_start_0|>
LazyConfigure.__init__(self)
self.url = None
self.user = None
self.password = None
<|end_body_0|>
<|body_start_1|>
LazyConfigure.configure(self)
os.makedirs(CACHE_DIR, exist_ok=True)
cache_name = os.path.join(CACHE_DIR, __name__)
requests... | Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process. | PhenomizerService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhenomizerService:
"""Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process."""
def __init__(self):
"""Create empty scaffold first."""
<|body_0|>
def configure(self, url: str='', user: str='', password: str=''):
... | stack_v2_sparse_classes_75kplus_train_004684 | 7,209 | permissive | [
{
"docstring": "Create empty scaffold first.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Configure the phenomizer service instance. Params: Phenomizer_Url: Url of phenomizer service Phenomizer_User: Username for the service Phenomizer_Password: Password for the ser... | 6 | null | Implement the Python class `PhenomizerService` described below.
Class description:
Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process.
Method signatures and docstrings:
- def __init__(self): Create empty scaffold first.
- def configure(self, url: str='', user: st... | Implement the Python class `PhenomizerService` described below.
Class description:
Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process.
Method signatures and docstrings:
- def __init__(self): Create empty scaffold first.
- def configure(self, url: str='', user: st... | f0ab0c7ed3833edb01ad0772ad294978b71feb64 | <|skeleton|>
class PhenomizerService:
"""Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process."""
def __init__(self):
"""Create empty scaffold first."""
<|body_0|>
def configure(self, url: str='', user: str='', password: str=''):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhenomizerService:
"""Handling of interop with Phenomizer service, which provides the pheno and boqa scores used in the process."""
def __init__(self):
"""Create empty scaffold first."""
LazyConfigure.__init__(self)
self.url = None
self.user = None
self.password = ... | the_stack_v2_python_sparse | lib/api/phenomizer.py | PEDIA-Charite/PEDIA-workflow | train | 9 |
a98cd5b6ea0fd08066013f3f25b03bdb03ada51d | [
"fields = {'_id': 0}\nif sensitivity == '1':\n sense_fields = {'standard_cost': 0}\n fields = {**fields, **sense_fields}\nelif sensitivity == '2':\n sense_fields = {'standard_cost': 0, 'tms_sales_allocated_bookings_base_list': 0}\n fields = {**fields, **sense_fields}\nreturn fields",
"if not based:\n ... | <|body_start_0|>
fields = {'_id': 0}
if sensitivity == '1':
sense_fields = {'standard_cost': 0}
fields = {**fields, **sense_fields}
elif sensitivity == '2':
sense_fields = {'standard_cost': 0, 'tms_sales_allocated_bookings_base_list': 0}
fields = {... | Contains class methods to provide others tools in generating query | MongoTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoTools:
"""Contains class methods to provide others tools in generating query"""
def hide_fields(cls, sensitivity):
"""Based on sensitivity/admin rights, it generates hideable fields query"""
<|body_0|>
def qry_aggregation(cls, field, match={}, based=''):
"""... | stack_v2_sparse_classes_75kplus_train_004685 | 5,868 | no_license | [
{
"docstring": "Based on sensitivity/admin rights, it generates hideable fields query",
"name": "hide_fields",
"signature": "def hide_fields(cls, sensitivity)"
},
{
"docstring": "Aggregation query generator for returning scalar data",
"name": "qry_aggregation",
"signature": "def qry_aggr... | 3 | stack_v2_sparse_classes_30k_train_009740 | Implement the Python class `MongoTools` described below.
Class description:
Contains class methods to provide others tools in generating query
Method signatures and docstrings:
- def hide_fields(cls, sensitivity): Based on sensitivity/admin rights, it generates hideable fields query
- def qry_aggregation(cls, field, ... | Implement the Python class `MongoTools` described below.
Class description:
Contains class methods to provide others tools in generating query
Method signatures and docstrings:
- def hide_fields(cls, sensitivity): Based on sensitivity/admin rights, it generates hideable fields query
- def qry_aggregation(cls, field, ... | 41100f86715acdc8ddafc156896920781cd78ee9 | <|skeleton|>
class MongoTools:
"""Contains class methods to provide others tools in generating query"""
def hide_fields(cls, sensitivity):
"""Based on sensitivity/admin rights, it generates hideable fields query"""
<|body_0|>
def qry_aggregation(cls, field, match={}, based=''):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MongoTools:
"""Contains class methods to provide others tools in generating query"""
def hide_fields(cls, sensitivity):
"""Based on sensitivity/admin rights, it generates hideable fields query"""
fields = {'_id': 0}
if sensitivity == '1':
sense_fields = {'standard_cost... | the_stack_v2_python_sparse | comdm/utils/querymaker.py | jeydurai/comdm | train | 0 |
5a66b20110b2947aefb4afa75292115957e03ecd | [
"try:\n return Member.objects.get(pk=pk)\nexcept Member.DoesNotExist:\n raise Http404",
"if pk is not None:\n member = self.get_member(int(pk))\nelse:\n member = None\nself.check_object_permissions(request, member)\nsavings = Savings.get_members_savings(member)\nserializer = SavingsMinimalSerializer(s... | <|body_start_0|>
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if pk is not None:
member = self.get_member(int(pk))
else:
member = None
self.check_object_permissions... | SavingsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Member's savings --- serializer: savings.serializers.SavingsMinimalSerializer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:... | stack_v2_sparse_classes_75kplus_train_004686 | 5,809 | no_license | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, pk)"
},
{
"docstring": "List Member's savings --- serializer: savings.serializers.SavingsMinimalSerializer",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015434 | Implement the Python class `SavingsView` described below.
Class description:
Implement the SavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Member's savings --- serializer: savings.serializers.SavingsMinimalSerializer | Implement the Python class `SavingsView` described below.
Class description:
Implement the SavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Member's savings --- serializer: savings.serializers.SavingsMinimalSerializer
<|ske... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class SavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Member's savings --- serializer: savings.serializers.SavingsMinimalSerializer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SavingsView:
def get_member(self, pk):
"""Get a member."""
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
"""List Member's savings --- serializer: savings.serializers.SavingsM... | the_stack_v2_python_sparse | savings/views.py | lubegamark/gosacco | train | 2 | |
d91c6af0dd2ba70391d785b296f46f9070e0a9d0 | [
"self.name = name\nself.scope = scope\nself.app_bundle_identifier = app_bundle_identifier\nself.provider_bundle_identifier = provider_bundle_identifier\nself.provider_configuration = provider_configuration\nself.uses_cert = uses_cert",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nscope... | <|body_start_0|>
self.name = name
self.scope = scope
self.app_bundle_identifier = app_bundle_identifier
self.provider_bundle_identifier = provider_bundle_identifier
self.provider_configuration = provider_configuration
self.uses_cert = uses_cert
<|end_body_0|>
<|body_star... | Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, withoutAny, or withoutAll) and a set of tags of the devices to be as... | UpdateNetworkSmProfileUmbrellaModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, witho... | stack_v2_sparse_classes_75kplus_train_004687 | 3,762 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkSmProfileUmbrellaModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, scope=None, app_bundle_identifier=None, provider_bundle_identifier=None, provider_configuration=None, uses_cert=None)"
},
{
"docstring": "Creates an ins... | 2 | stack_v2_sparse_classes_30k_train_016620 | Implement the Python class `UpdateNetworkSmProfileUmbrellaModel` described below.
Class description:
Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (on... | Implement the Python class `UpdateNetworkSmProfileUmbrellaModel` described below.
Class description:
Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (on... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, witho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateNetworkSmProfileUmbrellaModel:
"""Implementation of the 'updateNetworkSmProfileUmbrella' model. TODO: type model description here. Attributes: name (string): optional: A new name for the profile scope (string): optional: A new scope for the profile (one of all, none, withAny, withAll, withoutAny, or wit... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_sm_profile_umbrella_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
c920a5ad6413ec11274372a8e33ff16361b196a3 | [
"args = args.split()\nif _debug:\n WhoIsIAmConsoleCmd._debug('do_whois %r', args)\ntry:\n request = WhoIsRequest()\n if len(args) == 1 or len(args) == 3:\n request.pduDestination = Address(args[0])\n del args[0]\n else:\n request.pduDestination = GlobalBroadcast()\n if len(args) ... | <|body_start_0|>
args = args.split()
if _debug:
WhoIsIAmConsoleCmd._debug('do_whois %r', args)
try:
request = WhoIsRequest()
if len(args) == 1 or len(args) == 3:
request.pduDestination = Address(args[0])
del args[0]
... | WhoIsIAmConsoleCmd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhoIsIAmConsoleCmd:
def do_whois(self, args):
"""whois [ <addr>] [ <lolimit> <hilimit> ]"""
<|body_0|>
def do_iam(self, args):
"""iam"""
<|body_1|>
def do_rtn(self, args):
"""rtn <addr> <net> ..."""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_004688 | 7,081 | permissive | [
{
"docstring": "whois [ <addr>] [ <lolimit> <hilimit> ]",
"name": "do_whois",
"signature": "def do_whois(self, args)"
},
{
"docstring": "iam",
"name": "do_iam",
"signature": "def do_iam(self, args)"
},
{
"docstring": "rtn <addr> <net> ...",
"name": "do_rtn",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_010459 | Implement the Python class `WhoIsIAmConsoleCmd` described below.
Class description:
Implement the WhoIsIAmConsoleCmd class.
Method signatures and docstrings:
- def do_whois(self, args): whois [ <addr>] [ <lolimit> <hilimit> ]
- def do_iam(self, args): iam
- def do_rtn(self, args): rtn <addr> <net> ... | Implement the Python class `WhoIsIAmConsoleCmd` described below.
Class description:
Implement the WhoIsIAmConsoleCmd class.
Method signatures and docstrings:
- def do_whois(self, args): whois [ <addr>] [ <lolimit> <hilimit> ]
- def do_iam(self, args): iam
- def do_rtn(self, args): rtn <addr> <net> ...
<|skeleton|>
c... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class WhoIsIAmConsoleCmd:
def do_whois(self, args):
"""whois [ <addr>] [ <lolimit> <hilimit> ]"""
<|body_0|>
def do_iam(self, args):
"""iam"""
<|body_1|>
def do_rtn(self, args):
"""rtn <addr> <net> ..."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhoIsIAmConsoleCmd:
def do_whois(self, args):
"""whois [ <addr>] [ <lolimit> <hilimit> ]"""
args = args.split()
if _debug:
WhoIsIAmConsoleCmd._debug('do_whois %r', args)
try:
request = WhoIsRequest()
if len(args) == 1 or len(args) == 3:
... | the_stack_v2_python_sparse | samples/WhoIsIAmForeign.py | JoelBender/bacpypes | train | 284 | |
66e8e86f79ef5b260354fc79c83ffde8a0a8ee5d | [
"def inner_wrapper(wrapped_class: BaseMLMHead) -> Callable:\n for model_arch in model_arch_list:\n assert model_arch not in cls.registry\n cls.registry[model_arch] = wrapped_class\n return wrapped_class\nreturn inner_wrapper",
"mlm_head_class = self.registry[task.TASK_TYPE]\nmlm_head = mlm_hea... | <|body_start_0|>
def inner_wrapper(wrapped_class: BaseMLMHead) -> Callable:
for model_arch in model_arch_list:
assert model_arch not in cls.registry
cls.registry[model_arch] = wrapped_class
return wrapped_class
return inner_wrapper
<|end_body_0|>
... | This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model architectures to MLM task heads | JiantMLMHeadFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiantMLMHeadFactory:
"""This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model architectures to MLM task heads"""
def r... | stack_v2_sparse_classes_75kplus_train_004689 | 11,104 | permissive | [
{
"docstring": "Registers the ModelArchitectures in model_arch_list as keys mapping to a MLMHead Args: model_arch_list (List[ModelArchitectures]): List of ModelArchitectures mapping to an MLM task head. Returns: Callable: MLMHead class",
"name": "register",
"signature": "def register(cls, model_arch_lis... | 2 | stack_v2_sparse_classes_30k_train_000493 | Implement the Python class `JiantMLMHeadFactory` described below.
Class description:
This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model archit... | Implement the Python class `JiantMLMHeadFactory` described below.
Class description:
This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model archit... | daa5a258e3af5e7503288de8401429eaf3f58e13 | <|skeleton|>
class JiantMLMHeadFactory:
"""This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model architectures to MLM task heads"""
def r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JiantMLMHeadFactory:
"""This factory is used to create masked language modeling (MLM) task heads. This is required due to Transformers implementing different MLM heads for different encoders. Attributes: registry (dict): Dynamic registry mapping model architectures to MLM task heads"""
def register(cls, ... | the_stack_v2_python_sparse | jiant/proj/main/modeling/heads.py | nyu-mll/jiant | train | 1,289 |
7b7c05799b3b2436fc2989105f1539e7939e5c11 | [
"super().__init__(n_features, marginals, n_tail_features=n_tail_features, p=p, hidden_layers=hidden_layers, online_norm=online_norm, param_transform=param_transform, tail_features=tail_features)\nself.marginals = marginals\nn_channels, pdim = _get_z_shape(marginals)\nself.n_channels = n_channels\nself.tail_features... | <|body_start_0|>
super().__init__(n_features, marginals, n_tail_features=n_tail_features, p=p, hidden_layers=hidden_layers, online_norm=online_norm, param_transform=param_transform, tail_features=tail_features)
self.marginals = marginals
n_channels, pdim = _get_z_shape(marginals)
self.n_... | DefaultTail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultTail:
def __init__(self, n_features: int, marginals, hidden_layers: Sequence[int]=[256, 256, 256], p: float=0.0, online_norm: bool=True, param_transform=None, tail_features: bool=False, n_tail_features: int=2):
"""Default tail network. Args: n_features: Length of feature vector. m... | stack_v2_sparse_classes_75kplus_train_004690 | 9,403 | permissive | [
{
"docstring": "Default tail network. Args: n_features: Length of feature vector. marginals: List of marginals to learn. hidden_layers: Hidden layer size p: Dropout online_norm: Online normalization of parameters. param_transform: Perform optional parameter transform. tail_features: Use tail features. n_tail_fe... | 2 | null | Implement the Python class `DefaultTail` described below.
Class description:
Implement the DefaultTail class.
Method signatures and docstrings:
- def __init__(self, n_features: int, marginals, hidden_layers: Sequence[int]=[256, 256, 256], p: float=0.0, online_norm: bool=True, param_transform=None, tail_features: bool... | Implement the Python class `DefaultTail` described below.
Class description:
Implement the DefaultTail class.
Method signatures and docstrings:
- def __init__(self, n_features: int, marginals, hidden_layers: Sequence[int]=[256, 256, 256], p: float=0.0, online_norm: bool=True, param_transform=None, tail_features: bool... | 5f8721d4af044d7e7c66d1a8018c89018f7cca0f | <|skeleton|>
class DefaultTail:
def __init__(self, n_features: int, marginals, hidden_layers: Sequence[int]=[256, 256, 256], p: float=0.0, online_norm: bool=True, param_transform=None, tail_features: bool=False, n_tail_features: int=2):
"""Default tail network. Args: n_features: Length of feature vector. m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultTail:
def __init__(self, n_features: int, marginals, hidden_layers: Sequence[int]=[256, 256, 256], p: float=0.0, online_norm: bool=True, param_transform=None, tail_features: bool=False, n_tail_features: int=2):
"""Default tail network. Args: n_features: Length of feature vector. marginals: List... | the_stack_v2_python_sparse | swyft/networks/tail.py | andrew-lundgren/swyft | train | 0 | |
125bc8cec223ac30d5a5505cb0a1fa8c0c455a0c | [
"self.N = len(nums) + 1\nself.tree = [0] * self.N\nself.nums = nums\nself.init = True\nfor idx, val in enumerate(nums):\n self.update(idx, val * 2)\nself.init = False",
"diff = val - self.nums[i]\nif not self.init:\n self.nums[i] = val\ni += 1\nwhile i < self.N:\n self.tree[i] += diff\n i += i & -i",
... | <|body_start_0|>
self.N = len(nums) + 1
self.tree = [0] * self.N
self.nums = nums
self.init = True
for idx, val in enumerate(nums):
self.update(idx, val * 2)
self.init = False
<|end_body_0|>
<|body_start_1|>
diff = val - self.nums[i]
if not se... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int ... | stack_v2_sparse_classes_75kplus_train_004691 | 3,945 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int :rtype: void",... | 3 | stack_v2_sparse_classes_30k_train_033598 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): Input intends to replace the value, not adding the value. However, this function adds the value, not r... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): Input intends to replace the value, not adding the value. However, this function adds the value, not r... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""Input intends to replace the value, not adding the value. However, this function adds the value, not replacing it in the Fenwick tree. :type i: int :type val: int ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.N = len(nums) + 1
self.tree = [0] * self.N
self.nums = nums
self.init = True
for idx, val in enumerate(nums):
self.update(idx, val * 2)
self.init = False
def update(sel... | the_stack_v2_python_sparse | binary_index_tree/307_Range_Sum_Query.py | vsdrun/lc_public | train | 6 | |
4fd20b1408c0bab70cef4d26f58b1ca77e91bfe5 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"item = Inventory.return_as_dictionary(self)\nitem['Brand'] = self.brand\nitem['Voltage'] = self.voltage\nreturn item"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
item = Inventory.return_as_dictionary(self)
item['Brand'] = self.brand
item['Voltage'] = self.voltag... | The ElectricAppliances class | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
"""Function ... | stack_v2_sparse_classes_75kplus_train_004692 | 774 | no_license | [
{
"docstring": "Creates common instance variables from the parent class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, brand, voltage)"
},
{
"docstring": "Function to return appliance as a dictionary",
"name": "return_as_dictiona... | 2 | stack_v2_sparse_classes_30k_train_000168 | Implement the Python class `ElectricAppliances` described below.
Class description:
The ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class
- def return_as_dictio... | Implement the Python class `ElectricAppliances` described below.
Class description:
The ElectricAppliances class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Creates common instance variables from the parent class
- def return_as_dictio... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
"""Function ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElectricAppliances:
"""The ElectricAppliances class"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Creates common instance variables from the parent class"""
Inventory.__init__(self, product_code, description, market_price, rental_price)
... | the_stack_v2_python_sparse | students/JoeNunnelley/lesson01/assignment/inventory_management/electric_appliances.py | JavaRod/SP_Python220B_2019 | train | 1 |
4233974e2ab6706479a2105d5218ab58343b866e | [
"self.settings = None\nself.options = None\nself._sLabel = 'SETTINGS'\nself._oLabel = 'OPTIONS'\nself.set(settings, options)",
"config = ConfigParser()\nconfig.read(iniFile, encoding='utf-8')\nif config.has_section(self._sLabel):\n section = config[self._sLabel]\n for setting in self.settings:\n fall... | <|body_start_0|>
self.settings = None
self.options = None
self._sLabel = 'SETTINGS'
self._oLabel = 'OPTIONS'
self.set(settings, options)
<|end_body_0|>
<|body_start_1|>
config = ConfigParser()
config.read(iniFile, encoding='utf-8')
if config.has_section(s... | Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire configuration without writing the INI file. write(iniFile) -- save the configuration... | Configuration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire configuration without writing the INI file.... | stack_v2_sparse_classes_75kplus_train_004693 | 3,445 | permissive | [
{
"docstring": "Initalize attribute variables. Optional arguments: settings -- default settings (dictionary of strings) options -- default options (dictionary of boolean values)",
"name": "__init__",
"signature": "def __init__(self, settings={}, options={})"
},
{
"docstring": "Read a configurati... | 4 | stack_v2_sparse_classes_30k_train_002278 | Implement the Python class `Configuration` described below.
Class description:
Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire conf... | Implement the Python class `Configuration` described below.
Class description:
Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire conf... | 33a868daed653c3371f5991d243a034668a80884 | <|skeleton|>
class Configuration:
"""Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire configuration without writing the INI file.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Configuration:
"""Application configuration, representing an INI file. INI file sections: <self._sLabel> - Strings <self._oLabel> - Boolean values Public methods: read(iniFile) -- read a configuration file. set(settings={}, options={}) -- set the entire configuration without writing the INI file. write(iniFil... | the_stack_v2_python_sparse | src/pywriter/config/configuration.py | peter88213/PyWriter | train | 3 |
f168b53ce6f63da62f68753b3d1077739c775b81 | [
"LOG.info('initializing histogram')\nself.timestr = None\nself.x = robjects.FloatVector(inputlist)",
"directory = outdir + '/histogram/'\nLOG.info('checking if directory exists')\nif not os.path.exists(directory):\n LOG.info('%s does not exist so create directory', directory)\n os.makedirs(directory)\nretur... | <|body_start_0|>
LOG.info('initializing histogram')
self.timestr = None
self.x = robjects.FloatVector(inputlist)
<|end_body_0|>
<|body_start_1|>
directory = outdir + '/histogram/'
LOG.info('checking if directory exists')
if not os.path.exists(directory):
LOG.... | Histogram class to plot Histograms | Histogram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
<|body_0|>
def _check_dir(self, outdir):
"""Will check that outputdir exists"""
<|body_1|>
def _create_file(self, outdir):
... | stack_v2_sparse_classes_75kplus_train_004694 | 1,673 | no_license | [
{
"docstring": "constructor takes the data to plot",
"name": "__init__",
"signature": "def __init__(self, inputlist)"
},
{
"docstring": "Will check that outputdir exists",
"name": "_check_dir",
"signature": "def _check_dir(self, outdir)"
},
{
"docstring": "Will create file with s... | 4 | stack_v2_sparse_classes_30k_train_053454 | Implement the Python class `Histogram` described below.
Class description:
Histogram class to plot Histograms
Method signatures and docstrings:
- def __init__(self, inputlist): constructor takes the data to plot
- def _check_dir(self, outdir): Will check that outputdir exists
- def _create_file(self, outdir): Will cr... | Implement the Python class `Histogram` described below.
Class description:
Histogram class to plot Histograms
Method signatures and docstrings:
- def __init__(self, inputlist): constructor takes the data to plot
- def _check_dir(self, outdir): Will check that outputdir exists
- def _create_file(self, outdir): Will cr... | 73beebe994a7eb69985d5b56d677796e0c225cd6 | <|skeleton|>
class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
<|body_0|>
def _check_dir(self, outdir):
"""Will check that outputdir exists"""
<|body_1|>
def _create_file(self, outdir):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
LOG.info('initializing histogram')
self.timestr = None
self.x = robjects.FloatVector(inputlist)
def _check_dir(self, outdir):
"""Will ch... | the_stack_v2_python_sparse | core/plots/histogram.py | chesarin/master-thesis | train | 3 |
82bb39dbb7391161dd61f37312a2e56b4923b0f9 | [
"email = self.request.get('email')\npassword = self.request.get('password')\nif self.dstore.is_user_cloud_admin():\n success, message = self.helper.change_password(cgi.escape(email), cgi.escape(password))\nelse:\n success = False\n message = 'Only the cloud administrator can change passwords.'\nflash_messa... | <|body_start_0|>
email = self.request.get('email')
password = self.request.get('password')
if self.dstore.is_user_cloud_admin():
success, message = self.helper.change_password(cgi.escape(email), cgi.escape(password))
else:
success = False
message = 'On... | Class to handle user password changes. | ChangePasswordPage | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangePasswordPage:
"""Class to handle user password changes."""
def post(self):
"""Handler for POST requests."""
<|body_0|>
def get(self):
"""Handler for GET requests."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email = self.request.get('em... | stack_v2_sparse_classes_75kplus_train_004695 | 37,207 | permissive | [
{
"docstring": "Handler for POST requests.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Handler for GET requests.",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013643 | Implement the Python class `ChangePasswordPage` described below.
Class description:
Class to handle user password changes.
Method signatures and docstrings:
- def post(self): Handler for POST requests.
- def get(self): Handler for GET requests. | Implement the Python class `ChangePasswordPage` described below.
Class description:
Class to handle user password changes.
Method signatures and docstrings:
- def post(self): Handler for POST requests.
- def get(self): Handler for GET requests.
<|skeleton|>
class ChangePasswordPage:
"""Class to handle user passw... | aa36e8dfaa295d53bec616ed07f91ec8c02fa4e1 | <|skeleton|>
class ChangePasswordPage:
"""Class to handle user password changes."""
def post(self):
"""Handler for POST requests."""
<|body_0|>
def get(self):
"""Handler for GET requests."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangePasswordPage:
"""Class to handle user password changes."""
def post(self):
"""Handler for POST requests."""
email = self.request.get('email')
password = self.request.get('password')
if self.dstore.is_user_cloud_admin():
success, message = self.helper.chan... | the_stack_v2_python_sparse | AppDashboard/dashboard.py | shatterednirvana/appscale | train | 6 |
b574c35b5bdd3724bdd91054f3c83f3b485a194b | [
"assert len(scheduler_list) > 0\nfor i in six.moves.range(len(scheduler_list) - 1):\n assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.'\nself.scheduler_list = scheduler_list\nself.cur_index = 0\nself.cur_step = 0\nself.cur_value = self.scheduler_list[0][1]\ns... | <|body_start_0|>
assert len(scheduler_list) > 0
for i in six.moves.range(len(scheduler_list) - 1):
assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.'
self.scheduler_list = scheduler_list
self.cur_index = 0
self.cur_... | Set hyper parameters by a predefined step-based scheduler. | PiecewiseScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
<|body_0|>
def step... | stack_v2_sparse_classes_75kplus_train_004696 | 3,280 | permissive | [
{
"docstring": "Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]",
"name": "__init__",
"signature": "def __init__(self, scheduler_list)"
},
{
"docstring": "Step step_num and fetch value according to following rule: Given... | 2 | stack_v2_sparse_classes_30k_train_004887 | Implement the Python class `PiecewiseScheduler` described below.
Class description:
Set hyper parameters by a predefined step-based scheduler.
Method signatures and docstrings:
- def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.0... | Implement the Python class `PiecewiseScheduler` described below.
Class description:
Set hyper parameters by a predefined step-based scheduler.
Method signatures and docstrings:
- def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.0... | 3bb5fe36d245f4d69bae0710dc1dc9d1a172f64d | <|skeleton|>
class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
<|body_0|>
def step... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
assert len(scheduler_list) > 0
... | the_stack_v2_python_sparse | parl/utils/scheduler.py | PaddlePaddle/PARL | train | 3,818 |
fcfa8741c846c2fd476e85ad1a2446adca5a3c43 | [
"if node is not self:\n self.vertices.add(node)\n node.vertices.add(self)",
"for vertex in self.vertices:\n vertex.vertices.discard(self)\ndel self.vertices"
] | <|body_start_0|>
if node is not self:
self.vertices.add(node)
node.vertices.add(self)
<|end_body_0|>
<|body_start_1|>
for vertex in self.vertices:
vertex.vertices.discard(self)
del self.vertices
<|end_body_1|>
| An internal graph node class for the proximity handler. | GraphNode | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphNode:
"""An internal graph node class for the proximity handler."""
def link(self, node):
"""Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex."""
<|body_0|>
def unlink(self):
"""Unlink this node fro... | stack_v2_sparse_classes_75kplus_train_004697 | 5,910 | permissive | [
{
"docstring": "Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex.",
"name": "link",
"signature": "def link(self, node)"
},
{
"docstring": "Unlink this node from the connected vertices.",
"name": "unlink",
"signature": "def unlin... | 2 | stack_v2_sparse_classes_30k_train_039146 | Implement the Python class `GraphNode` described below.
Class description:
An internal graph node class for the proximity handler.
Method signatures and docstrings:
- def link(self, node): Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex.
- def unlink(self):... | Implement the Python class `GraphNode` described below.
Class description:
An internal graph node class for the proximity handler.
Method signatures and docstrings:
- def link(self, node): Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex.
- def unlink(self):... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class GraphNode:
"""An internal graph node class for the proximity handler."""
def link(self, node):
"""Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex."""
<|body_0|>
def unlink(self):
"""Unlink this node fro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphNode:
"""An internal graph node class for the proximity handler."""
def link(self, node):
"""Link this node with another vertex. Parameters ---------- node : GraphNode The node to link with this vertex."""
if node is not self:
self.vertices.add(node)
node.vert... | the_stack_v2_python_sparse | enaml/qt/docking/proximity_handler.py | MatthieuDartiailh/enaml | train | 26 |
05e1df9282130d3685351c1df9950e98cebbfc02 | [
"holder = ''\nlongest = ''\nfor i, c in enumerate(s):\n hit = holder.find(c)\n if hit is -1:\n holder += c\n else:\n if len(holder) >= len(longest):\n longest = holder\n holder = holder[hit + 1:] + c\nreturn len(longest) if len(longest) > len(holder) else len(holder)",
"le... | <|body_start_0|>
holder = ''
longest = ''
for i, c in enumerate(s):
hit = holder.find(c)
if hit is -1:
holder += c
else:
if len(holder) >= len(longest):
longest = holder
holder = holder[hit + ... | LongestSubstring | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestSubstring:
def get_length_of_longest_substring(s: str):
""":type s: str :rtype: int"""
<|body_0|>
def get_length_of_longest_substring_hash(s: str):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
holder = ''
... | stack_v2_sparse_classes_75kplus_train_004698 | 1,358 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "get_length_of_longest_substring",
"signature": "def get_length_of_longest_substring(s: str)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "get_length_of_longest_substring_hash",
"signature": "def get_length_of_longest_substring... | 2 | stack_v2_sparse_classes_30k_train_042767 | Implement the Python class `LongestSubstring` described below.
Class description:
Implement the LongestSubstring class.
Method signatures and docstrings:
- def get_length_of_longest_substring(s: str): :type s: str :rtype: int
- def get_length_of_longest_substring_hash(s: str): :type s: str :rtype: int | Implement the Python class `LongestSubstring` described below.
Class description:
Implement the LongestSubstring class.
Method signatures and docstrings:
- def get_length_of_longest_substring(s: str): :type s: str :rtype: int
- def get_length_of_longest_substring_hash(s: str): :type s: str :rtype: int
<|skeleton|>
c... | 638a1312a66805fefb2a1e1dd7b4968d2c957564 | <|skeleton|>
class LongestSubstring:
def get_length_of_longest_substring(s: str):
""":type s: str :rtype: int"""
<|body_0|>
def get_length_of_longest_substring_hash(s: str):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LongestSubstring:
def get_length_of_longest_substring(s: str):
""":type s: str :rtype: int"""
holder = ''
longest = ''
for i, c in enumerate(s):
hit = holder.find(c)
if hit is -1:
holder += c
else:
if len(holde... | the_stack_v2_python_sparse | longest_substring.py | wotann07/leetcode_py | train | 0 | |
49fd90d458f875467cb13a2bde9413bd17bc4d73 | [
"self._rep = rep\nself._output_sizes = output_sizes\nself._type = att_type\nself._scale = scale\nself._normalise = normalise\nif self._type == 'multihead':\n self._num_heads = num_heads",
"if self._rep == 'identity':\n k, q = (x1, x2)\nelif self._rep == 'mlp':\n k = batch_mlp(x1, self._output_sizes, 'att... | <|body_start_0|>
self._rep = rep
self._output_sizes = output_sizes
self._type = att_type
self._scale = scale
self._normalise = normalise
if self._type == 'multihead':
self._num_heads = num_heads
<|end_body_0|>
<|body_start_1|>
if self._rep == 'identit... | The Attention module. | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representat... | stack_v2_sparse_classes_75kplus_train_004699 | 15,798 | permissive | [
{
"docstring": "Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the context data. Args: rep: transformation to apply to contexts before computing attention. One of: ['identity','mlp']. output_sizes: l... | 2 | stack_v2_sparse_classes_30k_train_024441 | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Create attention module. Takes in context inputs, target inputs and representations of each cont... | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Create attention module. Takes in context inputs, target inputs and representations of each cont... | ddd3e586b01ba3a7f8b3721582aca7403649400e | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the co... | the_stack_v2_python_sparse | backup/model.py | jsikyoon/ASNP-RMR | train | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.