blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6fd09fa7ea694559cd29a6634e08ec49b50dae70 | [
"turno = TurnoAula.objects.filter(diaDaSemana=dia, turno=turno_a, turma=self.turma)\nif turno:\n return turno[0]\nelse:\n turno = TurnoAula(turma=self.turma, horario=self, diaDaSemana=dia, turno=turno_a)\n turno.save()\n return turno",
"turno_aula = self.get_turno_aula_or_create(dia, Turno.get_turno_b... | <|body_start_0|>
turno = TurnoAula.objects.filter(diaDaSemana=dia, turno=turno_a, turma=self.turma)
if turno:
return turno[0]
else:
turno = TurnoAula(turma=self.turma, horario=self, diaDaSemana=dia, turno=turno_a)
turno.save()
return turno
<|end_bo... | O horario de uma turma. | Horario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Horario:
"""O horario de uma turma."""
def get_turno_aula_or_create(self, dia, turno_a):
"""Retorna um turno ou o cria"""
<|body_0|>
def get_periodo_or_create(self, dia, turno: int, num):
"""Retorna um periodo ou cria um novo"""
<|body_1|>
def get_ho... | stack_v2_sparse_classes_36k_train_022900 | 43,305 | permissive | [
{
"docstring": "Retorna um turno ou o cria",
"name": "get_turno_aula_or_create",
"signature": "def get_turno_aula_or_create(self, dia, turno_a)"
},
{
"docstring": "Retorna um periodo ou cria um novo",
"name": "get_periodo_or_create",
"signature": "def get_periodo_or_create(self, dia, tur... | 3 | stack_v2_sparse_classes_30k_train_007138 | Implement the Python class `Horario` described below.
Class description:
O horario de uma turma.
Method signatures and docstrings:
- def get_turno_aula_or_create(self, dia, turno_a): Retorna um turno ou o cria
- def get_periodo_or_create(self, dia, turno: int, num): Retorna um periodo ou cria um novo
- def get_horari... | Implement the Python class `Horario` described below.
Class description:
O horario de uma turma.
Method signatures and docstrings:
- def get_turno_aula_or_create(self, dia, turno_a): Retorna um turno ou o cria
- def get_periodo_or_create(self, dia, turno: int, num): Retorna um periodo ou cria um novo
- def get_horari... | 37cf33d05be8b0195b10845061ca893ba5e814dd | <|skeleton|>
class Horario:
"""O horario de uma turma."""
def get_turno_aula_or_create(self, dia, turno_a):
"""Retorna um turno ou o cria"""
<|body_0|>
def get_periodo_or_create(self, dia, turno: int, num):
"""Retorna um periodo ou cria um novo"""
<|body_1|>
def get_ho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Horario:
"""O horario de uma turma."""
def get_turno_aula_or_create(self, dia, turno_a):
"""Retorna um turno ou o cria"""
turno = TurnoAula.objects.filter(diaDaSemana=dia, turno=turno_a, turma=self.turma)
if turno:
return turno[0]
else:
turno = Turn... | the_stack_v2_python_sparse | escola/models.py | vini84200/medusa2 | train | 1 |
60be2d203683281ebdf384dd69fb0cd0ad8f0eb9 | [
"super(BiasEncodingLayer, self).__init__()\nself.session_bias = nn.Parameter(torch.Tensor(max_num_session, 1, 1))\nself.position_bias = nn.Parameter(torch.Tensor(1, max_num_position, 1))\nself.item_bias = nn.Parameter(torch.Tensor(1, 1, embed_size))\nnn.init.normal_(self.session_bias)\nnn.init.normal_(self.position... | <|body_start_0|>
super(BiasEncodingLayer, self).__init__()
self.session_bias = nn.Parameter(torch.Tensor(max_num_session, 1, 1))
self.position_bias = nn.Parameter(torch.Tensor(1, max_num_position, 1))
self.item_bias = nn.Parameter(torch.Tensor(1, 1, embed_size))
nn.init.normal_(s... | Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bias of position in the session and bias of index in the session. :Reference: #. `Yufe... | BiasEncodingLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiasEncodingLayer:
"""Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bias of position in the session and bias ... | stack_v2_sparse_classes_36k_train_022901 | 3,342 | permissive | [
{
"docstring": "Initialize BiasEncodingLayer Args: embed_size (int): Size of embedding tensor max_num_session (int): Maximum number of session in sequences. max_num_position (int): Maximum number of position in sessions. Attributes: session_bias (nn.Parameter): Bias variable of session in sequence. position_bia... | 2 | stack_v2_sparse_classes_30k_train_018238 | Implement the Python class `BiasEncodingLayer` described below.
Class description:
Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bi... | Implement the Python class `BiasEncodingLayer` described below.
Class description:
Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bi... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class BiasEncodingLayer:
"""Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bias of position in the session and bias ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiasEncodingLayer:
"""Layer class of Bias Encoding Bias Encoding was used in Deep Session Interest Network :title:`Yufei Feng et al, 2019`[1], which is to add three types of session-positional bias to session embedding tensors, including: bias of session, bias of position in the session and bias of index in t... | the_stack_v2_python_sparse | torecsys/layers/ctr/bias_encoding.py | zwcdp/torecsys | train | 0 |
353b324f1358d7589b32a1f0794db731ad197292 | [
"self.tolerance = tolerance\nself.mz_power = mz_power\nself.intensity_power = intensity_power",
"def get_matching_pairs():\n \"\"\"Get pairs of peaks that match within the given tolerance.\"\"\"\n matching_pairs = collect_peak_pairs(spec1, spec2, self.tolerance, shift=0.0, mz_power=self.mz_power, intensity_... | <|body_start_0|>
self.tolerance = tolerance
self.mz_power = mz_power
self.intensity_power = intensity_power
<|end_body_0|>
<|body_start_1|>
def get_matching_pairs():
"""Get pairs of peaks that match within the given tolerance."""
matching_pairs = collect_peak_pai... | Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are considered a potential match if their m/z ratios lie within the given 'tolerance'. T... | CosineGreedy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CosineGreedy:
"""Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are considered a potential match if their m/z ra... | stack_v2_sparse_classes_36k_train_022902 | 4,099 | permissive | [
{
"docstring": "Parameters ---------- tolerance: Peaks will be considered a match when <= tolerance apart. Default is 0.1. mz_power: The power to raise m/z to in the cosine function. The default is 0, in which case the peak intensity products will not depend on the m/z ratios. intensity_power: The power to rais... | 2 | null | Implement the Python class `CosineGreedy` described below.
Class description:
Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are consi... | Implement the Python class `CosineGreedy` described below.
Class description:
Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are consi... | a161325b2edfa35e2a6f3fb2de30e1de171ba676 | <|skeleton|>
class CosineGreedy:
"""Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are considered a potential match if their m/z ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CosineGreedy:
"""Calculate 'cosine similarity score' between two spectra. The cosine score aims at quantifying the similarity between two mass spectra. The score is calculated by finding best possible matches between peaks of two spectra. Two peaks are considered a potential match if their m/z ratios lie with... | the_stack_v2_python_sparse | matchms/similarity/CosineGreedy.py | matchms/matchms | train | 140 |
55988b6452cce8ae583693422da84c005bfab4ba | [
"sig_generator.__init__(self, make_signal)\nself.master_pattern = ''.join(map(str, pattern))\nself.t_start, self.t_stop = (t_start, t_stop)",
"N_mastersymbols = len(self.master_pattern)\nT_symbol = (self.t_stop - self.t_start) / float(N_mastersymbols)\nN0 = int((time[0] - self.t_start) / T_symbol) % N_mastersymbo... | <|body_start_0|>
sig_generator.__init__(self, make_signal)
self.master_pattern = ''.join(map(str, pattern))
self.t_start, self.t_stop = (t_start, t_stop)
<|end_body_0|>
<|body_start_1|>
N_mastersymbols = len(self.master_pattern)
T_symbol = (self.t_stop - self.t_start) / float(N_... | A stateless generator to produce signals in blocks | pat_generator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pat_generator:
"""A stateless generator to produce signals in blocks"""
def __init__(self, make_signal, pattern, t_start=None, t_stop=None):
"""@param make_signal: a function to generate the signal time series, like lambda time,pattern: time_series_amplitude with t_sample: time serie... | stack_v2_sparse_classes_36k_train_022903 | 42,100 | permissive | [
{
"docstring": "@param make_signal: a function to generate the signal time series, like lambda time,pattern: time_series_amplitude with t_sample: time series for which to generate the signal [sec]. @param pattern: either a string representing the sequence of discrete symbols, or an array which can be trivially ... | 2 | stack_v2_sparse_classes_30k_train_015735 | Implement the Python class `pat_generator` described below.
Class description:
A stateless generator to produce signals in blocks
Method signatures and docstrings:
- def __init__(self, make_signal, pattern, t_start=None, t_stop=None): @param make_signal: a function to generate the signal time series, like lambda time... | Implement the Python class `pat_generator` described below.
Class description:
A stateless generator to produce signals in blocks
Method signatures and docstrings:
- def __init__(self, make_signal, pattern, t_start=None, t_stop=None): @param make_signal: a function to generate the signal time series, like lambda time... | 7f8e76b1a82238e148da73dea27db46b2824e711 | <|skeleton|>
class pat_generator:
"""A stateless generator to produce signals in blocks"""
def __init__(self, make_signal, pattern, t_start=None, t_stop=None):
"""@param make_signal: a function to generate the signal time series, like lambda time,pattern: time_series_amplitude with t_sample: time serie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pat_generator:
"""A stateless generator to produce signals in blocks"""
def __init__(self, make_signal, pattern, t_start=None, t_stop=None):
"""@param make_signal: a function to generate the signal time series, like lambda time,pattern: time_series_amplitude with t_sample: time series for which t... | the_stack_v2_python_sparse | rfiLib/siggen_aph.py | ska-telescope/ska-rfi-monitoring-processing | train | 1 |
2fec4ee9ce3ded47e52c00c37b63a97f8cc07fe4 | [
"from .search import AsyncSearch\ns = AsyncSearch(client=self, index_name=index_name)\nreturn s",
"from .graph import AsyncGraph\ng = AsyncGraph(client=self, name=index_name)\nreturn g"
] | <|body_start_0|>
from .search import AsyncSearch
s = AsyncSearch(client=self, index_name=index_name)
return s
<|end_body_0|>
<|body_start_1|>
from .graph import AsyncGraph
g = AsyncGraph(client=self, name=index_name)
return g
<|end_body_1|>
| AsyncRedisModuleCommands | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncRedisModuleCommands:
def ft(self, index_name='idx'):
"""Access the search namespace, providing support for redis search."""
<|body_0|>
def graph(self, index_name='idx'):
"""Access the graph namespace, providing support for redis graph data."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_022904 | 2,454 | permissive | [
{
"docstring": "Access the search namespace, providing support for redis search.",
"name": "ft",
"signature": "def ft(self, index_name='idx')"
},
{
"docstring": "Access the graph namespace, providing support for redis graph data.",
"name": "graph",
"signature": "def graph(self, index_nam... | 2 | null | Implement the Python class `AsyncRedisModuleCommands` described below.
Class description:
Implement the AsyncRedisModuleCommands class.
Method signatures and docstrings:
- def ft(self, index_name='idx'): Access the search namespace, providing support for redis search.
- def graph(self, index_name='idx'): Access the g... | Implement the Python class `AsyncRedisModuleCommands` described below.
Class description:
Implement the AsyncRedisModuleCommands class.
Method signatures and docstrings:
- def ft(self, index_name='idx'): Access the search namespace, providing support for redis search.
- def graph(self, index_name='idx'): Access the g... | e3de026a90ef2cc35a5b68934029a0ef2a5b2f53 | <|skeleton|>
class AsyncRedisModuleCommands:
def ft(self, index_name='idx'):
"""Access the search namespace, providing support for redis search."""
<|body_0|>
def graph(self, index_name='idx'):
"""Access the graph namespace, providing support for redis graph data."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncRedisModuleCommands:
def ft(self, index_name='idx'):
"""Access the search namespace, providing support for redis search."""
from .search import AsyncSearch
s = AsyncSearch(client=self, index_name=index_name)
return s
def graph(self, index_name='idx'):
"""Acces... | the_stack_v2_python_sparse | redis/commands/redismodules.py | redis/redis-py | train | 2,213 | |
e2f8e186dd4e84c355fece22dfbccc7e0d81834a | [
"self.is_categorical = is_categorical\nself.is_binary = len(unique_values) == 2\nself.unique_values = unique_values\nif not is_categorical and (not self.is_binary):\n self.unique_values = self.__get_stdev_band(unique_values)",
"mean = stats.mean(unique_values)\nstdev = stats.stdev(unique_values)\nreturn [mean ... | <|body_start_0|>
self.is_categorical = is_categorical
self.is_binary = len(unique_values) == 2
self.unique_values = unique_values
if not is_categorical and (not self.is_binary):
self.unique_values = self.__get_stdev_band(unique_values)
<|end_body_0|>
<|body_start_1|>
... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, unique_values, is_categorical):
"""Constructor of an Encoder using one-hot-encoding"""
<|body_0|>
def __get_stdev_band(self, unique_values):
"""Get the lower bound and upper bound for the standard devaitation band for continuous value."""
... | stack_v2_sparse_classes_36k_train_022905 | 1,683 | no_license | [
{
"docstring": "Constructor of an Encoder using one-hot-encoding",
"name": "__init__",
"signature": "def __init__(self, unique_values, is_categorical)"
},
{
"docstring": "Get the lower bound and upper bound for the standard devaitation band for continuous value.",
"name": "__get_stdev_band",... | 3 | stack_v2_sparse_classes_30k_test_001059 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, unique_values, is_categorical): Constructor of an Encoder using one-hot-encoding
- def __get_stdev_band(self, unique_values): Get the lower bound and upper bound... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, unique_values, is_categorical): Constructor of an Encoder using one-hot-encoding
- def __get_stdev_band(self, unique_values): Get the lower bound and upper bound... | 9ae339f81fc7134ba9058fe975dec9ac7e3aaba4 | <|skeleton|>
class Encoder:
def __init__(self, unique_values, is_categorical):
"""Constructor of an Encoder using one-hot-encoding"""
<|body_0|>
def __get_stdev_band(self, unique_values):
"""Get the lower bound and upper bound for the standard devaitation band for continuous value."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, unique_values, is_categorical):
"""Constructor of an Encoder using one-hot-encoding"""
self.is_categorical = is_categorical
self.is_binary = len(unique_values) == 2
self.unique_values = unique_values
if not is_categorical and (not self.is_bin... | the_stack_v2_python_sparse | Project5/encoding.py | vincy0320/School_Intro_to_ML | train | 0 | |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries\nself.frequencies = frequencies\nself.fraction = fraction",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nself.fracs = self.R.uniform(low=self.fraction[0], high=self.fraction[... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.boundaries = boundaries
self.frequencies = frequencies
self.fraction = fraction
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high... | Add a random partial sinusoidal signal to the input signal | SignalRandAddSinePartial | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower a... | stack_v2_sparse_classes_36k_train_022906 | 16,322 | permissive | [
{
"docstring": "Args: boundaries: list defining lower and upper boundaries for the sinusoidal magnitude, lower and upper values need to be positive , default : ``[0.1, 0.3]`` frequencies: list defining lower and upper frequencies for sinusoidal signal generation , default : ``[0.001, 0.02]`` fraction: list defi... | 2 | stack_v2_sparse_classes_30k_train_015284 | Implement the Python class `SignalRandAddSinePartial` described below.
Class description:
Add a random partial sinusoidal signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.0... | Implement the Python class `SignalRandAddSinePartial` described below.
Class description:
Add a random partial sinusoidal signal to the input signal
Method signatures and docstrings:
- def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.0... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalRandAddSinePartial:
"""Add a random partial sinusoidal signal to the input signal"""
def __init__(self, boundaries: Sequence[float]=(0.1, 0.3), frequencies: Sequence[float]=(0.001, 0.02), fraction: Sequence[float]=(0.01, 0.2)) -> None:
"""Args: boundaries: list defining lower and upper boun... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
ba6b8187fa93116736a47385fd020fa07a4d7739 | [
"mat = [[1] * N for _ in range(N)]\nfor i, j in mines:\n mat[i][j] = 0\nif not mat:\n return 0\nleftup = [[(0, 0)] * N for _ in range(N)]\nfor i in range(N):\n for j in range(N):\n e = mat[i][j]\n toleft = leftup[i][j - 1][0] * e + e\n toup = leftup[i - 1][j][1] * e + e\n leftup... | <|body_start_0|>
mat = [[1] * N for _ in range(N)]
for i, j in mines:
mat[i][j] = 0
if not mat:
return 0
leftup = [[(0, 0)] * N for _ in range(N)]
for i in range(N):
for j in range(N):
e = mat[i][j]
toleft = left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
"""09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)"""
<|body_0|>
def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k_train_022907 | 3,829 | no_license | [
{
"docstring": "09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)",
"name": "orderOfLargestPlusSign",
"signature": "def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int"
},
{
"docstring": "Horizontal and vertical line sweep Time comp... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int: 09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)
- def order... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int: 09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)
- def order... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
"""09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)"""
<|body_0|>
def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
"""09/10/2020 01:12 Top left and bottom right DP Time complexity: O(n^2) Time complexity: O(n^2)"""
mat = [[1] * N for _ in range(N)]
for i, j in mines:
mat[i][j] = 0
if not mat:
... | the_stack_v2_python_sparse | leetcode/solved/769_Largest_Plus_Sign/solution.py | sungminoh/algorithms | train | 0 | |
7cdd86c2bece49bc689dbbfe70c2c4b398aedee1 | [
"self._phrase_vocabulary = set((phrase.lower() for phrase in phrase_vocabulary))\nself._do_swap = do_swap\nself._max_added_phrase_length = 0\nself._token_vocabulary = set()\nfor phrase in self._phrase_vocabulary:\n tokens = phrase.split()\n self._token_vocabulary |= set(tokens)\n if len(tokens) > self._max... | <|body_start_0|>
self._phrase_vocabulary = set((phrase.lower() for phrase in phrase_vocabulary))
self._do_swap = do_swap
self._max_added_phrase_length = 0
self._token_vocabulary = set()
for phrase in self._phrase_vocabulary:
tokens = phrase.split()
self._t... | Converter from training target texts into tagging format. | TaggingConverter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaggingConverter:
"""Converter from training target texts into tagging format."""
def __init__(self, phrase_vocabulary, do_swap=False):
"""Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase vocabulary items (strings). do_swap: Whether to enable t... | stack_v2_sparse_classes_36k_train_022908 | 8,003 | permissive | [
{
"docstring": "Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase vocabulary items (strings). do_swap: Whether to enable the SWAP tag.",
"name": "__init__",
"signature": "def __init__(self, phrase_vocabulary, do_swap=False)"
},
{
"docstring": "Computes tags... | 5 | stack_v2_sparse_classes_30k_train_014414 | Implement the Python class `TaggingConverter` described below.
Class description:
Converter from training target texts into tagging format.
Method signatures and docstrings:
- def __init__(self, phrase_vocabulary, do_swap=False): Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase... | Implement the Python class `TaggingConverter` described below.
Class description:
Converter from training target texts into tagging format.
Method signatures and docstrings:
- def __init__(self, phrase_vocabulary, do_swap=False): Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase... | ce1e002bf9d026c10fbd2c178d454ebb76cb7a94 | <|skeleton|>
class TaggingConverter:
"""Converter from training target texts into tagging format."""
def __init__(self, phrase_vocabulary, do_swap=False):
"""Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase vocabulary items (strings). do_swap: Whether to enable t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaggingConverter:
"""Converter from training target texts into tagging format."""
def __init__(self, phrase_vocabulary, do_swap=False):
"""Initializes an instance of TaggingConverter. Args: phrase_vocabulary: Iterable of phrase vocabulary items (strings). do_swap: Whether to enable the SWAP tag."... | the_stack_v2_python_sparse | DataCreation/LaserTagger/tagging_converter.py | tech-srl/c3po | train | 25 |
039c6622f853c67c0b637c34f4ff07e853015901 | [
"try:\n with open(primary_config_file, 'r') as f:\n self.primary_config = json.load(f)\nexcept Exception as e:\n raise Exception('Error reading primary config file: {}. Run reset.py script to reinitialize configs'.format(primary_config_file))\ntry:\n with open(secondary_config_file, 'r') as f:\n ... | <|body_start_0|>
try:
with open(primary_config_file, 'r') as f:
self.primary_config = json.load(f)
except Exception as e:
raise Exception('Error reading primary config file: {}. Run reset.py script to reinitialize configs'.format(primary_config_file))
try:... | Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments | ConfigReader | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"WTFPL",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigReader:
"""Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments"""
def __init__(self, primary_config_file, secondary_con... | stack_v2_sparse_classes_36k_train_022909 | 3,982 | permissive | [
{
"docstring": "Constructor :param primary_config_file: str , path to primary config file :param secondary_config_file: str , path to secondary config file",
"name": "__init__",
"signature": "def __init__(self, primary_config_file, secondary_config_file)"
},
{
"docstring": "Overrides the config ... | 3 | stack_v2_sparse_classes_30k_train_000565 | Implement the Python class `ConfigReader` described below.
Class description:
Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments
Method signatures and... | Implement the Python class `ConfigReader` described below.
Class description:
Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments
Method signatures and... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ConfigReader:
"""Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments"""
def __init__(self, primary_config_file, secondary_con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigReader:
"""Reads the config files and supports requested values from the user Methods: get_config_value: returns the value of the config key override_with_command_line_args: overrides the config values with command line arguments"""
def __init__(self, primary_config_file, secondary_config_file):
... | the_stack_v2_python_sparse | govern/data-security/ranger/ranger-tools/src/main/python/ranger_performance_tool/ranger_perf_utils/config_utils.py | alldatacenter/alldata | train | 774 |
551069db97d0a25bc911126cef3481d39bf1fccb | [
"self.id = id\nself.title = title\nself.delegate = delegate_path",
"uf = getattr(aq_base(self), 'acl_users', None)\nif uf is None and self.delegate:\n uf = self.unrestrictedTraverse(self.delegate)\nreturn uf",
"acl = self._getDelegate()\nif acl is None:\n return ()\nreturn acl.searchUsers(id=id, login=log... | <|body_start_0|>
self.id = id
self.title = title
self.delegate = delegate_path
<|end_body_0|>
<|body_start_1|>
uf = getattr(aq_base(self), 'acl_users', None)
if uf is None and self.delegate:
uf = self.unrestrictedTraverse(self.delegate)
return uf
<|end_body_1... | SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object | SearchPrincipalsPlugin | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchPrincipalsPlugin:
"""SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object"""
def __init__(self, id, title='', delegate_path=''):
"""Initialize a new instance"""
<|body_0|>
def _getDelegate(self):
"""Safely ret... | stack_v2_sparse_classes_36k_train_022910 | 3,727 | permissive | [
{
"docstring": "Initialize a new instance",
"name": "__init__",
"signature": "def __init__(self, id, title='', delegate_path='')"
},
{
"docstring": "Safely retrieve a PluggableAuthService to work with",
"name": "_getDelegate",
"signature": "def _getDelegate(self)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_015162 | Implement the Python class `SearchPrincipalsPlugin` described below.
Class description:
SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object
Method signatures and docstrings:
- def __init__(self, id, title='', delegate_path=''): Initialize a new instance
- def _getDeleg... | Implement the Python class `SearchPrincipalsPlugin` described below.
Class description:
SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object
Method signatures and docstrings:
- def __init__(self, id, title='', delegate_path=''): Initialize a new instance
- def _getDeleg... | f0fde29f4c865a4e0908d22c19a0a72810b0a24f | <|skeleton|>
class SearchPrincipalsPlugin:
"""SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object"""
def __init__(self, id, title='', delegate_path=''):
"""Initialize a new instance"""
<|body_0|>
def _getDelegate(self):
"""Safely ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchPrincipalsPlugin:
"""SearchPrincipalsPlugin delegates its enumerateUsers and enumerateGroups methods to a delegate object"""
def __init__(self, id, title='', delegate_path=''):
"""Initialize a new instance"""
self.id = id
self.title = title
self.delegate = delegate_p... | the_stack_v2_python_sparse | src/Products/PluggableAuthService/plugins/SearchPrincipalsPlugin.py | zopefoundation/Products.PluggableAuthService | train | 8 |
d1e5836b5759bfd33b8cf61fe35951e782072722 | [
"if query and query not in force_text(field.field_name).lower():\n return False\nelse:\n return True",
"if self.field_types and field.field_type not in self.field_types:\n return False\nelse:\n return self._query_is_match(field, query)"
] | <|body_start_0|>
if query and query not in force_text(field.field_name).lower():
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.field_types and field.field_type not in self.field_types:
return False
else:
return sel... | Defines autocomplete rules for source on the Container admin page. | FilterFieldsAutocompleteBase | [
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
<|b... | stack_v2_sparse_classes_36k_train_022911 | 6,425 | permissive | [
{
"docstring": "Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string.",
"name": "_query_is_match",
"signature": "def _query_is_match(field, query)"
},
{
"docstring": "Takes a DataField and a query string. Returns a Boolea... | 2 | stack_v2_sparse_classes_30k_test_000509 | Implement the Python class `FilterFieldsAutocompleteBase` described below.
Class description:
Defines autocomplete rules for source on the Container admin page.
Method signatures and docstrings:
- def _query_is_match(field, query): Takes a DataField and a query string. Returns a Boolean indicating whether the DataFie... | Implement the Python class `FilterFieldsAutocompleteBase` described below.
Class description:
Defines autocomplete rules for source on the Container admin page.
Method signatures and docstrings:
- def _query_is_match(field, query): Takes a DataField and a query string. Returns a Boolean indicating whether the DataFie... | a379a134c0c5af14df4ed2afa066c1626506b754 | <|skeleton|>
class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterFieldsAutocompleteBase:
"""Defines autocomplete rules for source on the Container admin page."""
def _query_is_match(field, query):
"""Takes a DataField and a query string. Returns a Boolean indicating whether the DataField's field_name contains the query string."""
if query and que... | the_stack_v2_python_sparse | Incident-Response/Tools/cyphon/cyphon/bottler/tastes/autocomplete_light_registry.py | foss2cyber/Incident-Playbook | train | 1 |
6aa2408d55e4ec4f16425b0a398b320c73b2180b | [
"super().__init__(model)\nself.data = shap.kmeans(data, 25)\nself.explainer = shap.KernelExplainer(self.model, self.data, link=link)",
"shap_vals = self.explainer.shap_values(data_x[0], nsamples=10000, silent=True)\nif len(shap_vals) > 1:\n shap_value_at_label = shap_vals[label]\n final_shap_values = torch.... | <|body_start_0|>
super().__init__(model)
self.data = shap.kmeans(data, 25)
self.explainer = shap.KernelExplainer(self.model, self.data, link=link)
<|end_body_0|>
<|body_start_1|>
shap_vals = self.explainer.shap_values(data_x[0], nsamples=10000, silent=True)
if len(shap_vals) > 1... | The SHAP explainer | SHAPExplainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
<|body_0|>
def get_explanation(self, data_x: np... | stack_v2_sparse_classes_36k_train_022912 | 1,864 | permissive | [
{
"docstring": "Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'",
"name": "__init__",
"signature": "def __init__(self, model, data: torch.FloatTensor, link: str='identity')"
},
{
"docstring": "Gets the SHAP explanation. Returns SHAP values ... | 2 | stack_v2_sparse_classes_30k_train_005858 | Implement the Python class `SHAPExplainer` described below.
Class description:
The SHAP explainer
Method signatures and docstrings:
- def __init__(self, model, data: torch.FloatTensor, link: str='identity'): Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'
- def ... | Implement the Python class `SHAPExplainer` described below.
Class description:
The SHAP explainer
Method signatures and docstrings:
- def __init__(self, model, data: torch.FloatTensor, link: str='identity'): Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'
- def ... | 73612ebb3e72f4f8172380bab8c7ba941e70224b | <|skeleton|>
class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
<|body_0|>
def get_explanation(self, data_x: np... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SHAPExplainer:
"""The SHAP explainer"""
def __init__(self, model, data: torch.FloatTensor, link: str='identity'):
"""Init. Args: model: model object data: pandas data frame or numpy array link: str, 'identity' or 'logit'"""
super().__init__(model)
self.data = shap.kmeans(data, 25)... | the_stack_v2_python_sparse | explain/mega_explainer/shap_explainer.py | dylan-slack/TalkToModel | train | 84 |
64b52392b4c0491e895bcdf80544162cd0bfeaa9 | [
"super(Edge, self).__init__()\nself.input_model = 'rate'\nself.output_model = 'rate'",
"inputs = self.source.get_data(args)\nfoobar = lambda x: x\noutputs = foobar(inputs)\nargs = {'inputs': outputs, 'first_neuron': self.postFirst, 'last': self.postLast}\nself.target.set_data(args)"
] | <|body_start_0|>
super(Edge, self).__init__()
self.input_model = 'rate'
self.output_model = 'rate'
<|end_body_0|>
<|body_start_1|>
inputs = self.source.get_data(args)
foobar = lambda x: x
outputs = foobar(inputs)
args = {'inputs': outputs, 'first_neuron': self.po... | This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes that this edge is linking. | BrainStudioBEClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes tha... | stack_v2_sparse_classes_36k_train_022913 | 1,675 | no_license | [
{
"docstring": "This method acts as a constructor and is run every time an edge of this type is instantiated.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method transfers the data from the source node to the target. The data must be fetched and delivered using... | 2 | null | Implement the Python class `BrainStudioBEClass` described below.
Class description:
This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.tar... | Implement the Python class `BrainStudioBEClass` described below.
Class description:
This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.tar... | 37f18e5d652fcea9e7891b9401d3af84abc819e6 | <|skeleton|>
class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrainStudioBEClass:
"""This is a base class to illustrate how to add a new type of edge to BrainStudio. Follow the indications along this file and implement all specified methods and members. All edges have two very important fields, self.source and self.target, that store the ID of the nodes that this edge i... | the_stack_v2_python_sparse | backend/BrainStudioBECore/Edges/EdgeTemplate.py | brainstudio-team/BrainStudio | train | 9 |
c68e0d1d68fe9ae72cc4539b93bb6b6d35ac49e1 | [
"self.cluster_partition_id = cluster_partition_id\nself.job_id = job_id\nself.job_name = job_name\nself.job_uid = job_uid\nself.object_name = object_name\nself.os_type = os_type\nself.registered_source = registered_source\nself.snapshotted_source = snapshotted_source\nself.versions = versions\nself.view_box_id = vi... | <|body_start_0|>
self.cluster_partition_id = cluster_partition_id
self.job_id = job_id
self.job_name = job_name
self.job_uid = job_uid
self.object_name = object_name
self.os_type = os_type
self.registered_source = registered_source
self.snapshotted_source ... | Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_id (long|int): Specifies the id for the Protection Job that is currently associated w... | ObjectSnapshotInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectSnapshotInfo:
"""Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_id (long|int): Specifies the id for the... | stack_v2_sparse_classes_36k_train_022914 | 6,352 | permissive | [
{
"docstring": "Constructor for the ObjectSnapshotInfo class",
"name": "__init__",
"signature": "def __init__(self, cluster_partition_id=None, job_id=None, job_name=None, job_uid=None, object_name=None, os_type=None, registered_source=None, snapshotted_source=None, versions=None, view_box_id=None, view_... | 2 | stack_v2_sparse_classes_30k_train_010518 | Implement the Python class `ObjectSnapshotInfo` described below.
Class description:
Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_... | Implement the Python class `ObjectSnapshotInfo` described below.
Class description:
Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ObjectSnapshotInfo:
"""Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_id (long|int): Specifies the id for the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectSnapshotInfo:
"""Implementation of the 'ObjectSnapshotInfo' model. Specifies information about an object that has been backed up. Attributes: cluster_partition_id (long|int): Specifies the Cohesity Cluster partition id where this object is stored. job_id (long|int): Specifies the id for the Protection J... | the_stack_v2_python_sparse | cohesity_management_sdk/models/object_snapshot_info.py | cohesity/management-sdk-python | train | 24 |
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4 | [
"if nmax < 0:\n raise ValueError('nmax must be >= 0')\nsuper().__init__(self._Rr, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)\nself.nmax = nmax\nself.ell = ell\nself.d = d\nself.alpha = alpha\nreturn",
"nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif out is None:\n base_shape = X.shape[1:]\n out = np.... | <|body_start_0|>
if nmax < 0:
raise ValueError('nmax must be >= 0')
super().__init__(self._Rr, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)
self.nmax = nmax
self.ell = ell
self.d = d
self.alpha = alpha
return
<|end_body_0|>
<|body_start_1|>
... | Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\ell L_n^{(\\ell + d/2 - 1)} (\\alpha r^2) Attributes ---------- nmax : int Th... | RadialHO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadialHO:
"""Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\ell L_n^{(\\ell + d/2 - 1)} (\\alpha r^2)... | stack_v2_sparse_classes_36k_train_022915 | 39,055 | permissive | [
{
"docstring": "Create radial harmonic oscillator wavefunctions. Parameters ---------- nmax : int The maximum Laguerre index. ell : int The generalized angular momentum quantum number. d : int, optional The dimensionality. The default is 2. alpha : float, optional The radial scaling parameter, :math:`\\\\alpha`... | 2 | stack_v2_sparse_classes_30k_train_021652 | Implement the Python class `RadialHO` described below.
Class description:
Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\el... | Implement the Python class `RadialHO` described below.
Class description:
Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\el... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class RadialHO:
"""Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\ell L_n^{(\\ell + d/2 - 1)} (\\alpha r^2)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RadialHO:
"""Radial eigenfunctions for a :math:`d`-dimensional isotropic harmonic oscillator. .. math:: R_n^{(\\ell)}(r) = (-1)^n \\alpha^{d/4} \\left[ \\frac{2 \\Gamma(n+1) } {\\Gamma(n+\\ell + d/2)} \\right] ^{1/2} e^{-\\alpha r^2/2} (\\alpha^{1/2} r)^\\ell L_n^{(\\ell + d/2 - 1)} (\\alpha r^2) Attributes -... | the_stack_v2_python_sparse | nitrogen/special.py | bchangala/nitrogen | train | 11 |
f9d3c7f1e9ffe1e3c38cee5eeafd17c93abe2304 | [
"self.alphabet = alphabet\nself.initial_population = 500\nself.min_generations = 10\nself._set_up_genetic_algorithm()",
"self.motif_generator = RandomMotifGenerator(self.alphabet)\nself.mutator = SinglePositionMutation(mutation_rate=0.1)\nself.crossover = SinglePointCrossover(crossover_prob=0.25)\nself.repair = A... | <|body_start_0|>
self.alphabet = alphabet
self.initial_population = 500
self.min_generations = 10
self._set_up_genetic_algorithm()
<|end_body_0|>
<|body_start_1|>
self.motif_generator = RandomMotifGenerator(self.alphabet)
self.mutator = SinglePositionMutation(mutation_ra... | Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous DNA elements. This can be overridden easily by creating a GeneticAlgorithmFinder with a d... | GeneticAlgorithmFinder | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneticAlgorithmFinder:
"""Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous DNA elements. This can be overridden ea... | stack_v2_sparse_classes_36k_train_022916 | 26,199 | permissive | [
{
"docstring": "Initialize a finder to get schemas using Genetic Algorithms. Arguments: o alphabet -- The alphabet which specifies the contents of the schemas we'll be generating. This alphabet must contain the attribute 'alphabet_matches', which is a dictionary specifying the potential ambiguities of each lett... | 3 | stack_v2_sparse_classes_30k_train_018626 | Implement the Python class `GeneticAlgorithmFinder` described below.
Class description:
Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous ... | Implement the Python class `GeneticAlgorithmFinder` described below.
Class description:
Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous ... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class GeneticAlgorithmFinder:
"""Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous DNA elements. This can be overridden ea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneticAlgorithmFinder:
"""Find schemas using a genetic algorithm approach. This approach to finding schema uses Genetic Algorithms to evolve a set of schema and find the best schema for a specific set of records. The 'default' finder searches for ambiguous DNA elements. This can be overridden easily by creat... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/NeuralNetwork/Gene/Schema.py | LyonsLab/coge | train | 41 |
397459f58944441cdcc984cda806f176cda75f90 | [
"self.n = n\nself.m = m\nself.input = np.ones(n + 1)\nself.output = np.ones(m)\nself.weights = np.zeros((1, self.m, self.n + 1))\nself.votes = np.zeros((1,))",
"self.input[1:] = input_sample\no = np.sign(np.dot(self.weights[-1, :, :], self.input))\nif o == output_sample:\n self.votes[-1] += 1\nelse:\n self.... | <|body_start_0|>
self.n = n
self.m = m
self.input = np.ones(n + 1)
self.output = np.ones(m)
self.weights = np.zeros((1, self.m, self.n + 1))
self.votes = np.zeros((1,))
<|end_body_0|>
<|body_start_1|>
self.input[1:] = input_sample
o = np.sign(np.dot(self.... | VotedPerceptron | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
<|body_0|>
def learn(self, input_sample, output_sample):
"""The learning function : a single sample is expected"""
<|body_1|>
def __call__(self, inp... | stack_v2_sparse_classes_36k_train_022917 | 5,850 | permissive | [
{
"docstring": "Initialization of the voted perceptron with given sizes.",
"name": "__init__",
"signature": "def __init__(self, n, m)"
},
{
"docstring": "The learning function : a single sample is expected",
"name": "learn",
"signature": "def learn(self, input_sample, output_sample)"
}... | 3 | stack_v2_sparse_classes_30k_train_010056 | Implement the Python class `VotedPerceptron` described below.
Class description:
Implement the VotedPerceptron class.
Method signatures and docstrings:
- def __init__(self, n, m): Initialization of the voted perceptron with given sizes.
- def learn(self, input_sample, output_sample): The learning function : a single ... | Implement the Python class `VotedPerceptron` described below.
Class description:
Implement the VotedPerceptron class.
Method signatures and docstrings:
- def __init__(self, n, m): Initialization of the voted perceptron with given sizes.
- def learn(self, input_sample, output_sample): The learning function : a single ... | 8a4f77a16c407f8f3c2955ff930ee97d8a10bbb5 | <|skeleton|>
class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
<|body_0|>
def learn(self, input_sample, output_sample):
"""The learning function : a single sample is expected"""
<|body_1|>
def __call__(self, inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VotedPerceptron:
def __init__(self, n, m):
"""Initialization of the voted perceptron with given sizes."""
self.n = n
self.m = m
self.input = np.ones(n + 1)
self.output = np.ones(m)
self.weights = np.zeros((1, self.m, self.n + 1))
self.votes = np.zeros((1... | the_stack_v2_python_sparse | recipes/ANN/voted-perceptron.py | praveen686/ML-Recipes | train | 0 | |
dbebde59ed8a0e43fb4bbed39a6923d5ca52d483 | [
"self.driver = driver\nself.by = by\nself.value = value\nself.locator = (self.by, self.value)\nself.webelement = None",
"element = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(locator=self.locator))\nself.webelement = element\nreturn None",
"element = WebDriverWait(self.driver, 10).unti... | <|body_start_0|>
self.driver = driver
self.by = by
self.value = value
self.locator = (self.by, self.value)
self.webelement = None
<|end_body_0|>
<|body_start_1|>
element = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(locator=self.locator))
... | This represents the element | BaseElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseElement:
"""This represents the element"""
def __init__(self, driver, by, value):
"""This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value"""
<|body_0|>
def find(self):
"""This is use... | stack_v2_sparse_classes_36k_train_022918 | 2,273 | no_license | [
{
"docstring": "This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value",
"name": "__init__",
"signature": "def __init__(self, driver, by, value)"
},
{
"docstring": "This is used to find the element :return:",
"name": ... | 6 | stack_v2_sparse_classes_30k_train_004073 | Implement the Python class `BaseElement` described below.
Class description:
This represents the element
Method signatures and docstrings:
- def __init__(self, driver, by, value): This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value
- def fi... | Implement the Python class `BaseElement` described below.
Class description:
This represents the element
Method signatures and docstrings:
- def __init__(self, driver, by, value): This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value
- def fi... | 2b7edfafc4e448bd558c034044570496ca68bf2d | <|skeleton|>
class BaseElement:
"""This represents the element"""
def __init__(self, driver, by, value):
"""This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value"""
<|body_0|>
def find(self):
"""This is use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseElement:
"""This represents the element"""
def __init__(self, driver, by, value):
"""This initializes the values :param driver: arg1 and webdriver :param by: arg2 and the by element :param value: arg3 and the value"""
self.driver = driver
self.by = by
self.value = valu... | the_stack_v2_python_sparse | Page_Object_Model3_Amazon/base_element.py | gsudarshan1990/Training_Projects | train | 0 |
23d41da8d6697bb99527a5f950287c58a2df96b5 | [
"self._preorder = preorder\nself._inorder = inorder\nself.dict = {}\nfor i in range(len(inorder)):\n self.dict[inorder[i]] = i\nreturn self.dfs(0, len(self._preorder) - 1, 0, len(self._inorder) - 1)",
"if pl > pr:\n return None\nroot = TreeNode(self._preorder[pl])\nroot_position = self.dict[root.val]\nleft ... | <|body_start_0|>
self._preorder = preorder
self._inorder = inorder
self.dict = {}
for i in range(len(inorder)):
self.dict[inorder[i]] = i
return self.dfs(0, len(self._preorder) - 1, 0, len(self._inorder) - 1)
<|end_body_0|>
<|body_start_1|>
if pl > pr:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def dfs(self, pl, pr, il, ir):
"""递归 :param pl: preorder的左边界 :param pr: preorder的右边界 :param il: inorder的左边界 :param ir: inorder的右边界 :... | stack_v2_sparse_classes_36k_train_022919 | 2,129 | no_license | [
{
"docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": "递归 :param pl: preorder的左边界 :param pr: preorder的右边界 :param il: inorder的左边界 :param ir: inorder的右边界 :return:",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def dfs(self, pl, pr, il, ir): 递归 :param pl: preorder的左边界 :param pr:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def dfs(self, pl, pr, il, ir): 递归 :param pl: preorder的左边界 :param pr:... | 19db0e78826d3e3d27d2574abd9d461eb41458d1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def dfs(self, pl, pr, il, ir):
"""递归 :param pl: preorder的左边界 :param pr: preorder的右边界 :param il: inorder的左边界 :param ir: inorder的右边界 :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
self._preorder = preorder
self._inorder = inorder
self.dict = {}
for i in range(len(inorder)):
self.dict[inorder[i]] = i
retur... | the_stack_v2_python_sparse | 剑指offer/(经典)面试题7.重建二叉树.py | weiyuyan/LeetCode | train | 2 | |
461417a45e33bf5168c544661d74b0da2ccfe6c3 | [
"if root is None:\n return []\nfrom collections import deque\nq = deque([root])\nresult = []\nwhile q:\n sz = len(q)\n for i in range(sz):\n node = q.popleft()\n if i == 0:\n result.append(node.val)\n if node.right:\n q.append(node.right)\n if node.left:\n ... | <|body_start_0|>
if root is None:
return []
from collections import deque
q = deque([root])
result = []
while q:
sz = len(q)
for i in range(sz):
node = q.popleft()
if i == 0:
result.append(nod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
"""BFS, Time: O(n), Space: O(n)"""
<|body_0|>
def rightSideView(self, root: TreeNode) -> List[int]:
"""DFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ro... | stack_v2_sparse_classes_36k_train_022920 | 1,105 | no_license | [
{
"docstring": "BFS, Time: O(n), Space: O(n)",
"name": "rightSideView",
"signature": "def rightSideView(self, root: TreeNode) -> List[int]"
},
{
"docstring": "DFS, Time: O(n), Space: O(n)",
"name": "rightSideView",
"signature": "def rightSideView(self, root: TreeNode) -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root: TreeNode) -> List[int]: BFS, Time: O(n), Space: O(n)
- def rightSideView(self, root: TreeNode) -> List[int]: DFS, Time: O(n), Space: O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root: TreeNode) -> List[int]: BFS, Time: O(n), Space: O(n)
- def rightSideView(self, root: TreeNode) -> List[int]: DFS, Time: O(n), Space: O(n)
<|skeleto... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
"""BFS, Time: O(n), Space: O(n)"""
<|body_0|>
def rightSideView(self, root: TreeNode) -> List[int]:
"""DFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
"""BFS, Time: O(n), Space: O(n)"""
if root is None:
return []
from collections import deque
q = deque([root])
result = []
while q:
sz = len(q)
for i in range(sz):... | the_stack_v2_python_sparse | python/199-Binary Tree Right Side View.py | cwza/leetcode | train | 0 | |
2e68e8dd9650c809d53efe221558e256f49dafbb | [
"minStack = []\nnum3 = -INF\nfor num1 in reversed(nums):\n if num1 < num3:\n return True\n while minStack and minStack[-1] < num1:\n num3 = minStack.pop()\n minStack.append(num1)\nreturn False",
"n = len(nums)\nleftMin = INF\nright = SortedList(nums)\nfor i2 in range(n):\n leftMin = min(... | <|body_start_0|>
minStack = []
num3 = -INF
for num1 in reversed(nums):
if num1 < num3:
return True
while minStack and minStack[-1] < num1:
num3 = minStack.pop()
minStack.append(num1)
return False
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find132pattern1(self, nums: List[int]) -> bool:
"""枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式"""
<|body_0|>
def find132pattern3(self, nums: List[int]) -> bool:
"""枚举3(中间的数) O(nlogn) 对1:维护左... | stack_v2_sparse_classes_36k_train_022921 | 1,743 | no_license | [
{
"docstring": "枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式",
"name": "find132pattern1",
"signature": "def find132pattern1(self, nums: List[int]) -> bool"
},
{
"docstring": "枚举3(中间的数) O(nlogn) 对1:维护左侧最小值 对2:维护右侧有序集合,找到第一个比左侧最小值大的数,检... | 2 | stack_v2_sparse_classes_30k_train_021398 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern1(self, nums: List[int]) -> bool: 枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式
- def find132patte... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern1(self, nums: List[int]) -> bool: 枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式
- def find132patte... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def find132pattern1(self, nums: List[int]) -> bool:
"""枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式"""
<|body_0|>
def find132pattern3(self, nums: List[int]) -> bool:
"""枚举3(中间的数) O(nlogn) 对1:维护左... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find132pattern1(self, nums: List[int]) -> bool:
"""枚举1 单调栈O(n) !从后往前遍历,维护一个单减的栈 可以找到一对(j,k)使得nums[j]>nums[k] 记录这个被pop出的nums[k] 如果之后遇到一个元素比nums[k]小 那么就找到了132模式"""
minStack = []
num3 = -INF
for num1 in reversed(nums):
if num1 < num3:
retu... | the_stack_v2_python_sparse | 1_stack/单调栈/倒序遍历/456. 132 模式.py | 981377660LMT/algorithm-study | train | 225 | |
94788a97470b928d0db3e8ffc39a2819c4989d11 | [
"ret = []\nfor x in self.get_range(max_size, **kwargs):\n ret.append(callback())\nreturn ret",
"exclude = kwargs.pop('exclude', None)\nexclude = set(exclude) if exclude else set()\nvals = make_list(args)\nif exclude:\n vals = list(set(vals).difference(exclude))\n if not vals:\n raise ValueError('N... | <|body_start_0|>
ret = []
for x in self.get_range(max_size, **kwargs):
ret.append(callback())
return ret
<|end_body_0|>
<|body_start_1|>
exclude = kwargs.pop('exclude', None)
exclude = set(exclude) if exclude else set()
vals = make_list(args)
if exclu... | SequenceData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum... | stack_v2_sparse_classes_36k_train_022922 | 2,708 | permissive | [
{
"docstring": "Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum size of the list :returns: list, the randomly generated list",
"name": "ge... | 3 | stack_v2_sparse_classes_30k_train_008208 | Implement the Python class `SequenceData` described below.
Class description:
Implement the SequenceData class.
Method signatures and docstrings:
- def get_list(self, callback, max_size=100, **kwargs): Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback... | Implement the Python class `SequenceData` described below.
Class description:
Implement the SequenceData class.
Method signatures and docstrings:
- def get_list(self, callback, max_size=100, **kwargs): Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback... | 41ca4bbbff595c2bb50403c5353f19670ec9e2ef | <|skeleton|>
class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum size of the l... | the_stack_v2_python_sparse | testdata/types/sequence.py | Jaymon/testdata | train | 10 | |
45ae6571a2b3e92331cd3fb3d3f593415333db9c | [
"is_np = isinstance(inputs, np.ndarray)\nif is_np:\n inputs = torch.tensor(inputs, dtype=torch.float32)\n_, indices = torch.max(inputs, 1)\nif is_np:\n return indices.numpy()\nreturn indices",
"serialized = transformer_pb.Layer()\nserialized.argmax_data.SetInParent()\nreturn serialized",
"if serialized.Wh... | <|body_start_0|>
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
_, indices = torch.max(inputs, 1)
if is_np:
return indices.numpy()
return indices
<|end_body_0|>
<|body_start_1|>
serialized = tra... | Represents an ArgMax layer in a network. | ArgMaxLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for the transformer server."""
<|body_1|>
def deserialize(cls, serialized):
... | stack_v2_sparse_classes_36k_train_022923 | 1,038 | permissive | [
{
"docstring": "Returns ArgMax(inputs).",
"name": "compute",
"signature": "def compute(self, inputs)"
},
{
"docstring": "Serializes the layer for the transformer server.",
"name": "serialize",
"signature": "def serialize(self)"
},
{
"docstring": "Deserializes the layer from the P... | 3 | stack_v2_sparse_classes_30k_train_021601 | Implement the Python class `ArgMaxLayer` described below.
Class description:
Represents an ArgMax layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Returns ArgMax(inputs).
- def serialize(self): Serializes the layer for the transformer server.
- def deserialize(cls, serialized): Deser... | Implement the Python class `ArgMaxLayer` described below.
Class description:
Represents an ArgMax layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Returns ArgMax(inputs).
- def serialize(self): Serializes the layer for the transformer server.
- def deserialize(cls, serialized): Deser... | 19abf589e84ee67317134573054c648bb25c244d | <|skeleton|>
class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for the transformer server."""
<|body_1|>
def deserialize(cls, serialized):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgMaxLayer:
"""Represents an ArgMax layer in a network."""
def compute(self, inputs):
"""Returns ArgMax(inputs)."""
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
_, indices = torch.max(inputs, 1)
if... | the_stack_v2_python_sparse | pysyrenn/frontend/argmax_layer.py | 95616ARG/SyReNN | train | 38 |
079e6154245ad9024ab8b89e4c1e41e31ab644e1 | [
"obj = ContactType(name='Test', slug='test')\nobj.save()\nself.assertEquals('Test', obj.name)\nself.assertNotEquals(obj.id, None)\nobj.delete()",
"type = ContactType(name='Test', slug='test')\ntype.save()\nobj = Contact(name='Test', contact_type=type)\nobj.save()\nself.assertEquals('Test', obj.name)\nself.assertN... | <|body_start_0|>
obj = ContactType(name='Test', slug='test')
obj.save()
self.assertEquals('Test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
<|end_body_0|>
<|body_start_1|>
type = ContactType(name='Test', slug='test')
type.save()
obj = Cont... | Identities Model Tests | IdentitiesModelsTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentitiesModelsTest:
"""Identities Model Tests"""
def test_model_contacttype(self):
"""Test ContactType model"""
<|body_0|>
def test_model_contact(self):
"""Test Contact model"""
<|body_1|>
def test_model_field(self):
"""Test Field model"""
... | stack_v2_sparse_classes_36k_train_022924 | 16,679 | permissive | [
{
"docstring": "Test ContactType model",
"name": "test_model_contacttype",
"signature": "def test_model_contacttype(self)"
},
{
"docstring": "Test Contact model",
"name": "test_model_contact",
"signature": "def test_model_contact(self)"
},
{
"docstring": "Test Field model",
"... | 3 | stack_v2_sparse_classes_30k_train_008806 | Implement the Python class `IdentitiesModelsTest` described below.
Class description:
Identities Model Tests
Method signatures and docstrings:
- def test_model_contacttype(self): Test ContactType model
- def test_model_contact(self): Test Contact model
- def test_model_field(self): Test Field model | Implement the Python class `IdentitiesModelsTest` described below.
Class description:
Identities Model Tests
Method signatures and docstrings:
- def test_model_contacttype(self): Test ContactType model
- def test_model_contact(self): Test Contact model
- def test_model_field(self): Test Field model
<|skeleton|>
clas... | 001e85eaf489c93b565efe679eb159cfcfef4c67 | <|skeleton|>
class IdentitiesModelsTest:
"""Identities Model Tests"""
def test_model_contacttype(self):
"""Test ContactType model"""
<|body_0|>
def test_model_contact(self):
"""Test Contact model"""
<|body_1|>
def test_model_field(self):
"""Test Field model"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentitiesModelsTest:
"""Identities Model Tests"""
def test_model_contacttype(self):
"""Test ContactType model"""
obj = ContactType(name='Test', slug='test')
obj.save()
self.assertEquals('Test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
... | the_stack_v2_python_sparse | identities/tests.py | alejo8591/maker | train | 0 |
92abb4ae58c1a251c6fe049f6397654555239dd3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingAppointment()",
"from .booking_customer_information_base import BookingCustomerInformationBase\nfrom .booking_price_type import BookingPriceType\nfrom .booking_reminder import BookingReminder\nfrom .date_time_time_zone import Da... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingAppointment()
<|end_body_0|>
<|body_start_1|>
from .booking_customer_information_base import BookingCustomerInformationBase
from .booking_price_type import BookingPriceType
... | Represents a booked appointment of a service by a customer in a business. | BookingAppointment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingAppointment:
"""Represents a booked appointment of a service by a customer in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingAppointment:
"""Creates a new instance of the appropriate class based on discriminator value Args: p... | stack_v2_sparse_classes_36k_train_022925 | 10,710 | 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: BookingAppointment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `BookingAppointment` described below.
Class description:
Represents a booked appointment of a service by a customer in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingAppointment: Creates a new instance of t... | Implement the Python class `BookingAppointment` described below.
Class description:
Represents a booked appointment of a service by a customer in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingAppointment: Creates a new instance of t... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingAppointment:
"""Represents a booked appointment of a service by a customer in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingAppointment:
"""Creates a new instance of the appropriate class based on discriminator value Args: p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookingAppointment:
"""Represents a booked appointment of a service by a customer in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingAppointment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | the_stack_v2_python_sparse | msgraph/generated/models/booking_appointment.py | microsoftgraph/msgraph-sdk-python | train | 135 |
97e64dfff814406b53f2dcbaa3b597ab8bb6e704 | [
"names = names or utils.generate_ids(count=count)\nkeypairs = []\nfor name in names:\n keypair = self._client.create(name, public_key=public_key)\n keypairs.append(keypair)\nif check:\n self.check_keypairs_presence(keypairs)\n for keypair in keypairs:\n if public_key is not None:\n ass... | <|body_start_0|>
names = names or utils.generate_ids(count=count)
keypairs = []
for name in names:
keypair = self._client.create(name, public_key=public_key)
keypairs.append(keypair)
if check:
self.check_keypairs_presence(keypairs)
for keyp... | Keypair steps. | KeypairSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. ... | stack_v2_sparse_classes_36k_train_022926 | 4,659 | no_license | [
{
"docstring": "Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. public_key (str, optional): Existing public key to import. check (bool, optional): Flag whether to check step or not. Returns: ... | 4 | stack_v2_sparse_classes_30k_train_008987 | Implement the Python class `KeypairSteps` described below.
Class description:
Keypair steps.
Method signatures and docstrings:
- def create_keypairs(self, names=None, count=1, public_key=None, check=True): Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count ... | Implement the Python class `KeypairSteps` described below.
Class description:
Keypair steps.
Method signatures and docstrings:
- def create_keypairs(self, names=None, count=1, public_key=None, check=True): Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count ... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeypairSteps:
"""Keypair steps."""
def create_keypairs(self, names=None, count=1, public_key=None, check=True):
"""Step to create keypairs. Args: names (list, optional): Names of creating keypairs. count (int, optional): Count of creating keypairs, omitted if ``names`` is specified. public_key (s... | the_stack_v2_python_sparse | stepler/nova/steps/keypairs.py | Mirantis/stepler | train | 16 |
c9c5dd27228805e6c3b1ec4329574202a657d5de | [
"if 'ServiceRole' in usr_model['Configurations']:\n service_role = usr_model['Configurations']['ServiceRole'].split('/')[-1]\n try:\n get_role(service_role)\n except (NotFoundError, ServiceError):\n raise InvalidOptionsError(strings['lifecycle.invalidrole'].replace('{role}', service_role))\nr... | <|body_start_0|>
if 'ServiceRole' in usr_model['Configurations']:
service_role = usr_model['Configurations']['ServiceRole'].split('/')[-1]
try:
get_role(service_role)
except (NotFoundError, ServiceError):
raise InvalidOptionsError(strings['life... | LifecycleConfiguration | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifecycleConfiguration:
def collect_changes(self, usr_model):
"""Because we can't remove options from the lifecycle config we can only add to them so we just take the direct user model and apply that. :param usr_model: User model, key-value style :return: api_model"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_022927 | 3,127 | permissive | [
{
"docstring": "Because we can't remove options from the lifecycle config we can only add to them so we just take the direct user model and apply that. :param usr_model: User model, key-value style :return: api_model",
"name": "collect_changes",
"signature": "def collect_changes(self, usr_model)"
},
... | 2 | stack_v2_sparse_classes_30k_train_020170 | Implement the Python class `LifecycleConfiguration` described below.
Class description:
Implement the LifecycleConfiguration class.
Method signatures and docstrings:
- def collect_changes(self, usr_model): Because we can't remove options from the lifecycle config we can only add to them so we just take the direct use... | Implement the Python class `LifecycleConfiguration` described below.
Class description:
Implement the LifecycleConfiguration class.
Method signatures and docstrings:
- def collect_changes(self, usr_model): Because we can't remove options from the lifecycle config we can only add to them so we just take the direct use... | 252101641a7b6acb5de17fafd6adf8b96418426f | <|skeleton|>
class LifecycleConfiguration:
def collect_changes(self, usr_model):
"""Because we can't remove options from the lifecycle config we can only add to them so we just take the direct user model and apply that. :param usr_model: User model, key-value style :return: api_model"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LifecycleConfiguration:
def collect_changes(self, usr_model):
"""Because we can't remove options from the lifecycle config we can only add to them so we just take the direct user model and apply that. :param usr_model: User model, key-value style :return: api_model"""
if 'ServiceRole' in usr_m... | the_stack_v2_python_sparse | ebcli/objects/lifecycleconfiguration.py | aws/aws-elastic-beanstalk-cli | train | 149 | |
e186e7e45f3df5b77b37ab2b274296cc904ad2af | [
"if not arr1 or not arr2 or (not arr3):\n return []\narr1 = set(arr1)\narr2 = set(arr2)\narr3 = set(arr3)\narr1 = arr1.intersection(arr2)\narr1 = arr1.intersection(arr3)\nreturn sorted(list(arr1))",
"res = []\napperance = {}\nfor i in arr1:\n if i in apperance.keys():\n continue\n else:\n a... | <|body_start_0|>
if not arr1 or not arr2 or (not arr3):
return []
arr1 = set(arr1)
arr2 = set(arr2)
arr3 = set(arr3)
arr1 = arr1.intersection(arr2)
arr1 = arr1.intersection(arr3)
return sorted(list(arr1))
<|end_body_0|>
<|body_start_1|>
res = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def arraysIntersection(self, arr1, arr2, arr3):
"""思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:"""
<|body_0|>
def arraysIntersection1(self, arr1, arr2, arr3):
"""思路二:统计各个数字在三个列表中出现的次数,次数为3的为相交... | stack_v2_sparse_classes_36k_train_022928 | 1,888 | no_license | [
{
"docstring": "思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:",
"name": "arraysIntersection",
"signature": "def arraysIntersection(self, arr1, arr2, arr3)"
},
{
"docstring": "思路二:统计各个数字在三个列表中出现的次数,次数为3的为相交的数字",
"name": "arraysIn... | 2 | stack_v2_sparse_classes_30k_train_001265 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arraysIntersection(self, arr1, arr2, arr3): 思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:
- def arraysIntersec... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arraysIntersection(self, arr1, arr2, arr3): 思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:
- def arraysIntersec... | 95dddb78bccd169d9d219a473627361fe739ab5e | <|skeleton|>
class Solution:
def arraysIntersection(self, arr1, arr2, arr3):
"""思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:"""
<|body_0|>
def arraysIntersection1(self, arr1, arr2, arr3):
"""思路二:统计各个数字在三个列表中出现的次数,次数为3的为相交... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def arraysIntersection(self, arr1, arr2, arr3):
"""思路一:利用集合的交操作 因为set无序,所以顺序会变,需要最后排个序 利用内置数据结构,时间空间都消耗极低,战胜100% :param arr1: :param arr2: :param arr3: :return:"""
if not arr1 or not arr2 or (not arr3):
return []
arr1 = set(arr1)
arr2 = set(arr2)
a... | the_stack_v2_python_sparse | ArrayOperation/arraysIntersection.py | Philex5/codingPractice | train | 0 | |
f5b84403aa8430e2df9859ec0833b66fb5ef0220 | [
"res = 1\nfor i in xrange(k):\n res = res * a % 1337\nreturn res",
"if not b:\n return 1\nlast = b.pop()\nreturn self.smallkpow(self.superPow(a, b), 10) * self.smallkpow(a, last) % 1337"
] | <|body_start_0|>
res = 1
for i in xrange(k):
res = res * a % 1337
return res
<|end_body_0|>
<|body_start_1|>
if not b:
return 1
last = b.pop()
return self.smallkpow(self.superPow(a, b), 10) * self.smallkpow(a, last) % 1337
<|end_body_1|>
| Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def smallkpow(self, a, k):
"""k>=0 and k<=10"""
<|body_0|>
def superPow(self, a, b):
""":type a: int :type b: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 1
for i in xrange(k):
res = res *... | stack_v2_sparse_classes_36k_train_022929 | 588 | permissive | [
{
"docstring": "k>=0 and k<=10",
"name": "smallkpow",
"signature": "def smallkpow(self, a, k)"
},
{
"docstring": ":type a: int :type b: List[int] :rtype: int",
"name": "superPow",
"signature": "def superPow(self, a, b)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012930 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallkpow(self, a, k): k>=0 and k<=10
- def superPow(self, a, b): :type a: int :type b: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallkpow(self, a, k): k>=0 and k<=10
- def superPow(self, a, b): :type a: int :type b: List[int] :rtype: int
<|skeleton|>
class Solution:
def smallkpow(self, a, k):
... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def smallkpow(self, a, k):
"""k>=0 and k<=10"""
<|body_0|>
def superPow(self, a, b):
""":type a: int :type b: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def smallkpow(self, a, k):
"""k>=0 and k<=10"""
res = 1
for i in xrange(k):
res = res * a % 1337
return res
def superPow(self, a, b):
""":type a: int :type b: List[int] :rtype: int"""
if not b:
return 1
last = b.pop... | the_stack_v2_python_sparse | 372-Super-Pow/solution.py | Tanych/CodeTracking | train | 0 | |
9245ee49519a383f37c2562e1b192473e28e7025 | [
"if not spec.act_space.flat_dim % 2 == 0:\n raise pyrado.ShapeErr(msg='DualRBFLinearPolicy only works with an even number of actions, since we are using the time derivative of the features to create the second half of the outputs. This is done to use forward() in order to obtain the joint position and the joint ... | <|body_start_0|>
if not spec.act_space.flat_dim % 2 == 0:
raise pyrado.ShapeErr(msg='DualRBFLinearPolicy only works with an even number of actions, since we are using the time derivative of the features to create the second half of the outputs. This is done to use forward() in order to obtain the jo... | A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we reduce the number of parameters, while... | DualRBFLinearPolicy | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_36k_train_022930 | 6,470 | permissive | [
{
"docstring": "Constructor :param spec: specification of environment :param rbf_hparam: hyper-parameters for the RBF-features, see `RBFFeat` :param dim_mask: number of RBF features to mask out at the beginning and the end of every dimension, pass 1 to remove the first and the last features for the policy, pass... | 2 | stack_v2_sparse_classes_30k_train_018713 | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we redu... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/feed_back/dual_rfb.py | 1abner1/SimuRLacra | train | 0 |
a0748268918f95df8bb55248fcb6a14ecc966839 | [
"cls.BUFFER_SIZE = buffer_size\ncls.message_handler = message_handler\ncls.logger = logger\ncls.message_handler.logger = logging.getLogger(message_handler.__class__.__name__)\ncls.message_handler.logger.setLevel(logger.level)\nreturn cls",
"logger = StreamHandler.logger\nlogger.debug('handling requests with messa... | <|body_start_0|>
cls.BUFFER_SIZE = buffer_size
cls.message_handler = message_handler
cls.logger = logger
cls.message_handler.logger = logging.getLogger(message_handler.__class__.__name__)
cls.message_handler.logger.setLevel(logger.level)
return cls
<|end_body_0|>
<|body_... | A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler | StreamHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamHandler:
"""A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler"""
def create_handler(cls, message_handler, buffer_size, logger):
"""Class variables used here since the framework creates an instance for e... | stack_v2_sparse_classes_36k_train_022931 | 5,203 | permissive | [
{
"docstring": "Class variables used here since the framework creates an instance for each connection :param message_handler: the MessageHandler used to process each message. :param buffer_size: the TCP buffer size. :param logger: the global logger. :return: this class.",
"name": "create_handler",
"sign... | 2 | stack_v2_sparse_classes_30k_train_011060 | Implement the Python class `StreamHandler` described below.
Class description:
A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler
Method signatures and docstrings:
- def create_handler(cls, message_handler, buffer_size, logger): Class variable... | Implement the Python class `StreamHandler` described below.
Class description:
A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler
Method signatures and docstrings:
- def create_handler(cls, message_handler, buffer_size, logger): Class variable... | 208b542f9eba82e97882d52703af8e965a62a980 | <|skeleton|>
class StreamHandler:
"""A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler"""
def create_handler(cls, message_handler, buffer_size, logger):
"""Class variables used here since the framework creates an instance for e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamHandler:
"""A RequestHandler that waits for messages over its request socket until the socket is closed and delegates to a MessageHandler"""
def create_handler(cls, message_handler, buffer_size, logger):
"""Class variables used here since the framework creates an instance for each connectio... | the_stack_v2_python_sparse | springcloudstream/tcp/tcp.py | dturanski/springcloudstream | train | 1 |
d467e4aad74e0b846830603633fb678cca505b25 | [
"super().__init__()\nself.padding = (kernel_size - 1) * dilation\nself.causal_conv1d = torch.nn.Conv1d(idim, odim, kernel_size=kernel_size, stride=stride, padding=self.padding, dilation=dilation, groups=groups, bias=bias)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nif batch_norm:\n self.bn = torch.nn.Batch... | <|body_start_0|>
super().__init__()
self.padding = (kernel_size - 1) * dilation
self.causal_conv1d = torch.nn.Conv1d(idim, odim, kernel_size=kernel_size, stride=stride, padding=self.padding, dilation=dilation, groups=groups, bias=bias)
self.dropout = torch.nn.Dropout(p=dropout_rate)
... | 1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number of blocked connections from input channels to output channels. bias: Whether to... | CausalConv1d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CausalConv1d:
"""1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number of blocked connections from input chann... | stack_v2_sparse_classes_36k_train_022932 | 7,246 | permissive | [
{
"docstring": "Construct a CausalConv1d object.",
"name": "__init__",
"signature": "def __init__(self, idim: int, odim: int, kernel_size: int, stride: int=1, dilation: int=1, groups: int=1, bias: bool=True, batch_norm: bool=False, relu: bool=True, dropout_rate: float=0.0)"
},
{
"docstring": "Fo... | 2 | stack_v2_sparse_classes_30k_train_009693 | Implement the Python class `CausalConv1d` described below.
Class description:
1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number ... | Implement the Python class `CausalConv1d` described below.
Class description:
1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number ... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CausalConv1d:
"""1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number of blocked connections from input chann... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CausalConv1d:
"""1D causal convolution module for custom decoder. Args: idim: Input dimension. odim: Output dimension. kernel_size: Size of the convolving kernel. stride: Stride of the convolution. dilation: Spacing between the kernel points. groups: Number of blocked connections from input channels to output... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/conv1d_nets.py | espnet/espnet | train | 7,242 |
9bd37c6553575bcc390f57bdf54697f18e1c45e2 | [
"self.cam = camera_instance\nself.flow = None\nself._bw_image_array = np.zeros((self.cam.h, self.cam.w, 2), dtype=np.uint8)\nself._time_array = np.zeros(2, dtype=np.float32)\nself.initialised = False\nself.__flow_iterations = 0\nself.viewing_directions = None",
"if self.__flow_iterations < 2:\n self.__flow_ite... | <|body_start_0|>
self.cam = camera_instance
self.flow = None
self._bw_image_array = np.zeros((self.cam.h, self.cam.w, 2), dtype=np.uint8)
self._time_array = np.zeros(2, dtype=np.float32)
self.initialised = False
self.__flow_iterations = 0
self.viewing_directions =... | Class to generate optic flow | OpticFlow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpticFlow:
"""Class to generate optic flow"""
def __init__(self, camera_instance):
"""Initialise the optic flow class Args: camera_instance (Camera): the camera object"""
<|body_0|>
def __initialised(self):
"""This property must be called twice before the flow is... | stack_v2_sparse_classes_36k_train_022933 | 3,312 | no_license | [
{
"docstring": "Initialise the optic flow class Args: camera_instance (Camera): the camera object",
"name": "__init__",
"signature": "def __init__(self, camera_instance)"
},
{
"docstring": "This property must be called twice before the flow is initialised (since we need at least 2 frames to comp... | 3 | stack_v2_sparse_classes_30k_train_017786 | Implement the Python class `OpticFlow` described below.
Class description:
Class to generate optic flow
Method signatures and docstrings:
- def __init__(self, camera_instance): Initialise the optic flow class Args: camera_instance (Camera): the camera object
- def __initialised(self): This property must be called twi... | Implement the Python class `OpticFlow` described below.
Class description:
Class to generate optic flow
Method signatures and docstrings:
- def __init__(self, camera_instance): Initialise the optic flow class Args: camera_instance (Camera): the camera object
- def __initialised(self): This property must be called twi... | b51b224cc19c252555b3e0e3a77e9ebd811c9293 | <|skeleton|>
class OpticFlow:
"""Class to generate optic flow"""
def __init__(self, camera_instance):
"""Initialise the optic flow class Args: camera_instance (Camera): the camera object"""
<|body_0|>
def __initialised(self):
"""This property must be called twice before the flow is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpticFlow:
"""Class to generate optic flow"""
def __init__(self, camera_instance):
"""Initialise the optic flow class Args: camera_instance (Camera): the camera object"""
self.cam = camera_instance
self.flow = None
self._bw_image_array = np.zeros((self.cam.h, self.cam.w, 2... | the_stack_v2_python_sparse | src/opticFlow.py | joanreyero/pyx4-avoidance | train | 0 |
a4bfffa4c70966bdfde8013101f51799e329a4fd | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsMetricHistory()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'deviceId': lambda n: setattr(self, 'device_id', n.get_str_value()), 'metricDateTime': lambda... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsMetricHistory()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'deviceId... | The user experience analytics metric history. | UserExperienceAnalyticsMetricHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsMetricHistory:
"""The user experience analytics metric history."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsMetricHistory:
"""Creates a new instance of the appropriate class based on discriminator value... | stack_v2_sparse_classes_36k_train_022934 | 2,929 | 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: UserExperienceAnalyticsMetricHistory",
"name": "create_from_discriminator_value",
"signature": "def create_f... | 3 | stack_v2_sparse_classes_30k_test_000174 | Implement the Python class `UserExperienceAnalyticsMetricHistory` described below.
Class description:
The user experience analytics metric history.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsMetricHistory: Creates a new insta... | Implement the Python class `UserExperienceAnalyticsMetricHistory` described below.
Class description:
The user experience analytics metric history.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsMetricHistory: Creates a new insta... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsMetricHistory:
"""The user experience analytics metric history."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsMetricHistory:
"""Creates a new instance of the appropriate class based on discriminator value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsMetricHistory:
"""The user experience analytics metric history."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsMetricHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_metric_history.py | microsoftgraph/msgraph-sdk-python | train | 135 |
91ff1f496b8b073141bfdc71f965b0187e3a2488 | [
"try:\n self._cur.execute('COMMIT')\n self._cur.execute(query)\n return str(self._cur.fetchall())\nexcept DatabaseError:\n return None",
"query = query.strip(' ;\\n')\nif not query:\n return 0\norig_checksum = self._result_checksum(query)\nif not orig_checksum:\n return 0\ntokens = query.split()... | <|body_start_0|>
try:
self._cur.execute('COMMIT')
self._cur.execute(query)
return str(self._cur.fetchall())
except DatabaseError:
return None
<|end_body_0|>
<|body_start_1|>
query = query.strip(' ;\n')
if not query:
return 0
... | AllPartsEssential | [
"Apache-2.0",
"BSD-2-Clause",
"CC0-1.0",
"BSD-3-Clause",
"MPL-2.0",
"0BSD",
"PostgreSQL",
"GPL-1.0-or-later",
"GPL-2.0-only",
"MIT",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllPartsEssential:
def _result_checksum(self, query: str) -> Optional[str]:
"""Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set"""
<|body_0|>
def fitness(self, query: str) -> fl... | stack_v2_sparse_classes_36k_train_022935 | 2,632 | permissive | [
{
"docstring": "Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set",
"name": "_result_checksum",
"signature": "def _result_checksum(self, query: str) -> Optional[str]"
},
{
"docstring": "Test if all p... | 2 | null | Implement the Python class `AllPartsEssential` described below.
Class description:
Implement the AllPartsEssential class.
Method signatures and docstrings:
- def _result_checksum(self, query: str) -> Optional[str]: Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply... | Implement the Python class `AllPartsEssential` described below.
Class description:
Implement the AllPartsEssential class.
Method signatures and docstrings:
- def _result_checksum(self, query: str) -> Optional[str]: Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply... | cb9d59d2f1c0eaee33b864982f22b7b3b9ba8759 | <|skeleton|>
class AllPartsEssential:
def _result_checksum(self, query: str) -> Optional[str]:
"""Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set"""
<|body_0|>
def fitness(self, query: str) -> fl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllPartsEssential:
def _result_checksum(self, query: str) -> Optional[str]:
"""Execute the query and return a 'checksum' of the result. In this implementation, the checksum is simply the serialization of the entire result set"""
try:
self._cur.execute('COMMIT')
self._cu... | the_stack_v2_python_sparse | misc/python/materialize/query_fitness/all_parts_essential.py | nisarhassan12/materialize | train | 0 | |
5fd11087005f18f9e56a7c6cdf19fac3a065061e | [
"logger.trace('Loading latest preview')\nget_images().load_latest_preview()\nself.display_item = get_images().previewoutput",
"logger.trace('Displaying preview')\nif not self.subnotebook.children:\n self.add_child()\nelse:\n self.update_child()",
"logger.debug('Adding child')\npreview = self.subnotebook_a... | <|body_start_0|>
logger.trace('Loading latest preview')
get_images().load_latest_preview()
self.display_item = get_images().previewoutput
<|end_body_0|>
<|body_start_1|>
logger.trace('Displaying preview')
if not self.subnotebook.children:
self.add_child()
els... | Tab to display output preview images for extract and convert | PreviewExtract | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreviewExtract:
"""Tab to display output preview images for extract and convert"""
def display_item_set(self):
"""Load the latest preview if available"""
<|body_0|>
def display_item_process(self):
"""Display the preview"""
<|body_1|>
def add_child(se... | stack_v2_sparse_classes_36k_train_022936 | 9,600 | permissive | [
{
"docstring": "Load the latest preview if available",
"name": "display_item_set",
"signature": "def display_item_set(self)"
},
{
"docstring": "Display the preview",
"name": "display_item_process",
"signature": "def display_item_process(self)"
},
{
"docstring": "Add the preview l... | 5 | stack_v2_sparse_classes_30k_train_008991 | Implement the Python class `PreviewExtract` described below.
Class description:
Tab to display output preview images for extract and convert
Method signatures and docstrings:
- def display_item_set(self): Load the latest preview if available
- def display_item_process(self): Display the preview
- def add_child(self):... | Implement the Python class `PreviewExtract` described below.
Class description:
Tab to display output preview images for extract and convert
Method signatures and docstrings:
- def display_item_set(self): Load the latest preview if available
- def display_item_process(self): Display the preview
- def add_child(self):... | e507f94d4f5d74c36e41c386c6fb14bb745a4885 | <|skeleton|>
class PreviewExtract:
"""Tab to display output preview images for extract and convert"""
def display_item_set(self):
"""Load the latest preview if available"""
<|body_0|>
def display_item_process(self):
"""Display the preview"""
<|body_1|>
def add_child(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreviewExtract:
"""Tab to display output preview images for extract and convert"""
def display_item_set(self):
"""Load the latest preview if available"""
logger.trace('Loading latest preview')
get_images().load_latest_preview()
self.display_item = get_images().previewoutpu... | the_stack_v2_python_sparse | lib/gui/display_command.py | oveis/DeepVideoFaceSwap | train | 6 |
da07c5ea03b747c7333afc677373ed9bbf657aac | [
"res = []\n\ndef dfs(root):\n if root is None:\n res.append('N')\n return\n res.append(str(root.val))\n dfs(root.left)\n dfs(root.right)\ndfs(root)\nres = ','.join(res)\nreturn res",
"data = data.split(',')\nself.idx = 0\n\ndef dfs():\n if data[self.idx] == 'N':\n self.idx += 1... | <|body_start_0|>
res = []
def dfs(root):
if root is None:
res.append('N')
return
res.append(str(root.val))
dfs(root.left)
dfs(root.right)
dfs(root)
res = ','.join(res)
return res
<|end_body_0|>
<|bo... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_022937 | 1,410 | 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_val_000678 | 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:... | 86875d7436a78420591a60b716acd2780287b4a8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def dfs(root):
if root is None:
res.append('N')
return
res.append(str(root.val))
dfs(root.left)
... | the_stack_v2_python_sparse | leetcode/LeetCode-150/Trees/297-Serialize-and-Deserialize-Binary-Tree.py | hrishikeshtak/Coding_Practises_Solutions | train | 0 | |
e6cfc3f42cbc1fb0be626f631034c4f610cf5056 | [
"shift = ampcor.libpyre.grid.Index2D(index=self.shift)\npairings = ampcor.libampcor.constantShift(points=points, shift=shift)\nreturn pairings",
"yield f'{margin}functor: {self.pyre_family()}'\nyield f'{margin}{indent}name: {self.pyre_name}'\nyield f'{margin}{indent}family: {self.pyre_family()}'\nyield f'{margin}... | <|body_start_0|>
shift = ampcor.libpyre.grid.Index2D(index=self.shift)
pairings = ampcor.libampcor.constantShift(points=points, shift=shift)
return pairings
<|end_body_0|>
<|body_start_1|>
yield f'{margin}functor: {self.pyre_family()}'
yield f'{margin}{indent}name: {self.pyre_na... | A functor that add a constant offset | Constant | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Constant:
"""A functor that add a constant offset"""
def eval(self, points, **kwds):
"""Map the given set of {points} to their images under my transformation"""
<|body_0|>
def show(self, indent, margin):
"""Display my configuration"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_022938 | 1,473 | permissive | [
{
"docstring": "Map the given set of {points} to their images under my transformation",
"name": "eval",
"signature": "def eval(self, points, **kwds)"
},
{
"docstring": "Display my configuration",
"name": "show",
"signature": "def show(self, indent, margin)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009197 | Implement the Python class `Constant` described below.
Class description:
A functor that add a constant offset
Method signatures and docstrings:
- def eval(self, points, **kwds): Map the given set of {points} to their images under my transformation
- def show(self, indent, margin): Display my configuration | Implement the Python class `Constant` described below.
Class description:
A functor that add a constant offset
Method signatures and docstrings:
- def eval(self, points, **kwds): Map the given set of {points} to their images under my transformation
- def show(self, indent, margin): Display my configuration
<|skeleto... | 95c1e29f57b7a6eb29c61e2983c384a6eabf2e8b | <|skeleton|>
class Constant:
"""A functor that add a constant offset"""
def eval(self, points, **kwds):
"""Map the given set of {points} to their images under my transformation"""
<|body_0|>
def show(self, indent, margin):
"""Display my configuration"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Constant:
"""A functor that add a constant offset"""
def eval(self, points, **kwds):
"""Map the given set of {points} to their images under my transformation"""
shift = ampcor.libpyre.grid.Index2D(index=self.shift)
pairings = ampcor.libampcor.constantShift(points=points, shift=shi... | the_stack_v2_python_sparse | pkg/ampcor/correlators/Constant.py | aivazis/ampcor | train | 3 |
02e4befb1952d023997bac68961c5a728887435b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Searches for videos | SearchServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
<|body_0|>
def GetQuerySuggestions(self, request, context):
"""Gets search query suggestions (could be used for typeahead su... | stack_v2_sparse_classes_36k_train_022939 | 2,478 | permissive | [
{
"docstring": "Searches for videos by a given query term",
"name": "SearchVideos",
"signature": "def SearchVideos(self, request, context)"
},
{
"docstring": "Gets search query suggestions (could be used for typeahead support)",
"name": "GetQuerySuggestions",
"signature": "def GetQuerySu... | 2 | stack_v2_sparse_classes_30k_train_000497 | Implement the Python class `SearchServiceServicer` described below.
Class description:
Searches for videos
Method signatures and docstrings:
- def SearchVideos(self, request, context): Searches for videos by a given query term
- def GetQuerySuggestions(self, request, context): Gets search query suggestions (could be ... | Implement the Python class `SearchServiceServicer` described below.
Class description:
Searches for videos
Method signatures and docstrings:
- def SearchVideos(self, request, context): Searches for videos by a given query term
- def GetQuerySuggestions(self, request, context): Gets search query suggestions (could be ... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
<|body_0|>
def GetQuerySuggestions(self, request, context):
"""Gets search query suggestions (could be used for typeahead su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchServiceServicer:
"""Searches for videos"""
def SearchVideos(self, request, context):
"""Searches for videos by a given query term"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not i... | the_stack_v2_python_sparse | killrvideo/search/search_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
1f149501ee1f991a2fe0e31947b627d399d8a74a | [
"self.distance_x = distance_x\nself.eps = eps\nself.lr_lamb = lr_lamb\nself.lr_param = lr_param\nself.auditor_nsteps = auditor_nsteps\nself.auditor_lr = auditor_lr\nsuper().__init__(module=module, criterion=criterion, regression=regression, **kwargs)",
"self.initialize_criterion()\nkwargs = self.get_params_for('m... | <|body_start_0|>
self.distance_x = distance_x
self.eps = eps
self.lr_lamb = lr_lamb
self.lr_param = lr_param
self.auditor_nsteps = auditor_nsteps
self.auditor_lr = auditor_lr
super().__init__(module=module, criterion=criterion, regression=regression, **kwargs)
<|e... | Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individually fair ML models with sensitiv... | SenSR | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individu... | stack_v2_sparse_classes_36k_train_022940 | 15,710 | permissive | [
{
"docstring": "Args: module (torch.nn.Module): Network architecture. criterion (torch.nn.Module): Loss function. distance_x (inFairness.distances.Distance): Distance metric in the input space. eps (float): :math:`\\\\epsilon` parameter in the SenSR algorithm. lr_lamb (float): :math:`\\\\lambda` parameter in th... | 2 | stack_v2_sparse_classes_30k_train_004321 | Implement the Python class `SenSR` described below.
Class description:
Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A... | Implement the Python class `SenSR` described below.
Class description:
Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SenSR:
"""Sensitive Subspace Robustness (SenSR). SenSR is an in-processing method for individual fairness which enforces performance invariance under certain sensitive perturbations to the input [#yurochkin19]_. References: .. [#yurochkin19] `M. Yurochkin, A. Bower, and Y. Sun, "Training individually fair ML ... | the_stack_v2_python_sparse | aif360/sklearn/inprocessing/infairness.py | Trusted-AI/AIF360 | train | 1,157 |
5b9ce0393b608fe830a7ac00f32ded5d74f34480 | [
"node = XMLHelper.build_node_from_string(ResourceInfoBuilder.RESOURCE_TEMPLATE)\nnode.set('Name', resource_info.name)\nnode.set('ResourceFamilyName', resource_info.family_name)\nnode.set('ResourceModelName', resource_info.model_name)\nnode.set('SerialNumber', resource_info.serial_number)\nnode.set('Address', resour... | <|body_start_0|>
node = XMLHelper.build_node_from_string(ResourceInfoBuilder.RESOURCE_TEMPLATE)
node.set('Name', resource_info.name)
node.set('ResourceFamilyName', resource_info.family_name)
node.set('ResourceModelName', resource_info.model_name)
node.set('SerialNumber', resource... | Build resource info node. | ResourceInfoBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceInfoBuilder:
"""Build resource info node."""
def _build_resource_node(resource_info: ResourceInfo) -> Element:
"""Build resource xml node."""
<|body_0|>
def _build_attribute_node(attribute: Attribute) -> Element:
"""Build attribute node. :type attribute: ... | stack_v2_sparse_classes_36k_train_022941 | 3,487 | no_license | [
{
"docstring": "Build resource xml node.",
"name": "_build_resource_node",
"signature": "def _build_resource_node(resource_info: ResourceInfo) -> Element"
},
{
"docstring": "Build attribute node. :type attribute: cloudshell.layer_one.core.response.resource_info.entities.base.Attribute # noqa: E5... | 5 | stack_v2_sparse_classes_30k_train_007806 | Implement the Python class `ResourceInfoBuilder` described below.
Class description:
Build resource info node.
Method signatures and docstrings:
- def _build_resource_node(resource_info: ResourceInfo) -> Element: Build resource xml node.
- def _build_attribute_node(attribute: Attribute) -> Element: Build attribute no... | Implement the Python class `ResourceInfoBuilder` described below.
Class description:
Build resource info node.
Method signatures and docstrings:
- def _build_resource_node(resource_info: ResourceInfo) -> Element: Build resource xml node.
- def _build_attribute_node(attribute: Attribute) -> Element: Build attribute no... | 82562665834908294136bbe8e7bc46da1a21b8e2 | <|skeleton|>
class ResourceInfoBuilder:
"""Build resource info node."""
def _build_resource_node(resource_info: ResourceInfo) -> Element:
"""Build resource xml node."""
<|body_0|>
def _build_attribute_node(attribute: Attribute) -> Element:
"""Build attribute node. :type attribute: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceInfoBuilder:
"""Build resource info node."""
def _build_resource_node(resource_info: ResourceInfo) -> Element:
"""Build resource xml node."""
node = XMLHelper.build_node_from_string(ResourceInfoBuilder.RESOURCE_TEMPLATE)
node.set('Name', resource_info.name)
node.se... | the_stack_v2_python_sparse | cloudshell/layer_one/core/response/resource_info/resource_info_builder.py | QualiSystems/cloudshell-L1-networking-core | train | 1 |
f3ae4fca5dc624155c53492ff1fff49eb09ae562 | [
"self._check_cp(cp)\nself.cp = cp\nself.mass = mass\nself.g_tt = g_tt\nself.g_vlq = g_vlq\nself.mass_vlq = mass_vlq\nself.num_vlq = num_vlq\nself.var_scale = self.width_tt(cp, mass, g=g_tt)\nself.k_res = 2.0\nself.k_int = math.sqrt(2.0 * 2.0)",
"s = sqrt_s ** 2\nif s <= 4 * self.mt ** 2:\n return 0.0\nwidth = ... | <|body_start_0|>
self._check_cp(cp)
self.cp = cp
self.mass = mass
self.g_tt = g_tt
self.g_vlq = g_vlq
self.mass_vlq = mass_vlq
self.num_vlq = num_vlq
self.var_scale = self.width_tt(cp, mass, g=g_tt)
self.k_res = 2.0
self.k_int = math.sqrt(2... | Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed. | XSecVLQ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XSecVLQ:
"""Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed."""
def __init__(self, cp, mass, mass_vlq,... | stack_v2_sparse_classes_36k_train_022942 | 9,620 | no_license | [
{
"docstring": "Initialize from properties of the Higgs boson and VLQ. Arguments: cp: CP state, 'A' or 'H'. mass: Mass of the heavy Higgs boson, in GeV. mass_vlq: Mass of vector-like quarks, in GeV. g_tt: Reduced coupling of the heavy Higgs boson to top quarks. g_vlq: Coupling of the heavy Higgs boson to vector... | 3 | stack_v2_sparse_classes_30k_train_015313 | Implement the Python class `XSecVLQ` described below.
Class description:
Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed.
Method... | Implement the Python class `XSecVLQ` described below.
Class description:
Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed.
Method... | e6ef12cec5606cbf3e5c8a1224d4170d2ccdbf3b | <|skeleton|>
class XSecVLQ:
"""Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed."""
def __init__(self, cp, mass, mass_vlq,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XSecVLQ:
"""Cross sections for gg -> S -> tt with vector-like quarks. A heavy Higgs boson of a fixed CP state is produced via gluon fusuon. The loop is populated by top quarks and vector-like quarks (VLQ). Multiple VLQ degenerate in mass are allowed."""
def __init__(self, cp, mass, mass_vlq, g_tt=1.0, g_... | the_stack_v2_python_sparse | Analysis/scan_VLQ.py | andrey-popov/pheno-htt | train | 0 |
e5ab5511bfc15c6f36690c752b5cbeb03171476d | [
"context = super(ExhibitionPastListView, self).get_context_data(**kwargs)\ncontext['past'] = 'active'\ncontext['title'] = 'Выставки, которые прошли.'\nreturn context",
"qs = super(ExhibitionPastListView, self).get_queryset()\nqs = qs.filter(date__lt=timezone.now())\nreturn qs"
] | <|body_start_0|>
context = super(ExhibitionPastListView, self).get_context_data(**kwargs)
context['past'] = 'active'
context['title'] = 'Выставки, которые прошли.'
return context
<|end_body_0|>
<|body_start_1|>
qs = super(ExhibitionPastListView, self).get_queryset()
qs =... | List of exhibition which was | ExhibitionPastListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExhibitionPastListView:
"""List of exhibition which was"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
<|body_0|>
def get_queryset(self):
"""Filter exhibition :return: exhibition which was"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_022943 | 5,515 | no_license | [
{
"docstring": "Extends context data :param kwargs: :return: context",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Filter exhibition :return: exhibition which was",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012494 | Implement the Python class `ExhibitionPastListView` described below.
Class description:
List of exhibition which was
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Extends context data :param kwargs: :return: context
- def get_queryset(self): Filter exhibition :return: exhibition which was | Implement the Python class `ExhibitionPastListView` described below.
Class description:
List of exhibition which was
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Extends context data :param kwargs: :return: context
- def get_queryset(self): Filter exhibition :return: exhibition which was
... | 8eb18b831e034302f90585a179110336bb18af45 | <|skeleton|>
class ExhibitionPastListView:
"""List of exhibition which was"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
<|body_0|>
def get_queryset(self):
"""Filter exhibition :return: exhibition which was"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExhibitionPastListView:
"""List of exhibition which was"""
def get_context_data(self, **kwargs):
"""Extends context data :param kwargs: :return: context"""
context = super(ExhibitionPastListView, self).get_context_data(**kwargs)
context['past'] = 'active'
context['title'] ... | the_stack_v2_python_sparse | exhibition/views.py | YevheniiaSmyrnova/butterflies | train | 0 |
90d9ba94b2779fe3901790cb22932ed1e80e98c9 | [
"if x < 0:\n raise Exception('不能输入负数')\nif x == 0:\n return 0\ncur = -5\nwhile True:\n pre = cur\n cur = (cur + x / cur) / 2\n if abs(cur - pre) < 1e-06:\n return cur",
"if x < 0:\n raise Exception('不能输入负数')\nif x == 0:\n return 0\ncur = 1\nwhile True:\n pre = cur\n cur = (cur + ... | <|body_start_0|>
if x < 0:
raise Exception('不能输入负数')
if x == 0:
return 0
cur = -5
while True:
pre = cur
cur = (cur + x / cur) / 2
if abs(cur - pre) < 1e-06:
return cur
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt1(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
raise Exception('不能输入负数')
if x == 0:
... | stack_v2_sparse_classes_36k_train_022944 | 1,203 | permissive | [
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "mySqrt1",
"signature": "def mySqrt1(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005326 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt1(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): :type x: int :rtype: int
- def mySqrt1(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rt... | b484ae4c4e9f9186232e31f2de11720aebb42968 | <|skeleton|>
class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def mySqrt1(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x):
""":type x: int :rtype: int"""
if x < 0:
raise Exception('不能输入负数')
if x == 0:
return 0
cur = -5
while True:
pre = cur
cur = (cur + x / cur) / 2
if abs(cur - pre) < 1e-06:
... | the_stack_v2_python_sparse | 17-二分查找/0069_1.py | Sytx74/LeetCode-Solution-Python | train | 0 | |
910c7250523eb60873493430ae0b98467391f749 | [
"res = []\nself.helper(res, [], sorted(candidates), target)\nreturn res",
"if target < 0:\n return\nif target == 0:\n if part_res in total_res:\n return\n total_res.append(part_res)\n return\nfor i, e in enumerate(candidates):\n if e > target:\n return\n self.helper(total_res, part... | <|body_start_0|>
res = []
self.helper(res, [], sorted(candidates), target)
return res
<|end_body_0|>
<|body_start_1|>
if target < 0:
return
if target == 0:
if part_res in total_res:
return
total_res.append(part_res)
... | Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, candidates, target):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, candidates, target):
"""Solution function description"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_022945 | 941 | permissive | [
{
"docstring": "Solution function description",
"name": "func",
"signature": "def func(self, candidates, target)"
},
{
"docstring": "Solution function description",
"name": "helper",
"signature": "def helper(self, total_res, part_res, candidates, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008522 | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, candidates, target): Solution function description
- def helper(self, total_res, part_res, candidates, target): Solution function description | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def func(self, candidates, target): Solution function description
- def helper(self, total_res, part_res, candidates, target): Solution function description
<|skeleton|>
class Solution:
... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def func(self, candidates, target):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, candidates, target):
"""Solution function description"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def func(self, candidates, target):
"""Solution function description"""
res = []
self.helper(res, [], sorted(candidates), target)
return res
def helper(self, total_res, part_res, candidates, target):
"""Solution function de... | the_stack_v2_python_sparse | 40.Combination.Sum.2/1.py | cerebrumaize/leetcode | train | 0 |
83c7988a689d6a9baadb732e84229bdea20fe01b | [
"df_copy = df.copy(deep=True)\nfor col in df_copy.columns:\n if df_copy[col].dtype == np.dtype('O'):\n df_copy[col] = df[col].apply(lambda x: re.sub('[^\\\\x00-\\\\x7f]', '', x) if isinstance(x, six.string_types) else x)\nreturn df_copy",
"import IPython\nif not isinstance(data, dict) or not all((isinst... | <|body_start_0|>
df_copy = df.copy(deep=True)
for col in df_copy.columns:
if df_copy[col].dtype == np.dtype('O'):
df_copy[col] = df[col].apply(lambda x: re.sub('[^\\x00-\\x7f]', '', x) if isinstance(x, six.string_types) else x)
return df_copy
<|end_body_0|>
<|body_st... | Represents A facets overview. | FacetsOverview | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacetsOverview:
"""Represents A facets overview."""
def _remove_nonascii(self, df):
"""Make copy and remove non-ascii characters from it."""
<|body_0|>
def plot(self, data):
"""Plots an overview in a list of dataframes Args: data: a dictionary with key the name, ... | stack_v2_sparse_classes_36k_train_022946 | 3,449 | permissive | [
{
"docstring": "Make copy and remove non-ascii characters from it.",
"name": "_remove_nonascii",
"signature": "def _remove_nonascii(self, df)"
},
{
"docstring": "Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.",
"name": "plot",
... | 2 | null | Implement the Python class `FacetsOverview` described below.
Class description:
Represents A facets overview.
Method signatures and docstrings:
- def _remove_nonascii(self, df): Make copy and remove non-ascii characters from it.
- def plot(self, data): Plots an overview in a list of dataframes Args: data: a dictionar... | Implement the Python class `FacetsOverview` described below.
Class description:
Represents A facets overview.
Method signatures and docstrings:
- def _remove_nonascii(self, df): Make copy and remove non-ascii characters from it.
- def plot(self, data): Plots an overview in a list of dataframes Args: data: a dictionar... | 8bf007da3e43096aa3a3dca158fc56b286ba6f5c | <|skeleton|>
class FacetsOverview:
"""Represents A facets overview."""
def _remove_nonascii(self, df):
"""Make copy and remove non-ascii characters from it."""
<|body_0|>
def plot(self, data):
"""Plots an overview in a list of dataframes Args: data: a dictionary with key the name, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacetsOverview:
"""Represents A facets overview."""
def _remove_nonascii(self, df):
"""Make copy and remove non-ascii characters from it."""
df_copy = df.copy(deep=True)
for col in df_copy.columns:
if df_copy[col].dtype == np.dtype('O'):
df_copy[col] = ... | the_stack_v2_python_sparse | google/datalab/ml/_fasets.py | googledatalab/pydatalab | train | 200 |
1bef05abcb184ab3359113381af031fe1e35c270 | [
"super(SimpleCNN, self).__init__()\ncnn = []\nfor i in range(n_hidden_layers):\n cnn.append(torch.nn.Conv2d(in_channels=n_in_channels, out_channels=n_kernels, kernel_size=kernel_size, bias=True, padding=int(kernel_size / 2)))\n cnn.append(torch.nn.ReLU())\n n_in_channels = n_kernels\nself.hidden_layers = t... | <|body_start_0|>
super(SimpleCNN, self).__init__()
cnn = []
for i in range(n_hidden_layers):
cnn.append(torch.nn.Conv2d(in_channels=n_in_channels, out_channels=n_kernels, kernel_size=kernel_size, bias=True, padding=int(kernel_size / 2)))
cnn.append(torch.nn.ReLU())
... | SimpleCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleCNN:
def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7):
"""Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hyperparameters"""
<|body_0|>
def forward(self, x):
"""Apply CNN to input `x` o... | stack_v2_sparse_classes_36k_train_022947 | 2,028 | no_license | [
{
"docstring": "Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hyperparameters",
"name": "__init__",
"signature": "def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7)"
},
{
"docstring": "Apply CNN to input `x` of shape (N,... | 2 | stack_v2_sparse_classes_30k_train_018622 | Implement the Python class `SimpleCNN` described below.
Class description:
Implement the SimpleCNN class.
Method signatures and docstrings:
- def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7): Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hy... | Implement the Python class `SimpleCNN` described below.
Class description:
Implement the SimpleCNN class.
Method signatures and docstrings:
- def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7): Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hy... | 26ea3306ff989de94414d50708ae30171f48ef53 | <|skeleton|>
class SimpleCNN:
def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7):
"""Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hyperparameters"""
<|body_0|>
def forward(self, x):
"""Apply CNN to input `x` o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleCNN:
def __init__(self, n_in_channels: int=1, n_hidden_layers: int=3, n_kernels: int=32, kernel_size: int=7):
"""Simple CNN with `n_hidden_layers`, `n_kernels`, and `kernel_size` as hyperparameters"""
super(SimpleCNN, self).__init__()
cnn = []
for i in range(n_hidden_laye... | the_stack_v2_python_sparse | Programming-in-Python-II/example_project/architectures.py | diabeticwizard10/programming-in-python | train | 0 | |
afbeb7216f984d5977c15a8fa1789f16048282c3 | [
"result = [[r0, c0]]\nk = 1\nwhile len(result) < R * C:\n if 0 <= r0 < R:\n for j in range(max(0, c0 + 1), min(c0 + 1 + k, C)):\n result.append([r0, j])\n c0 = c0 + k\n print('1', r0, c0, k)\n if 0 <= c0 < C:\n for i in range(max(r0 + 1, 0), min(r0 + 1 + k, R)):\n res... | <|body_start_0|>
result = [[r0, c0]]
k = 1
while len(result) < R * C:
if 0 <= r0 < R:
for j in range(max(0, c0 + 1), min(c0 + 1 + k, C)):
result.append([r0, j])
c0 = c0 + k
print('1', r0, c0, k)
if 0 <= c0 < C:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
<|body_0|>
def spiralMatrixIII_1(self, R, C, r0, c0):
"""180ms :param R: :param C: :param r0: :param c0: :return:"""
<... | stack_v2_sparse_classes_36k_train_022948 | 3,291 | no_license | [
{
"docstring": ":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS",
"name": "spiralMatrixIII",
"signature": "def spiralMatrixIII(self, R, C, r0, c0)"
},
{
"docstring": "180ms :param R: :param C: :param r0: :param c0: :return:",
"name": "spiralMatrixIII_1",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralMatrixIII(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS
- def spiralMatrixIII_1(self, R, C, r0, c0): 180ms :p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralMatrixIII(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS
- def spiralMatrixIII_1(self, R, C, r0, c0): 180ms :p... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
<|body_0|>
def spiralMatrixIII_1(self, R, C, r0, c0):
"""180ms :param R: :param C: :param r0: :param c0: :return:"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
result = [[r0, c0]]
k = 1
while len(result) < R * C:
if 0 <= r0 < R:
for j in range(max(0, c0 + 1), min(c0 + ... | the_stack_v2_python_sparse | SpiralMatrixIII_MID_889.py | 953250587/leetcode-python | train | 2 | |
2d1dd913f1d0d9ea39ec367f241513f7b0e4109d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosLobApp()",
"from .ios_device_type import IosDeviceType\nfrom .ios_minimum_operating_system import IosMinimumOperatingSystem\nfrom .mobile_lob_app import MobileLobApp\nfrom .ios_device_type import IosDeviceType\nfrom .ios_minimum_ope... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosLobApp()
<|end_body_0|>
<|body_start_1|>
from .ios_device_type import IosDeviceType
from .ios_minimum_operating_system import IosMinimumOperatingSystem
from .mobile_lob_app im... | Contains properties and inherited properties for iOS Line Of Business apps. | IosLobApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosLobApp:
"""Contains properties and inherited properties for iOS Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosLobApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_36k_train_022949 | 4,054 | 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: IosLobApp",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `IosLobApp` described below.
Class description:
Contains properties and inherited properties for iOS Line Of Business apps.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosLobApp: Creates a new instance of the appropriate c... | Implement the Python class `IosLobApp` described below.
Class description:
Contains properties and inherited properties for iOS Line Of Business apps.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosLobApp: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosLobApp:
"""Contains properties and inherited properties for iOS Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosLobApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IosLobApp:
"""Contains properties and inherited properties for iOS Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosLobApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to ... | the_stack_v2_python_sparse | msgraph/generated/models/ios_lob_app.py | microsoftgraph/msgraph-sdk-python | train | 135 |
069971931c677493ff245fb14d88316554475f90 | [
"super(Encoder, self).__init__()\nself.hidden_dim = hidden_dim // 2 if bidir else hidden_dim\nself.n_layers = n_layers * 2 if bidir else n_layers\nself.bidir = bidir\nself.lstm = nn.LSTM(input_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)\nself.h0 = Parameter(torch.zeros(1), requires_grad=Fa... | <|body_start_0|>
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim // 2 if bidir else hidden_dim
self.n_layers = n_layers * 2 if bidir else n_layers
self.bidir = bidir
self.lstm = nn.LSTM(input_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)
... | Encoder class for Pointer-Net | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, input_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers... | stack_v2_sparse_classes_36k_train_022950 | 2,546 | no_license | [
{
"docstring": "Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for LSTMs :param float dropout: Float between 0-1 :param bool bidir: Bidirectional",
"name": "__init__",
"signature": "d... | 3 | null | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden... | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden... | bc32142d059add14d550c8980adf3672485d4a98 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, input_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, input_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor input_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for LSTMs :p... | the_stack_v2_python_sparse | Others/PtrNet/Components/Encoder.py | cvlab-stonybrook/S2N_Release | train | 0 |
0d38f9e18c8ce70021ca88784cdc900323a691ac | [
"if low < high:\n pi = self.partition(lst, low, high)\n self.quick_sort(lst, low, pi - 1)\n self.quick_sort(lst, pi + 1, high)",
"pivot = int((low + high) / 2)\nlst[pivot], lst[high] = (lst[high], lst[pivot])\npivot = high\ni = low - 1\nfor j in range(low, high):\n if lst[j] <= lst[pivot]:\n i ... | <|body_start_0|>
if low < high:
pi = self.partition(lst, low, high)
self.quick_sort(lst, low, pi - 1)
self.quick_sort(lst, pi + 1, high)
<|end_body_0|>
<|body_start_1|>
pivot = int((low + high) / 2)
lst[pivot], lst[high] = (lst[high], lst[pivot])
pivo... | QuickSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuickSort:
def quick_sort(self, lst, low, high):
"""Takes a list and sorts it"""
<|body_0|>
def partition(self, lst, low, high):
"""Splits the list by a pivot point Swaps high number from right with low number from left and returns the pivot point"""
<|body_1... | stack_v2_sparse_classes_36k_train_022951 | 1,451 | no_license | [
{
"docstring": "Takes a list and sorts it",
"name": "quick_sort",
"signature": "def quick_sort(self, lst, low, high)"
},
{
"docstring": "Splits the list by a pivot point Swaps high number from right with low number from left and returns the pivot point",
"name": "partition",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_017523 | Implement the Python class `QuickSort` described below.
Class description:
Implement the QuickSort class.
Method signatures and docstrings:
- def quick_sort(self, lst, low, high): Takes a list and sorts it
- def partition(self, lst, low, high): Splits the list by a pivot point Swaps high number from right with low nu... | Implement the Python class `QuickSort` described below.
Class description:
Implement the QuickSort class.
Method signatures and docstrings:
- def quick_sort(self, lst, low, high): Takes a list and sorts it
- def partition(self, lst, low, high): Splits the list by a pivot point Swaps high number from right with low nu... | 687f7b91404fd0f32e8dfc4e76ea9534e98d1c50 | <|skeleton|>
class QuickSort:
def quick_sort(self, lst, low, high):
"""Takes a list and sorts it"""
<|body_0|>
def partition(self, lst, low, high):
"""Splits the list by a pivot point Swaps high number from right with low number from left and returns the pivot point"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuickSort:
def quick_sort(self, lst, low, high):
"""Takes a list and sorts it"""
if low < high:
pi = self.partition(lst, low, high)
self.quick_sort(lst, low, pi - 1)
self.quick_sort(lst, pi + 1, high)
def partition(self, lst, low, high):
"""Spli... | the_stack_v2_python_sparse | Final_Capstone_Projects/Classic Algorithms/QuickSort.py | EthanShapiro/PythonCompleteCourse | train | 0 | |
6309dff27da1287bf9ee022f37a09445b542520c | [
"parameters = super().parameters()\nparameters['resize_type'].update_default_value('standard')\nparameters.update({'metadata': DictValue(description='Metadata for inference'), 'threshold': NumericalValue(description='Threshold used to classify anomaly')})\nreturn parameters",
"normalized = (targets - threshold) /... | <|body_start_0|>
parameters = super().parameters()
parameters['resize_type'].update_default_value('standard')
parameters.update({'metadata': DictValue(description='Metadata for inference'), 'threshold': NumericalValue(description='Threshold used to classify anomaly')})
return parameters
... | Wrapper for anomaly tasks. | AnomalyBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
<|body_0|>
def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarray, float], max_val: Union[np.nd... | stack_v2_sparse_classes_36k_train_022952 | 1,617 | permissive | [
{
"docstring": "Dictionary containing model parameters.",
"name": "parameters",
"signature": "def parameters(cls)"
},
{
"docstring": "Apply min-max normalization and shift the values such that the threshold value is centered at 0.5.",
"name": "_normalize",
"signature": "def _normalize(ta... | 2 | stack_v2_sparse_classes_30k_train_009418 | Implement the Python class `AnomalyBase` described below.
Class description:
Wrapper for anomaly tasks.
Method signatures and docstrings:
- def parameters(cls): Dictionary containing model parameters.
- def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarr... | Implement the Python class `AnomalyBase` described below.
Class description:
Wrapper for anomaly tasks.
Method signatures and docstrings:
- def parameters(cls): Dictionary containing model parameters.
- def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarr... | 80454808b38727e358e8b880043eeac0f18152fb | <|skeleton|>
class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
<|body_0|>
def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarray, float], max_val: Union[np.nd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
parameters = super().parameters()
parameters['resize_type'].update_default_value('standard')
parameters.update({'metadata': DictValue(description='Metadata for ... | the_stack_v2_python_sparse | src/otx/algorithms/anomaly/adapters/anomalib/exportable_code/base.py | openvinotoolkit/training_extensions | train | 397 |
d3dde0fc668294af4c3e0eb15a260e89dcf7a52c | [
"login_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018822125828'\ndata = {'email': '15899962704', 'icode': '', 'origURL': 'http://www.renren.com/home', 'domain': 'renren.com', 'key_id': '1', 'captcha_type': 'web_login', 'password': '2c18e5058b11daacfa19994395734b2490de52f533def51d9eb68e009710a... | <|body_start_0|>
login_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018822125828'
data = {'email': '15899962704', 'icode': '', 'origURL': 'http://www.renren.com/home', 'domain': 'renren.com', 'key_id': '1', 'captcha_type': 'web_login', 'password': '2c18e5058b11daacfa19994395734b2490... | LoginSpider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginSpider:
def start_requests(self):
"""人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码"""
<|body_0|>
def parse(self, response):
"""爬虫 start_requests 方法的回调函数。 返回的是 JSON 数据,解析 response 将数据取出,如果登录失败,显示其中的 failDescriptio... | stack_v2_sparse_classes_36k_train_022953 | 2,373 | permissive | [
{
"docstring": "人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "爬虫 start_requests 方法的回调函数。 返回的是 JSON 数据,解析 response 将数据取出,如果登录失败,显示其中的 failDescription 值。 如果这个字段不... | 3 | stack_v2_sparse_classes_30k_val_000526 | Implement the Python class `LoginSpider` described below.
Class description:
Implement the LoginSpider class.
Method signatures and docstrings:
- def start_requests(self): 人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码
- def parse(self, response): 爬虫 start_requests 方法的... | Implement the Python class `LoginSpider` described below.
Class description:
Implement the LoginSpider class.
Method signatures and docstrings:
- def start_requests(self): 人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码
- def parse(self, response): 爬虫 start_requests 方法的... | e851524917b60e7308172bc235597b7c578882cc | <|skeleton|>
class LoginSpider:
def start_requests(self):
"""人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码"""
<|body_0|>
def parse(self, response):
"""爬虫 start_requests 方法的回调函数。 返回的是 JSON 数据,解析 response 将数据取出,如果登录失败,显示其中的 failDescriptio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginSpider:
def start_requests(self):
"""人人网登录操作 使用 yield 与 scrapy 的 FormRequest 提交用户登录信息,并使用回调方法访问 parse 来接下来处理返回的代码。 注意:测试时请使用您的用户名与密码"""
login_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018822125828'
data = {'email': '15899962704', 'icode': '', 'origURL': 'ht... | the_stack_v2_python_sparse | 9th_week/homework/作业2/renren/renren/spiders/login.py | luhuadong/Python_Learning | train | 1 | |
6cac0f31537727d617227d04df999bd63cf5b7a7 | [
"root_key = camel_to_snake_case(cls.__name__)\n\ndef find_errors(metadata=metadata, path_key=root_key):\n \"\"\"Generator for vmware attributes errors\n\n for each attribute in 'metadata' gets relevant values from vmware\n 'value' and checks them with restrictions and regexs\n \"... | <|body_start_0|>
root_key = camel_to_snake_case(cls.__name__)
def find_errors(metadata=metadata, path_key=root_key):
"""Generator for vmware attributes errors
for each attribute in 'metadata' gets relevant values from vmware
'value' and checks them w... | VmwareAttributesRestriction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmw... | stack_v2_sparse_classes_36k_train_022954 | 13,635 | permissive | [
{
"docstring": "Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmware attributes data(value) object :type data: list|dict :retruns: func -- generator w... | 2 | null | Implement the Python class `VmwareAttributesRestriction` described below.
Class description:
Implement the VmwareAttributesRestriction class.
Method signatures and docstrings:
- def check_data(cls, models, metadata, data): Check cluster vmware attributes data :param models: objects which represent models in restricti... | Implement the Python class `VmwareAttributesRestriction` described below.
Class description:
Implement the VmwareAttributesRestriction class.
Method signatures and docstrings:
- def check_data(cls, models, metadata, data): Check cluster vmware attributes data :param models: objects which represent models in restricti... | 0e09dce510927f2cc490b898e5fe3f813bd791be | <|skeleton|>
class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmwareAttributesRestriction:
def check_data(cls, models, metadata, data):
"""Check cluster vmware attributes data :param models: objects which represent models in restrictions :type models: dict :param metadata: vmware attributes metadata object :type metadata: list|dict :param data: vmware attributes... | the_stack_v2_python_sparse | nailgun/nailgun/utils/restrictions.py | mba811/fuel-web | train | 1 | |
42fd77035457445f78f3bf09751b4c08d930bb40 | [
"editor = self.window.active_editor\nif editor is not None:\n self.window.edit(editor.obj, type(editor), use_existing=False)",
"if new is not None:\n self.enabled = True\nelse:\n self.enabled = False"
] | <|body_start_0|>
editor = self.window.active_editor
if editor is not None:
self.window.edit(editor.obj, type(editor), use_existing=False)
<|end_body_0|>
<|body_start_1|>
if new is not None:
self.enabled = True
else:
self.enabled = False
<|end_body_1|>... | An action that opens a new workbench window. | NewEditorAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewEditorAction:
"""An action that opens a new workbench window."""
def perform(self, event):
"""Perform the action"""
<|body_0|>
def _active_editor_changed_for_window(self, new):
"""Enables the action if the window has one or more open editors"""
<|body_... | stack_v2_sparse_classes_36k_train_022955 | 8,852 | permissive | [
{
"docstring": "Perform the action",
"name": "perform",
"signature": "def perform(self, event)"
},
{
"docstring": "Enables the action if the window has one or more open editors",
"name": "_active_editor_changed_for_window",
"signature": "def _active_editor_changed_for_window(self, new)"
... | 2 | stack_v2_sparse_classes_30k_train_018130 | Implement the Python class `NewEditorAction` described below.
Class description:
An action that opens a new workbench window.
Method signatures and docstrings:
- def perform(self, event): Perform the action
- def _active_editor_changed_for_window(self, new): Enables the action if the window has one or more open edito... | Implement the Python class `NewEditorAction` described below.
Class description:
An action that opens a new workbench window.
Method signatures and docstrings:
- def perform(self, event): Perform the action
- def _active_editor_changed_for_window(self, new): Enables the action if the window has one or more open edito... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class NewEditorAction:
"""An action that opens a new workbench window."""
def perform(self, event):
"""Perform the action"""
<|body_0|>
def _active_editor_changed_for_window(self, new):
"""Enables the action if the window has one or more open editors"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewEditorAction:
"""An action that opens a new workbench window."""
def perform(self, event):
"""Perform the action"""
editor = self.window.active_editor
if editor is not None:
self.window.edit(editor.obj, type(editor), use_existing=False)
def _active_editor_chang... | the_stack_v2_python_sparse | puddle/workbench/workbench_action.py | rwl/puddle | train | 2 |
87acdf4adb9dea268d206d434b48dab8cdec56f2 | [
"plugin = LinearWeights(y0val=20.0, ynval=2.0)\nself.assertEqual(plugin.y0val, 20.0)\nself.assertEqual(plugin.ynval, 2.0)",
"msg = 'y0val must be a float >= 0.0'\nwith self.assertRaisesRegex(ValueError, msg):\n LinearWeights(y0val=-10.0, ynval=2.0)"
] | <|body_start_0|>
plugin = LinearWeights(y0val=20.0, ynval=2.0)
self.assertEqual(plugin.y0val, 20.0)
self.assertEqual(plugin.ynval, 2.0)
<|end_body_0|>
<|body_start_1|>
msg = 'y0val must be a float >= 0.0'
with self.assertRaisesRegex(ValueError, msg):
LinearWeights(y0... | Test the __init__ method. | Test__init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
<|body_0|>
def test_fails_y0val_less_than_zero(self):
"""Test it raises a Value Error if y0val less than zero."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_022956 | 7,404 | permissive | [
{
"docstring": "Test values of y0val and ynval are set correctly",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test it raises a Value Error if y0val less than zero.",
"name": "test_fails_y0val_less_than_zero",
"signature": "def test_fails_y0val_less_than_... | 2 | null | Implement the Python class `Test__init__` described below.
Class description:
Test the __init__ method.
Method signatures and docstrings:
- def test_basic(self): Test values of y0val and ynval are set correctly
- def test_fails_y0val_less_than_zero(self): Test it raises a Value Error if y0val less than zero. | Implement the Python class `Test__init__` described below.
Class description:
Test the __init__ method.
Method signatures and docstrings:
- def test_basic(self): Test values of y0val and ynval are set correctly
- def test_fails_y0val_less_than_zero(self): Test it raises a Value Error if y0val less than zero.
<|skele... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
<|body_0|>
def test_fails_y0val_less_than_zero(self):
"""Test it raises a Value Error if y0val less than zero."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
plugin = LinearWeights(y0val=20.0, ynval=2.0)
self.assertEqual(plugin.y0val, 20.0)
self.assertEqual(plugin.ynval, 2.0)
def test_fails_y0val_less_... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py | metoppv/improver | train | 101 |
11ef01f03025f4049d8a9c4b631680f48a632216 | [
"self.operands: List[Operand] = list(operands)\nfor i in range(len(self.operands)):\n self.operands[i] = Operand.validate_operand(self.operands[i])\nsuper().__init__()",
"incomplete_expression = False\nfor operand in self.operands:\n if not issubclass(type(operand), Operand):\n raise RuntimeError(f'O... | <|body_start_0|>
self.operands: List[Operand] = list(operands)
for i in range(len(self.operands)):
self.operands[i] = Operand.validate_operand(self.operands[i])
super().__init__()
<|end_body_0|>
<|body_start_1|>
incomplete_expression = False
for operand in self.opera... | And operator class for filtering JumpStart content. | And | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class And:
"""And operator class for filtering JumpStart content."""
def __init__(self, *operands: Union[Operand, str]) -> None:
"""Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_022957 | 16,623 | permissive | [
{
"docstring": "Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated.",
"name": "__init__",
"signature": "def __init__(self, *operands: Union[Operand, str]) -> None"
},
{
"docstring": "Evaluates operator. Raises: Runtime... | 3 | stack_v2_sparse_classes_30k_train_001871 | Implement the Python class `And` described below.
Class description:
And operator class for filtering JumpStart content.
Method signatures and docstrings:
- def __init__(self, *operands: Union[Operand, str]) -> None: Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the o... | Implement the Python class `And` described below.
Class description:
And operator class for filtering JumpStart content.
Method signatures and docstrings:
- def __init__(self, *operands: Union[Operand, str]) -> None: Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the o... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class And:
"""And operator class for filtering JumpStart content."""
def __init__(self, *operands: Union[Operand, str]) -> None:
"""Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class And:
"""And operator class for filtering JumpStart content."""
def __init__(self, *operands: Union[Operand, str]) -> None:
"""Instantiates And object. Args: operand (Operand): Operand for And-ing. Raises: RuntimeError: If the operands cannot be validated."""
self.operands: List[Operand] =... | the_stack_v2_python_sparse | src/sagemaker/jumpstart/filters.py | aws/sagemaker-python-sdk | train | 2,050 |
88a65006985360161006052c8ece162013e54a3c | [
"self.name = mtc_input.programName\nself.num = 0\nself.ranObj = []\ni = 0\nwhile i < mtc_input.num_lines:\n if self.num > MAX_VARIABLE_ARRAY_SIZE:\n raise InputError('Too many variables in %(cn)s' % {'cn': mtc_input.name()})\n size = len(mtc_input.line_set(i))\n tok002 = mtc_input.line_set(i)[2]\n ... | <|body_start_0|>
self.name = mtc_input.programName
self.num = 0
self.ranObj = []
i = 0
while i < mtc_input.num_lines:
if self.num > MAX_VARIABLE_ARRAY_SIZE:
raise InputError('Too many variables in %(cn)s' % {'cn': mtc_input.name()})
size = ... | Randomized container for entire program | RandomAll | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomAll:
"""Randomized container for entire program"""
def __init__(self, mtc_input):
"""Instantiate"""
<|body_0|>
def __repr__(self):
"""Print the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name = mtc_input.programName
... | stack_v2_sparse_classes_36k_train_022958 | 40,703 | permissive | [
{
"docstring": "Instantiate",
"name": "__init__",
"signature": "def __init__(self, mtc_input)"
},
{
"docstring": "Print the class",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014009 | Implement the Python class `RandomAll` described below.
Class description:
Randomized container for entire program
Method signatures and docstrings:
- def __init__(self, mtc_input): Instantiate
- def __repr__(self): Print the class | Implement the Python class `RandomAll` described below.
Class description:
Randomized container for entire program
Method signatures and docstrings:
- def __init__(self, mtc_input): Instantiate
- def __repr__(self): Print the class
<|skeleton|>
class RandomAll:
"""Randomized container for entire program"""
... | 0c0af95cc581e39ec438313b235e2c0c127ffb6c | <|skeleton|>
class RandomAll:
"""Randomized container for entire program"""
def __init__(self, mtc_input):
"""Instantiate"""
<|body_0|>
def __repr__(self):
"""Print the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomAll:
"""Randomized container for entire program"""
def __init__(self, mtc_input):
"""Instantiate"""
self.name = mtc_input.programName
self.num = 0
self.ranObj = []
i = 0
while i < mtc_input.num_lines:
if self.num > MAX_VARIABLE_ARRAY_SIZE:... | the_stack_v2_python_sparse | pyDAG3/Apps/genGorilla/genGorilla.py | davegutz/pyDAGx | train | 0 |
5c85824e71bbb0ec98db509b64452e5e645a1507 | [
"r = LRUCache(2)\nr.put(2, 1)\nr.put(1, 1)\nr.put(2, 3)\nr.put(4, 1)\nself.assertEqual(-1, r.get(1))\nself.assertEqual(3, r.get(2))",
"r = LRUCache(2)\nr.put(1, 1)\nr.put(2, 2)\nself.assertEqual(1, r.get(1))\nr.put(3, 3)\nself.assertEqual(-1, r.get(2))\nr.put(4, 4)\nself.assertEqual(-1, r.get(1))\nself.assertEqua... | <|body_start_0|>
r = LRUCache(2)
r.put(2, 1)
r.put(1, 1)
r.put(2, 3)
r.put(4, 1)
self.assertEqual(-1, r.get(1))
self.assertEqual(3, r.get(2))
<|end_body_0|>
<|body_start_1|>
r = LRUCache(2)
r.put(1, 1)
r.put(2, 2)
self.assertEqual(... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test1(self):
"""["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]"""
<|body_0|>
def test2(self):
"""["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]""... | stack_v2_sparse_classes_36k_train_022959 | 1,845 | no_license | [
{
"docstring": "[\"LRUCache\", \"put\", \"put\", \"put\", \"put\", \"get\", \"get\"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "[\"LRUCache\", \"put\", \"put\", \"put\", \"put\", \"get\", \"get\"] [[2], [2, 1], [1, 1], [2,... | 4 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): ["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]
- def test2(self): ["LRUCache", "put", "put", "put", "put", "get",... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): ["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]
- def test2(self): ["LRUCache", "put", "put", "put", "put", "get",... | 248b620791611001ebb471dcf8284437264b2f20 | <|skeleton|>
class Test:
def test1(self):
"""["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]"""
<|body_0|>
def test2(self):
"""["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test1(self):
"""["LRUCache", "put", "put", "put", "put", "get", "get"] [[2], [2, 1], [1, 1], [2, 3], [4, 1], [1], [2]]"""
r = LRUCache(2)
r.put(2, 1)
r.put(1, 1)
r.put(2, 3)
r.put(4, 1)
self.assertEqual(-1, r.get(1))
self.assertEqual(3,... | the_stack_v2_python_sparse | 146_lru_cache/_0.py | chxj1992/leetcode-exercise | train | 0 | |
7c441ff14a0ae9d4cb81b15eaf42a7793bebb96a | [
"super().__init__()\nself.logger = logging.getLogger(KNeighborsDetector.__name__)\nself._n_neighbors = n_neighbors\nself._weights = weights\nself._algorithm = algorithm\nself._leaf_size = leaf_size\nself._metric = metric\nself._p = p\nself._metric_params = metric_params\nself._n_jobs = n_jobs\nself.model = None\nse... | <|body_start_0|>
super().__init__()
self.logger = logging.getLogger(KNeighborsDetector.__name__)
self._n_neighbors = n_neighbors
self._weights = weights
self._algorithm = algorithm
self._leaf_size = leaf_size
self._metric = metric
self._p = p
self.... | KNeighborsDetector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNeighborsDetector:
def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs):
"""Classifier implementing the k-nearest neighbors vote Parameters ---------- :param n_neighbors: int, default=5 N... | stack_v2_sparse_classes_36k_train_022960 | 4,134 | permissive | [
{
"docstring": "Classifier implementing the k-nearest neighbors vote Parameters ---------- :param n_neighbors: int, default=5 Number of neighbors to use by default for kneighbors queries. :param weights:{‘uniform’, ‘distance’} or callable, default=’uniform’ weight function used in prediction. :param algorithm:{... | 4 | stack_v2_sparse_classes_30k_train_020366 | Implement the Python class `KNeighborsDetector` described below.
Class description:
Implement the KNeighborsDetector class.
Method signatures and docstrings:
- def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs): Clas... | Implement the Python class `KNeighborsDetector` described below.
Class description:
Implement the KNeighborsDetector class.
Method signatures and docstrings:
- def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs): Clas... | 9346979b9a3723349a8248389cc9ca0cf01ded0f | <|skeleton|>
class KNeighborsDetector:
def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs):
"""Classifier implementing the k-nearest neighbors vote Parameters ---------- :param n_neighbors: int, default=5 N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNeighborsDetector:
def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs):
"""Classifier implementing the k-nearest neighbors vote Parameters ---------- :param n_neighbors: int, default=5 Number of neigh... | the_stack_v2_python_sparse | talpa/classifiers/knn.py | proy3189/coding_challenge | train | 0 | |
1f8e3bf4142fbf6429870407b957e1b508fc9a71 | [
"value = self.value.get(name, [])\nif isinstance(value, basestring):\n value = [value]\nreturn SelectPatch.select(value, self.option.get(name, []), False, name, attributes, get_option_attributes, self)",
"from bn import HTMLFragment\nfrom formbuild.internal import _select, check_attributes, html_open\nattribut... | <|body_start_0|>
value = self.value.get(name, [])
if isinstance(value, basestring):
value = [value]
return SelectPatch.select(value, self.option.get(name, []), False, name, attributes, get_option_attributes, self)
<|end_body_0|>
<|body_start_1|>
from bn import HTMLFragment
... | SelectPatch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectPatch:
def dropdown(self, name, attributes=None, get_option_attributes=None):
"""Monkey patch for FormBuild 3.0.3 bug"""
<|body_0|>
def select(value, options, multiple, name, attributes=None, get_option_attributes=None, self=None):
"""This is the same as formbu... | stack_v2_sparse_classes_36k_train_022961 | 3,090 | no_license | [
{
"docstring": "Monkey patch for FormBuild 3.0.3 bug",
"name": "dropdown",
"signature": "def dropdown(self, name, attributes=None, get_option_attributes=None)"
},
{
"docstring": "This is the same as formbuild.internal._select, with two changes.",
"name": "select",
"signature": "def selec... | 2 | stack_v2_sparse_classes_30k_train_011172 | Implement the Python class `SelectPatch` described below.
Class description:
Implement the SelectPatch class.
Method signatures and docstrings:
- def dropdown(self, name, attributes=None, get_option_attributes=None): Monkey patch for FormBuild 3.0.3 bug
- def select(value, options, multiple, name, attributes=None, ge... | Implement the Python class `SelectPatch` described below.
Class description:
Implement the SelectPatch class.
Method signatures and docstrings:
- def dropdown(self, name, attributes=None, get_option_attributes=None): Monkey patch for FormBuild 3.0.3 bug
- def select(value, options, multiple, name, attributes=None, ge... | 8a0dd75b196c0e641bb8b4b20124540aaaa2814b | <|skeleton|>
class SelectPatch:
def dropdown(self, name, attributes=None, get_option_attributes=None):
"""Monkey patch for FormBuild 3.0.3 bug"""
<|body_0|>
def select(value, options, multiple, name, attributes=None, get_option_attributes=None, self=None):
"""This is the same as formbu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelectPatch:
def dropdown(self, name, attributes=None, get_option_attributes=None):
"""Monkey patch for FormBuild 3.0.3 bug"""
value = self.value.get(name, [])
if isinstance(value, basestring):
value = [value]
return SelectPatch.select(value, self.option.get(name, [... | the_stack_v2_python_sparse | src/main/resources/qtools/lib/helpers/form.py | v-makarenko/vtoolsmq | train | 0 | |
8d4a981582b019644c6fc91736897948591cc89f | [
"if n % 2 != 0:\n LOGGER.warn(f'n should be a multiple of 2. Actual values = {n}')\nn = n // 2\nrng = np.random.default_rng(seed)\nbeta_baseline = rng.standard_t(dof_baseline) * scale_baseline\nsigma_state = np.abs(rng.standard_cauchy()) * scale_state\nsigma_district = np.abs(rng.standard_cauchy()) * scale_distr... | <|body_start_0|>
if n % 2 != 0:
LOGGER.warn(f'n should be a multiple of 2. Actual values = {n}')
n = n // 2
rng = np.random.default_rng(seed)
beta_baseline = rng.standard_t(dof_baseline) * scale_baseline
sigma_state = np.abs(rng.standard_cauchy()) * scale_state
... | N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school type. Hyper Parameters: n - total numb... | NSchools | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school ty... | stack_v2_sparse_classes_36k_train_022962 | 6,995 | permissive | [
{
"docstring": "See the class documentation for an explanation of the parameters. :param seed: random number generator seed",
"name": "generate_data",
"signature": "def generate_data(seed: int, n: int=2000, num_states: int=8, num_districts_per_state: int=5, num_types: int=5, dof_baseline: float=3.0, sca... | 2 | null | Implement the Python class `NSchools` described below.
Class description:
N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state... | Implement the Python class `NSchools` described below.
Class description:
N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state... | d69c652fc882ba50f56eb0cfaa3097d3ede295f9 | <|skeleton|>
class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school type. Hyper Par... | the_stack_v2_python_sparse | pplbench/models/n_schools.py | rambam613/pplbench | train | 0 |
265ebf8cd6b3f6dc3cf6767437cbba85a9a41968 | [
"goodschannelgroup_queryset = GoodsChannelGroup.objects.all()\ngs = GoodsChannelGroupSerializer(goodschannelgroup_queryset, many=True)\nreturn Response(gs.data)",
"cate_queryset = GoodsCategory.objects.filter(parent=None)\ngs = GoodsCategorySerializer(cate_queryset, many=True)\nreturn Response(gs.data)"
] | <|body_start_0|>
goodschannelgroup_queryset = GoodsChannelGroup.objects.all()
gs = GoodsChannelGroupSerializer(goodschannelgroup_queryset, many=True)
return Response(gs.data)
<|end_body_0|>
<|body_start_1|>
cate_queryset = GoodsCategory.objects.filter(parent=None)
gs = GoodsCate... | GoodsChannelView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsChannelView:
def get_goodschannelgroup(self, request):
"""获取频道组信息"""
<|body_0|>
def get_goodscategory(self, request):
"""获取一级分类信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
goodschannelgroup_queryset = GoodsChannelGroup.objects.all()
... | stack_v2_sparse_classes_36k_train_022963 | 1,149 | no_license | [
{
"docstring": "获取频道组信息",
"name": "get_goodschannelgroup",
"signature": "def get_goodschannelgroup(self, request)"
},
{
"docstring": "获取一级分类信息",
"name": "get_goodscategory",
"signature": "def get_goodscategory(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007095 | Implement the Python class `GoodsChannelView` described below.
Class description:
Implement the GoodsChannelView class.
Method signatures and docstrings:
- def get_goodschannelgroup(self, request): 获取频道组信息
- def get_goodscategory(self, request): 获取一级分类信息 | Implement the Python class `GoodsChannelView` described below.
Class description:
Implement the GoodsChannelView class.
Method signatures and docstrings:
- def get_goodschannelgroup(self, request): 获取频道组信息
- def get_goodscategory(self, request): 获取一级分类信息
<|skeleton|>
class GoodsChannelView:
def get_goodschannel... | 2df5abda5d1f5c8bd0cfca41feac2e4d68e1f1e9 | <|skeleton|>
class GoodsChannelView:
def get_goodschannelgroup(self, request):
"""获取频道组信息"""
<|body_0|>
def get_goodscategory(self, request):
"""获取一级分类信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoodsChannelView:
def get_goodschannelgroup(self, request):
"""获取频道组信息"""
goodschannelgroup_queryset = GoodsChannelGroup.objects.all()
gs = GoodsChannelGroupSerializer(goodschannelgroup_queryset, many=True)
return Response(gs.data)
def get_goodscategory(self, request):
... | the_stack_v2_python_sparse | meiduo_mall_admin/apps/meiduo_admin/views/channel_views.py | 921957877/meiduo_mall_admin | train | 0 | |
a53cc0ea286a06e1995acfa7240b948b54d52d10 | [
"for i, v in enumerate(nums):\n if i == v:\n return i\nreturn -1",
"length = len(nums)\nleft = 0\nright = length - 1\nwhile left <= right:\n mid = (right + left) // 2\n if mid >= nums[mid]:\n pass\n else:\n pass"
] | <|body_start_0|>
for i, v in enumerate(nums):
if i == v:
return i
return -1
<|end_body_0|>
<|body_start_1|>
length = len(nums)
left = 0
right = length - 1
while left <= right:
mid = (right + left) // 2
if mid >= nums[mi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
"""直接遍历全数据 时间复杂度 O(N)"""
<|body_0|>
def findMagicIndex1(self, nums: List[int]) -> int:
"""因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i, v in enumer... | stack_v2_sparse_classes_36k_train_022964 | 1,706 | no_license | [
{
"docstring": "直接遍历全数据 时间复杂度 O(N)",
"name": "findMagicIndex",
"signature": "def findMagicIndex(self, nums: List[int]) -> int"
},
{
"docstring": "因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN)",
"name": "findMagicIndex1",
"signature": "def findMagicIndex1(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMagicIndex(self, nums: List[int]) -> int: 直接遍历全数据 时间复杂度 O(N)
- def findMagicIndex1(self, nums: List[int]) -> int: 因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMagicIndex(self, nums: List[int]) -> int: 直接遍历全数据 时间复杂度 O(N)
- def findMagicIndex1(self, nums: List[int]) -> int: 因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN)
<|skeleton|>
class Sol... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
"""直接遍历全数据 时间复杂度 O(N)"""
<|body_0|>
def findMagicIndex1(self, nums: List[int]) -> int:
"""因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
"""直接遍历全数据 时间复杂度 O(N)"""
for i, v in enumerate(nums):
if i == v:
return i
return -1
def findMagicIndex1(self, nums: List[int]) -> int:
"""因为是有序数组,可以使用二分法 时间复杂度可以达到 O(lnN)"""
len... | the_stack_v2_python_sparse | 2022/magic_index.py | EachenKuang/LeetCode | train | 28 | |
d8a171b8c2a82b1ea59cb6027c59d1c995dd657b | [
"def helper(p1, p2):\n if p1 and p2:\n return p1.val == p2.val and helper(p1.left, p2.right) and helper(p1.right, p2.left)\n else:\n return p1 is p2\nif root is None:\n return True\nelse:\n return helper(root.left, root.right)",
"if root is None:\n return True\np1 = root.left\np2 = ro... | <|body_start_0|>
def helper(p1, p2):
if p1 and p2:
return p1.val == p2.val and helper(p1.left, p2.right) and helper(p1.right, p2.left)
else:
return p1 is p2
if root is None:
return True
else:
return helper(root.left,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
"""When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetricIterative(self, root):
"""Using it... | stack_v2_sparse_classes_36k_train_022965 | 1,950 | no_license | [
{
"docstring": "When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": "Using iterative :param root: :r... | 2 | stack_v2_sparse_classes_30k_train_008602 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode ... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
"""When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool"""
<|body_0|>
def isSymmetricIterative(self, root):
"""Using it... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
"""When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool"""
def helper(p1, p2):
if p1 and p2:
return p1.val == p2.val a... | the_stack_v2_python_sparse | LeetCodes/DFS/SymmetricTree.py | chutianwen/LeetCodes | train | 0 | |
397e735b5a62ed49e22c9d50970bc0f817a9cac2 | [
"self.data_feature = data_feature\nself.data_index = data_index\nself.mask_data = mask_data\nself.amax_feature = amax_data_feature\nself.amin_feature = amin_data_feature",
"valid_data_mask = eopatch.mask['VALID_DATA'] if self.mask_data else eopatch.mask['IS_DATA']\ndata = eopatch.data[self.data_feature] if self.d... | <|body_start_0|>
self.data_feature = data_feature
self.data_index = data_index
self.mask_data = mask_data
self.amax_feature = amax_data_feature
self.amin_feature = amin_data_feature
<|end_body_0|>
<|body_start_1|>
valid_data_mask = eopatch.mask['VALID_DATA'] if self.mask... | Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `mask_data` flag to `True`. In that case, the `'VALID_DATA'` mask feature is used for masking. If ... | AddMaxMinTemporalIndicesTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMaxMinTemporalIndicesTask:
"""Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `mask_data` flag to `True`. In that case, ... | stack_v2_sparse_classes_36k_train_022966 | 10,624 | permissive | [
{
"docstring": "Task constructor :param data_feature: Name of the feature in data used for computation of max/min. Default is `'NDVI'` :param data_index: Index of to be extracted from last dimension in `data_feature`. If None, last dimension of data array is assumed ot be of size 1 (e.g. as in NDVI). Default is... | 2 | stack_v2_sparse_classes_30k_train_011017 | Implement the Python class `AddMaxMinTemporalIndicesTask` described below.
Class description:
Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `ma... | Implement the Python class `AddMaxMinTemporalIndicesTask` described below.
Class description:
Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `ma... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class AddMaxMinTemporalIndicesTask:
"""Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `mask_data` flag to `True`. In that case, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMaxMinTemporalIndicesTask:
"""Task to compute temporal indices of the maximum and minimum of a data feature This class computes the `argmax` and `argmin` of a data feature in the input eopatch (e.g. NDVI, B4). The data can be masked out by setting the `mask_data` flag to `True`. In that case, the `'VALID_D... | the_stack_v2_python_sparse | features/eolearn/features/temporal_features.py | sentinel-hub/eo-learn | train | 1,072 |
c5c7a6b82df5397cdfc0701acc51f352f6ae92f9 | [
"self.fs_type = fs_type\nself.lun = lun\nself.target_w_w_ns = target_w_w_ns",
"if dictionary is None:\n return None\nfs_type = dictionary.get('fsType')\nlun = dictionary.get('lun')\ntarget_w_w_ns = dictionary.get('targetWWNs')\nreturn cls(fs_type, lun, target_w_w_ns)"
] | <|body_start_0|>
self.fs_type = fs_type
self.lun = lun
self.target_w_w_ns = target_w_w_ns
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
fs_type = dictionary.get('fsType')
lun = dictionary.get('lun')
target_w_w_ns = dictionary.get(... | Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of Fibre Channel target's World Wide Names | PodInfo_PodSpec_VolumeInfo_FC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_FC:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of Fibre Channel target's World Wide Names"... | stack_v2_sparse_classes_36k_train_022967 | 1,791 | permissive | [
{
"docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_FC class",
"name": "__init__",
"signature": "def __init__(self, fs_type=None, lun=None, target_w_w_ns=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represent... | 2 | null | Implement the Python class `PodInfo_PodSpec_VolumeInfo_FC` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of F... | Implement the Python class `PodInfo_PodSpec_VolumeInfo_FC` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of F... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_FC:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of Fibre Channel target's World Wide Names"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PodInfo_PodSpec_VolumeInfo_FC:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_FC' model. Fibre channel volumes Attributes: fs_type (string): TODO: Type description here. lun (int): TODO: Type description here. target_w_w_ns (list of string): Array of Fibre Channel target's World Wide Names"""
def _... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pod_info_pod_spec_volume_info_fc.py | cohesity/management-sdk-python | train | 24 |
f8e56dcab782df4e870963fd31b2fc66de2f498c | [
"super().__init__(pr, git_repo)\nself.pack = pack\nself.branch_metadata = branch_metadata or {}\nself.origin_base_metadata = origin_base_metadata or {}\nself.pr_base_metadata = pr_base_metadata or {}",
"metadata_path = f'{PACKS_DIR}/{pack_id}/{PACK_METADATA_FILE}'\norigin_base_pack_metadata = load_json(metadata_p... | <|body_start_0|>
super().__init__(pr, git_repo)
self.pack = pack
self.branch_metadata = branch_metadata or {}
self.origin_base_metadata = origin_base_metadata or {}
self.pr_base_metadata = pr_base_metadata or {}
<|end_body_0|>
<|body_start_1|>
metadata_path = f'{PACKS_DI... | Conditions that needs metadata files in order to check them. | MetadataCondition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataCondition:
"""Conditions that needs metadata files in order to check them."""
def __init__(self, pack: str, pr: PullRequest, git_repo: Repo, branch_metadata: Optional[Dict]=None, origin_base_metadata: Optional[Dict]=None, pr_base_metadata: Optional[Dict]=None):
"""Args: pack(... | stack_v2_sparse_classes_36k_train_022968 | 29,534 | permissive | [
{
"docstring": "Args: pack(str): pack name. pr(PullRequest): pull request where the metadata pack was changed. git_repo(Repo): git repo object for git API. branch_metadata(dict): Pack's metadata as it appears in the branch. origin_base_metadata(dict): Pack's metadata as it appears in the base (origin/master). p... | 3 | null | Implement the Python class `MetadataCondition` described below.
Class description:
Conditions that needs metadata files in order to check them.
Method signatures and docstrings:
- def __init__(self, pack: str, pr: PullRequest, git_repo: Repo, branch_metadata: Optional[Dict]=None, origin_base_metadata: Optional[Dict]=... | Implement the Python class `MetadataCondition` described below.
Class description:
Conditions that needs metadata files in order to check them.
Method signatures and docstrings:
- def __init__(self, pack: str, pr: PullRequest, git_repo: Repo, branch_metadata: Optional[Dict]=None, origin_base_metadata: Optional[Dict]=... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class MetadataCondition:
"""Conditions that needs metadata files in order to check them."""
def __init__(self, pack: str, pr: PullRequest, git_repo: Repo, branch_metadata: Optional[Dict]=None, origin_base_metadata: Optional[Dict]=None, pr_base_metadata: Optional[Dict]=None):
"""Args: pack(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetadataCondition:
"""Conditions that needs metadata files in order to check them."""
def __init__(self, pack: str, pr: PullRequest, git_repo: Repo, branch_metadata: Optional[Dict]=None, origin_base_metadata: Optional[Dict]=None, pr_base_metadata: Optional[Dict]=None):
"""Args: pack(str): pack na... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/skip_conditions.py | demisto/content | train | 1,023 |
bf33eb786db7a9018921a03bfb7bcc00c8368fbb | [
"link = Link.query.filter_by(id=link_id).first()\nlink_data, errors = self.schema.dump(link)\nif errors:\n current_app.logger.warning(errors)\nresponse_out = {'id': link.id, 'data': link_data, 'url': '/links', 'type': 'link'}\nreturn (response_out, 200)",
"args = convert_args(args)\nlink = Link(url=args.url, d... | <|body_start_0|>
link = Link.query.filter_by(id=link_id).first()
link_data, errors = self.schema.dump(link)
if errors:
current_app.logger.warning(errors)
response_out = {'id': link.id, 'data': link_data, 'url': '/links', 'type': 'link'}
return (response_out, 200)
<|en... | Link resource. | LinkResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkResource:
"""Link resource."""
def get(self, link_id):
"""Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/... | stack_v2_sparse_classes_36k_train_022969 | 3,983 | permissive | [
{
"docstring": "Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { \"data\": { \"clic... | 2 | stack_v2_sparse_classes_30k_train_011396 | Implement the Python class `LinkResource` described below.
Class description:
Link resource.
Method signatures and docstrings:
- def get(self, link_id): Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/ja... | Implement the Python class `LinkResource` described below.
Class description:
Link resource.
Method signatures and docstrings:
- def get(self, link_id): Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/ja... | d4d64c102478623022f68632adff070398a8771f | <|skeleton|>
class LinkResource:
"""Link resource."""
def get(self, link_id):
"""Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkResource:
"""Link resource."""
def get(self, link_id):
"""Get link resource. .. :quickref: Link collection. **Example request**: .. sourcecode:: http GET /links/1 HTTP/1.1 Host: example.com Accept: application/json, text/javascript **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Va... | the_stack_v2_python_sparse | slicr/resources/links.py | travisbyrum/slicr | train | 0 |
9d9ff88390110b0d8e64a934a56dcf5394d2f7a4 | [
"stack: List[List[str, int]] = []\nfor c in s:\n if stack and stack[-1][0] == c:\n stack[-1][1] += 1\n else:\n stack.append([c, 1])\n while stack and stack[-1][1] == k:\n stack.pop()\nreturn ''.join([c * n for c, n in stack])",
"stack = []\nfor c in s:\n if stack and stack[-1][0] ... | <|body_start_0|>
stack: List[List[str, int]] = []
for c in s:
if stack and stack[-1][0] == c:
stack[-1][1] += 1
else:
stack.append([c, 1])
while stack and stack[-1][1] == k:
stack.pop()
return ''.join([c * n for ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
"""05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def removeDuplicates(self, s: str, k: int) -> str:
"""05/20/2022 14:27"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_022970 | 2,302 | no_license | [
{
"docstring": "05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, s: str, k: int) -> str"
},
{
"docstring": "05/20/2022 14:27",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, s: str, ... | 2 | stack_v2_sparse_classes_30k_train_017745 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, s: str, k: int) -> str: 05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)
- def removeDuplicates(self, s: str, k: int) -> str: 05/20/2022 1... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, s: str, k: int) -> str: 05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)
- def removeDuplicates(self, s: str, k: int) -> str: 05/20/2022 1... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
"""05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def removeDuplicates(self, s: str, k: int) -> str:
"""05/20/2022 14:27"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
"""05/05/2021 09:41 Time complexity: O(n) Space complexity: O(n)"""
stack: List[List[str, int]] = []
for c in s:
if stack and stack[-1][0] == c:
stack[-1][1] += 1
else:
... | the_stack_v2_python_sparse | leetcode/solved/1320_Remove_All_Adjacent_Duplicates_in_String_II/solution.py | sungminoh/algorithms | train | 0 | |
a90b03fe212378f95373e2cdd081680bd4d16050 | [
"super().__init__()\nlayers = []\nnum_filts = num_filts * 2 ** n_upsample\nfor _ in range(n_residual):\n layers += [ResidualBlock(num_filts, norm='adain')]\nfor _ in range(n_upsample):\n layers += [torch.nn.Upsample(scale_factor=2), torch.nn.Conv2d(num_filts, num_filts // 2, 5, stride=1, padding=2), torch.nn.... | <|body_start_0|>
super().__init__()
layers = []
num_filts = num_filts * 2 ** n_upsample
for _ in range(n_residual):
layers += [ResidualBlock(num_filts, norm='adain')]
for _ in range(n_upsample):
layers += [torch.nn.Upsample(scale_factor=2), torch.nn.Conv2d... | Simple Decoder to convert a style encoding and a content encoding into an image | Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Simple Decoder to convert a style encoding and a content encoding into an image"""
def __init__(self, out_channels=3, num_filts=64, n_residual=3, n_upsample=2, style_dim=8):
"""Parameters ---------- out_channels : int number of image channels to generate num_filts : int n... | stack_v2_sparse_classes_36k_train_022971 | 16,260 | permissive | [
{
"docstring": "Parameters ---------- out_channels : int number of image channels to generate num_filts : int number if filters n_residual : int number of residual blocks n_upsample : int number of upsampling blocks style_dim : int size of the style encoding",
"name": "__init__",
"signature": "def __ini... | 4 | null | Implement the Python class `Decoder` described below.
Class description:
Simple Decoder to convert a style encoding and a content encoding into an image
Method signatures and docstrings:
- def __init__(self, out_channels=3, num_filts=64, n_residual=3, n_upsample=2, style_dim=8): Parameters ---------- out_channels : i... | Implement the Python class `Decoder` described below.
Class description:
Simple Decoder to convert a style encoding and a content encoding into an image
Method signatures and docstrings:
- def __init__(self, out_channels=3, num_filts=64, n_residual=3, n_upsample=2, style_dim=8): Parameters ---------- out_channels : i... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class Decoder:
"""Simple Decoder to convert a style encoding and a content encoding into an image"""
def __init__(self, out_channels=3, num_filts=64, n_residual=3, n_upsample=2, style_dim=8):
"""Parameters ---------- out_channels : int number of image channels to generate num_filts : int n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Simple Decoder to convert a style encoding and a content encoding into an image"""
def __init__(self, out_channels=3, num_filts=64, n_residual=3, n_upsample=2, style_dim=8):
"""Parameters ---------- out_channels : int number of image channels to generate num_filts : int number if filt... | the_stack_v2_python_sparse | dlutils/models/gans/munit/models.py | justusschock/dl-utils | train | 15 |
844cf68e32509f56d9aafb4a32ed8459946ae0ce | [
"if x < 0:\n return False\nif x < 10:\n return True\ns = str(x)\nreturn s[::-1] == s",
"if x < 0:\n return False\nif x < 10:\n return True\nif x % 10 == 0:\n return False\nreverse = 0\nt = x\nwhile t:\n reverse = reverse * 10 + t % 10\n if reverse > x:\n return False\n t //= 10\nret... | <|body_start_0|>
if x < 0:
return False
if x < 10:
return True
s = str(x)
return s[::-1] == s
<|end_body_0|>
<|body_start_1|>
if x < 0:
return False
if x < 10:
return True
if x % 10 == 0:
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x: int) -> bool:
"""是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number."""
<|body_0|>
def isPalindrome2(self, x: int) -> bool:
"""是否回文数字"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_022972 | 2,175 | no_license | [
{
"docstring": "是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number.",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x: int) -> bool"
},
{
"docstring": "是否回文数字",
"name": "isPalindrome2",
"signature": "def isPalindrome2(self, x: i... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x: int) -> bool: 是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number.
- def isPalindrome2(self, x: int) -> bool... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x: int) -> bool: 是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number.
- def isPalindrome2(self, x: int) -> bool... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def isPalindrome(self, x: int) -> bool:
"""是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number."""
<|body_0|>
def isPalindrome2(self, x: int) -> bool:
"""是否回文数字"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, x: int) -> bool:
"""是否回文数字, Runtime: 76 ms, faster than 100.00% of Python3 online submissions for Palindrome Number."""
if x < 0:
return False
if x < 10:
return True
s = str(x)
return s[::-1] == s
def isPalin... | the_stack_v2_python_sparse | math/009 Palindrome Number.py | mofei952/leetcode_python | train | 0 | |
c42145706873c6a924e3ab932bfa5561ad9c93c1 | [
"pickleFileStr = self.fbBasename() + '_fr.pick'\nfileExists = os.path.isfile(pickleFileStr)\nif fileExists:\n mTime = os.path.getmtime(self.fileStr)\n tTime = os.path.getmtime(pickleFileStr)\n fSize = os.path.getsize(pickleFileStr)\n if tTime < mTime or fSize < 100:\n print('~updating {:s}'.forma... | <|body_start_0|>
pickleFileStr = self.fbBasename() + '_fr.pick'
fileExists = os.path.isfile(pickleFileStr)
if fileExists:
mTime = os.path.getmtime(self.fileStr)
tTime = os.path.getmtime(pickleFileStr)
fSize = os.path.getsize(pickleFileStr)
if tTime... | full read stores count information across the entire read | FileBED_FR | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileBED_FR:
"""full read stores count information across the entire read"""
def getBedDict(self):
"""return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of reads that cover the position dictionary contains key '##cou... | stack_v2_sparse_classes_36k_train_022973 | 22,678 | no_license | [
{
"docstring": "return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of reads that cover the position dictionary contains key '##counts##' that stores total bp in library",
"name": "getBedDict",
"signature": "def getBedDict(self)"
},
... | 3 | null | Implement the Python class `FileBED_FR` described below.
Class description:
full read stores count information across the entire read
Method signatures and docstrings:
- def getBedDict(self): return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of rea... | Implement the Python class `FileBED_FR` described below.
Class description:
full read stores count information across the entire read
Method signatures and docstrings:
- def getBedDict(self): return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of rea... | 189bf355f0f878c5603b09a06b3b50b61a11ad93 | <|skeleton|>
class FileBED_FR:
"""full read stores count information across the entire read"""
def getBedDict(self):
"""return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of reads that cover the position dictionary contains key '##cou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileBED_FR:
"""full read stores count information across the entire read"""
def getBedDict(self):
"""return dictionary where key is chromosome, value is dictionary that dictionary has positions as key and value is number of reads that cover the position dictionary contains key '##counts##' that s... | the_stack_v2_python_sparse | python_util/bioFiles.py | bhofmei/analysis-scripts | train | 2 |
5e0c41ac6ed1052513b543157fa96446b2942435 | [
"pickings = self.mapped('picking_ids').filtered(lambda picking: picking.state not in ('cancel', 'done'))\nfor picking in pickings:\n try:\n picking.button_validate()\n except Exception as e:\n raise UserError(_('Issue While validate the picking : %s, %s' % (picking.name, e)))\nreturn super(Stock... | <|body_start_0|>
pickings = self.mapped('picking_ids').filtered(lambda picking: picking.state not in ('cancel', 'done'))
for picking in pickings:
try:
picking.button_validate()
except Exception as e:
raise UserError(_('Issue While validate the pick... | StockPickingBatchEpt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockPickingBatchEpt:
def done(self):
"""Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good. @author: Emipro Technologies - Jigar v vagadiya on date 12 sep 2018."""
<|body_0|>
def send_to_... | stack_v2_sparse_classes_36k_train_022974 | 7,533 | no_license | [
{
"docstring": "Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good. @author: Emipro Technologies - Jigar v vagadiya on date 12 sep 2018.",
"name": "done",
"signature": "def done(self)"
},
{
"docstring": "Execu... | 4 | stack_v2_sparse_classes_30k_train_001712 | Implement the Python class `StockPickingBatchEpt` described below.
Class description:
Implement the StockPickingBatchEpt class.
Method signatures and docstrings:
- def done(self): Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good.... | Implement the Python class `StockPickingBatchEpt` described below.
Class description:
Implement the StockPickingBatchEpt class.
Method signatures and docstrings:
- def done(self): Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good.... | 148ab8c37d04c93d3d23c7d15ca808de4748d2f4 | <|skeleton|>
class StockPickingBatchEpt:
def done(self):
"""Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good. @author: Emipro Technologies - Jigar v vagadiya on date 12 sep 2018."""
<|body_0|>
def send_to_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockPickingBatchEpt:
def done(self):
"""Checked the some condition like button validate. @param: none @return: If issue in picking than raise the warning other wise working good. @author: Emipro Technologies - Jigar v vagadiya on date 12 sep 2018."""
pickings = self.mapped('picking_ids').filt... | the_stack_v2_python_sparse | odoo_apps/shipping_integration_ept/models/batch_picking_ept.py | jchancafe/demo12 | train | 0 | |
6fb5716491c0dd69402517487d2a5eaa435fdd38 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EventMessageResponse()",
"from .event_message import EventMessage\nfrom .response_type import ResponseType\nfrom .time_slot import TimeSlot\nfrom .event_message import EventMessage\nfrom .response_type import ResponseType\nfrom .time_s... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EventMessageResponse()
<|end_body_0|>
<|body_start_1|>
from .event_message import EventMessage
from .response_type import ResponseType
from .time_slot import TimeSlot
fro... | EventMessageResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventMessageResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EventMessageResponse:
"""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 ... | stack_v2_sparse_classes_36k_train_022975 | 2,635 | 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: EventMessageResponse",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `EventMessageResponse` described below.
Class description:
Implement the EventMessageResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EventMessageResponse: Creates a new instance of the appropriate class based o... | Implement the Python class `EventMessageResponse` described below.
Class description:
Implement the EventMessageResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EventMessageResponse: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EventMessageResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EventMessageResponse:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventMessageResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EventMessageResponse:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/event_message_response.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c6ede396fad99534e4d0a7f6161c53c2b2640c5d | [
"super(Critic, self).__init__()\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.hidden = 128\nself.usecuda = usecuda\nself.rnn = nn.LSTMCell(self.state_dim, self.hidden, bias=True)\nself.fcs1 = nn.Linear(self.hidden, 1)\nself.fcs1.weight.data.uniform_(-EPS, EPS)\nself.fca1 = nn.Linear(self.action_di... | <|body_start_0|>
super(Critic, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.hidden = 128
self.usecuda = usecuda
self.rnn = nn.LSTMCell(self.state_dim, self.hidden, bias=True)
self.fcs1 = nn.Linear(self.hidden, 1)
self.fcs1.... | Critic network | Critic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Critic network"""
def __init__(self, state_dim, action_dim, usecuda=False):
"""Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of input action. :type action_dim: int."""
<|body_... | stack_v2_sparse_classes_36k_train_022976 | 3,704 | permissive | [
{
"docstring": "Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of input action. :type action_dim: int.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim, usecuda=False)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_014125 | Implement the Python class `Critic` described below.
Class description:
Critic network
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, usecuda=False): Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension o... | Implement the Python class `Critic` described below.
Class description:
Critic network
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, usecuda=False): Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension o... | a02bdb1754e9bae1c2448e4bccec795c739b3e6f | <|skeleton|>
class Critic:
"""Critic network"""
def __init__(self, state_dim, action_dim, usecuda=False):
"""Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of input action. :type action_dim: int."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
"""Critic network"""
def __init__(self, state_dim, action_dim, usecuda=False):
"""Special method for class initialisation. :param state_dim: Dimension of input state. :type state_dim: int. :param action_dim: Dimension of input action. :type action_dim: int."""
super(Critic, self).... | the_stack_v2_python_sparse | notebook/njord-ddpg/model.py | LUOFENGZHOU/njord | train | 0 |
b857f4095cf36042baa38810ad2a0995c717e324 | [
"warnings.warn('SequentialDAGGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)\nself.graph = tf.Graph()\nwith self.graph.as_default():\n self.graph_topology = DAGGraphTopology(n_atom_feat=n_atom_feat, max_atoms=max_atoms)\n self.output = self.graph_topology.get_atom_features_placehol... | <|body_start_0|>
warnings.warn('SequentialDAGGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)
self.graph = tf.Graph()
with self.graph.as_default():
self.graph_topology = DAGGraphTopology(n_atom_feat=n_atom_feat, max_atoms=max_atoms)
self.output ... | SequentialGraph for DAG models | SequentialDAGGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialDAGGraph:
"""SequentialGraph for DAG models"""
def __init__(self, n_atom_feat=75, max_atoms=50):
"""Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on datas... | stack_v2_sparse_classes_36k_train_022977 | 11,824 | permissive | [
{
"docstring": "Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset",
"name": "__init__",
"signature": "def __init__(self, n_atom_feat=75, max_atoms=50)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_021624 | Implement the Python class `SequentialDAGGraph` described below.
Class description:
SequentialGraph for DAG models
Method signatures and docstrings:
- def __init__(self, n_atom_feat=75, max_atoms=50): Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number... | Implement the Python class `SequentialDAGGraph` described below.
Class description:
SequentialGraph for DAG models
Method signatures and docstrings:
- def __init__(self, n_atom_feat=75, max_atoms=50): Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SequentialDAGGraph:
"""SequentialGraph for DAG models"""
def __init__(self, n_atom_feat=75, max_atoms=50):
"""Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on datas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialDAGGraph:
"""SequentialGraph for DAG models"""
def __init__(self, n_atom_feat=75, max_atoms=50):
"""Parameters ---------- n_atom_feat: int, optional Number of features per atom. max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset"""
... | the_stack_v2_python_sparse | contrib/one_shot_models/graph_models.py | deepchem/deepchem | train | 4,876 |
77ca8fe62a4c7a3f3aaad55e066b57154cefc059 | [
"self.dic = dict()\nl = len(words)\nself.max = l\nfor i in xrange(l):\n word = words[i]\n if word in self.dic:\n self.dic[word].append(i)\n else:\n self.dic[word] = [i]",
"l1, l2 = (self.dic[word1], self.dic[word2])\nn1, n2 = (len(l1), len(l2))\np1, p2 = (0, 0)\nret = self.max\nwhile p1 < n... | <|body_start_0|>
self.dic = dict()
l = len(words)
self.max = l
for i in xrange(l):
word = words[i]
if word in self.dic:
self.dic[word].append(i)
else:
self.dic[word] = [i]
<|end_body_0|>
<|body_start_1|>
l1, l2 ... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_022978 | 1,174 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_006043 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | d6fac85a94a7188e93d4e202e67b6485562d12bd | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.dic = dict()
l = len(words)
self.max = l
for i in xrange(l):
word = words[i]
if word in self.dic:
self.dic[word].appen... | the_stack_v2_python_sparse | lc244.py | GeorgyZhou/Leetcode-Problem | train | 0 | |
56d0f940ffb3a70a2daca19a46a65909c8de1100 | [
"creator = self.get(user=user)\ncreator.is_creator = True\ncreator.save()\nif send_email:\n creator.send_acceptance_email(site, request)\nreturn creator",
"creator = self.create(user=user, url=url, is_creator=False)\nif send_email:\n creator.send_creator_request_email(site, request)\nreturn creator"
] | <|body_start_0|>
creator = self.get(user=user)
creator.is_creator = True
creator.save()
if send_email:
creator.send_acceptance_email(site, request)
return creator
<|end_body_0|>
<|body_start_1|>
creator = self.create(user=user, url=url, is_creator=False)
... | A custom manager for the `UserCreator` Model | CreatorManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatorManager:
"""A custom manager for the `UserCreator` Model"""
def activate_creator(self, user, site, send_email=True, request=None):
"""Activate the Creator by changing `is_creator` field to True"""
<|body_0|>
def create_inactive_creator(self, user, url, site, send_... | stack_v2_sparse_classes_36k_train_022979 | 2,419 | no_license | [
{
"docstring": "Activate the Creator by changing `is_creator` field to True",
"name": "activate_creator",
"signature": "def activate_creator(self, user, site, send_email=True, request=None)"
},
{
"docstring": "Creates a new creator entry, and emails the information at join@musetic.com",
"nam... | 2 | stack_v2_sparse_classes_30k_train_012429 | Implement the Python class `CreatorManager` described below.
Class description:
A custom manager for the `UserCreator` Model
Method signatures and docstrings:
- def activate_creator(self, user, site, send_email=True, request=None): Activate the Creator by changing `is_creator` field to True
- def create_inactive_crea... | Implement the Python class `CreatorManager` described below.
Class description:
A custom manager for the `UserCreator` Model
Method signatures and docstrings:
- def activate_creator(self, user, site, send_email=True, request=None): Activate the Creator by changing `is_creator` field to True
- def create_inactive_crea... | 1dfcebfda703c3fceffa2d9030e5196c351259f2 | <|skeleton|>
class CreatorManager:
"""A custom manager for the `UserCreator` Model"""
def activate_creator(self, user, site, send_email=True, request=None):
"""Activate the Creator by changing `is_creator` field to True"""
<|body_0|>
def create_inactive_creator(self, user, url, site, send_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreatorManager:
"""A custom manager for the `UserCreator` Model"""
def activate_creator(self, user, site, send_email=True, request=None):
"""Activate the Creator by changing `is_creator` field to True"""
creator = self.get(user=user)
creator.is_creator = True
creator.save(... | the_stack_v2_python_sparse | musetic/user/managers.py | joshchandler/musetic-web | train | 0 |
9499948812698af51adb743a2b7d7b81c35dc7ea | [
"super(MultiTverskyLoss, self).__init__()\nself.alpha = alpha\nself.beta = beta\nself.gamma = gamma\nself.weights = weights",
"targets = targets.unsqueeze(1)\nnum_class = inputs.size(1)\nweight_losses = 0.0\nif self.weights is not None:\n assert len(self.weights) == num_class, 'number of classes should be equa... | <|body_start_0|>
super(MultiTverskyLoss, self).__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.weights = weights
<|end_body_0|>
<|body_start_1|>
targets = targets.unsqueeze(1)
num_class = inputs.size(1)
weight_losses = 0.0
i... | Tversky Loss for segmentation adaptive with multi class segmentation | MultiTverskyLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiTverskyLoss:
"""Tversky Loss for segmentation adaptive with multi class segmentation"""
def __init__(self, alpha=0.5, beta=0.5, gamma=1.0, weights=None):
""":param alpha (Tensor, float, optional): controls the penalty for false positives. :param beta (Tensor, float, optional): c... | stack_v2_sparse_classes_36k_train_022980 | 10,977 | permissive | [
{
"docstring": ":param alpha (Tensor, float, optional): controls the penalty for false positives. :param beta (Tensor, float, optional): controls the penalty for false negative. :param gamma (Tensor, float, optional): focal coefficient :param weights (Tensor, optional): a manual rescaling weight given to each c... | 2 | stack_v2_sparse_classes_30k_train_006741 | Implement the Python class `MultiTverskyLoss` described below.
Class description:
Tversky Loss for segmentation adaptive with multi class segmentation
Method signatures and docstrings:
- def __init__(self, alpha=0.5, beta=0.5, gamma=1.0, weights=None): :param alpha (Tensor, float, optional): controls the penalty for ... | Implement the Python class `MultiTverskyLoss` described below.
Class description:
Tversky Loss for segmentation adaptive with multi class segmentation
Method signatures and docstrings:
- def __init__(self, alpha=0.5, beta=0.5, gamma=1.0, weights=None): :param alpha (Tensor, float, optional): controls the penalty for ... | d83c9f6dfcfe36573fe77fbdfec4fda23ded9180 | <|skeleton|>
class MultiTverskyLoss:
"""Tversky Loss for segmentation adaptive with multi class segmentation"""
def __init__(self, alpha=0.5, beta=0.5, gamma=1.0, weights=None):
""":param alpha (Tensor, float, optional): controls the penalty for false positives. :param beta (Tensor, float, optional): c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiTverskyLoss:
"""Tversky Loss for segmentation adaptive with multi class segmentation"""
def __init__(self, alpha=0.5, beta=0.5, gamma=1.0, weights=None):
""":param alpha (Tensor, float, optional): controls the penalty for false positives. :param beta (Tensor, float, optional): controls the p... | the_stack_v2_python_sparse | utils/criterions.py | thanhhau097/brats-dmf-bifpn | train | 4 |
b05b91cc0cfa4d85ee88571193c56607fde67a07 | [
"obj = self.new_obj\nobj.save()\narchiving, status = Archiving.objects.get_or_create(year=obj.add_time.year, month=obj.add_time.month)\nif not status:\n old_tags_map = TagsMap.objects.filter(article=obj)\n for old_tag_map in old_tags_map:\n old_tag_map.delete()\nfor tag in split_tags(obj.tags):\n ta... | <|body_start_0|>
obj = self.new_obj
obj.save()
archiving, status = Archiving.objects.get_or_create(year=obj.add_time.year, month=obj.add_time.month)
if not status:
old_tags_map = TagsMap.objects.filter(article=obj)
for old_tag_map in old_tags_map:
... | PageDetailAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageDetailAdmin:
def save_models(self):
"""保存文章"""
<|body_0|>
def delete_model(self):
"""删除文章时进行的数据更新"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = self.new_obj
obj.save()
archiving, status = Archiving.objects.get_or_create(y... | stack_v2_sparse_classes_36k_train_022981 | 4,329 | no_license | [
{
"docstring": "保存文章",
"name": "save_models",
"signature": "def save_models(self)"
},
{
"docstring": "删除文章时进行的数据更新",
"name": "delete_model",
"signature": "def delete_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007354 | Implement the Python class `PageDetailAdmin` described below.
Class description:
Implement the PageDetailAdmin class.
Method signatures and docstrings:
- def save_models(self): 保存文章
- def delete_model(self): 删除文章时进行的数据更新 | Implement the Python class `PageDetailAdmin` described below.
Class description:
Implement the PageDetailAdmin class.
Method signatures and docstrings:
- def save_models(self): 保存文章
- def delete_model(self): 删除文章时进行的数据更新
<|skeleton|>
class PageDetailAdmin:
def save_models(self):
"""保存文章"""
<|bod... | 7d86de995deacac4eb45fed31865ba8a9598c289 | <|skeleton|>
class PageDetailAdmin:
def save_models(self):
"""保存文章"""
<|body_0|>
def delete_model(self):
"""删除文章时进行的数据更新"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageDetailAdmin:
def save_models(self):
"""保存文章"""
obj = self.new_obj
obj.save()
archiving, status = Archiving.objects.get_or_create(year=obj.add_time.year, month=obj.add_time.month)
if not status:
old_tags_map = TagsMap.objects.filter(article=obj)
... | the_stack_v2_python_sparse | apps/blog/adminx.py | SatoKoi/Blog | train | 1 | |
785a2ace1e7d76b2755d63b89e855df3976a4c86 | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\nhiddenQ... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | class rnn encoder | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
<|body_0|>
def initialize_hidden_state(self):
"""Inititalize hidden states Returns: tensor of shap... | stack_v2_sparse_classes_36k_train_022982 | 1,642 | no_license | [
{
"docstring": "Inititalizer function Args: batch: integer representing the batch size",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "Inititalize hidden states Returns: tensor of shape (batch, units) containing the initialized hidden st... | 3 | stack_v2_sparse_classes_30k_train_001455 | Implement the Python class `RNNEncoder` described below.
Class description:
class rnn encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Inititalizer function Args: batch: integer representing the batch size
- def initialize_hidden_state(self): Inititalize hidden states Re... | Implement the Python class `RNNEncoder` described below.
Class description:
class rnn encoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Inititalizer function Args: batch: integer representing the batch size
- def initialize_hidden_state(self): Inititalize hidden states Re... | a51fbcb76dae9281ff34ace0fb762ef899b4c380 | <|skeleton|>
class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
<|body_0|>
def initialize_hidden_state(self):
"""Inititalize hidden states Returns: tensor of shap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""class rnn encoder"""
def __init__(self, vocab, embedding, units, batch):
"""Inititalizer function Args: batch: integer representing the batch size"""
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.l... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | Diegokernel/holbertonschool-machine_learning | train | 0 |
bbdc1a47cc11b838f782af32629dd345dadefd75 | [
"candidate = [1]\nnum = [0, 1, 2]\nfor i in range(3, n + 1):\n new_candidate = (len(candidate) + 1) ** 2\n if i >= new_candidate:\n candidate.append(new_candidate)\n subnum = 2 ** 31 - 1\n for j in candidate:\n subnum = min(1 + num[i - j], subnum)\n num.append(subnum)\nreturn num[n]",
... | <|body_start_0|>
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + 1):
new_candidate = (len(candidate) + 1) ** 2
if i >= new_candidate:
candidate.append(new_candidate)
subnum = 2 ** 31 - 1
for j in candidate:
sub... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + ... | stack_v2_sparse_classes_36k_train_022983 | 915 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares2",
"signature": "def numSquares2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares(self, n):
""":typ... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
candidate = [1]
num = [0, 1, 2]
for i in range(3, n + 1):
new_candidate = (len(candidate) + 1) ** 2
if i >= new_candidate:
candidate.append(new_candidate)
subnu... | the_stack_v2_python_sparse | 中级算法/numSquares.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
f84875aabf7d564856ea31d7185f06a578fa85c0 | [
"if hasattr(node, 'lights'):\n if hasattr(node, 'ambient'):\n a = node.ambient\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [a, a, a, 1.0])\n IDs = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7]\n from OpenGLContext.scenegraph import light\n for direct... | <|body_start_0|>
if hasattr(node, 'lights'):
if hasattr(node, 'ambient'):
a = node.ambient
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [a, a, a, 1.0])
IDs = [GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7]
fro... | Rendering-pass mix-in which is visual-aware | PassMixIn | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems ... | stack_v2_sparse_classes_36k_train_022984 | 2,740 | permissive | [
{
"docstring": "Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems with support for calculating light IDs beyond eight, so I have limited the set for now. This method relies on ... | 2 | null | Implement the Python class `PassMixIn` described below.
Class description:
Rendering-pass mix-in which is visual-aware
Method signatures and docstrings:
- def SceneGraphLights(self, node): Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL re... | Implement the Python class `PassMixIn` described below.
Class description:
Rendering-pass mix-in which is visual-aware
Method signatures and docstrings:
- def SceneGraphLights(self, node): Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL re... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PassMixIn:
"""Rendering-pass mix-in which is visual-aware"""
def SceneGraphLights(self, node):
"""Render lights for a scenegraph The default implementation limits you to eight active lights, despite the fact that many OpenGL renderers support more than this. There have been problems with support ... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/browser/passes.py | alexus37/AugmentedRealityChess | train | 1 |
f8c53ddfdaad407ad5bdc525a87f734ce687eb12 | [
"self.algorithm = algorithm.lower()\nself.min_val = min_val\nself.threshold_val = threshold_val\nself.num_boxes = num_boxes\nself.allow_overlap = allow_overlap\nself.validate()",
"if self.algorithm not in {'brute_force', 'threshold', 'edge_tracing', 'bounding_boxes'}:\n msg = 'Algorithm specified is not implem... | <|body_start_0|>
self.algorithm = algorithm.lower()
self.min_val = min_val
self.threshold_val = threshold_val
self.num_boxes = num_boxes
self.allow_overlap = allow_overlap
self.validate()
<|end_body_0|>
<|body_start_1|>
if self.algorithm not in {'brute_force', 't... | Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters | ValidInsertLocationsConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidInsertLocationsConfig:
"""Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters"""
def __init__(self, algorithm: str='brute_force', min_val: Union[int, Sequence[int]]=0, threshold_val: Union[float, Sequence[float]]... | stack_v2_sparse_classes_36k_train_022985 | 9,934 | permissive | [
{
"docstring": "Initialize and validate all relevant parameters for InsertAtRandomLocation :param algorithm: algorithm to use for determining valid placement, options include brute_force -> for every edge pixel of the image, invalidates all intersecting pattern insert locations threshold -> a trigger position o... | 2 | stack_v2_sparse_classes_30k_train_012536 | Implement the Python class `ValidInsertLocationsConfig` described below.
Class description:
Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters
Method signatures and docstrings:
- def __init__(self, algorithm: str='brute_force', min_val: Union... | Implement the Python class `ValidInsertLocationsConfig` described below.
Class description:
Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters
Method signatures and docstrings:
- def __init__(self, algorithm: str='brute_force', min_val: Union... | 6ee5912f1fa57f49a4dd4feeeaf7862153bb6a9f | <|skeleton|>
class ValidInsertLocationsConfig:
"""Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters"""
def __init__(self, algorithm: str='brute_force', min_val: Union[int, Sequence[int]]=0, threshold_val: Union[float, Sequence[float]]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidInsertLocationsConfig:
"""Specifies which algorithm to use for determining the valid spots for trigger insertion on an image and all relevant parameters"""
def __init__(self, algorithm: str='brute_force', min_val: Union[int, Sequence[int]]=0, threshold_val: Union[float, Sequence[float]]=5.0, num_box... | the_stack_v2_python_sparse | trojai/trojai/datagen/config.py | ionutmodo/TrojAI-UMD | train | 1 |
bfa466c23686fa68977400e011a6e42ccaacdf1a | [
"context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)\ncontext['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)\nreturn context",
"try:\n form.instance.escuela = escuela_m.Escuela.objects.get(codigo=form.cleaned_data['udi'])\nexcept ObjectDoesNotExist:\n ... | <|body_start_0|>
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)
return context
<|end_body_0|>
<|body_start_1|>
try:
form.instance.escuela = escuela_m.Escuela.o... | Vista para la creación de :class:`ProcesoNaat`. | ProcesoNaatCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_36k_train_022986 | 7,670 | no_license | [
{
"docstring": "Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Asigna al usuario actual como `capacitador` del objeto.",
"name": "form_valid",
"signature": "def form... | 2 | stack_v2_sparse_classes_30k_train_000617 | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | 0e37786d7173abe820fd10b094ffcc2db9593a9c | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_li... | the_stack_v2_python_sparse | src/apps/naat/views.py | jinchuika/app-suni | train | 7 |
b919433c62b52836aaa876373abbd54060f2c79c | [
"self.conf = conf\nself.bars = bars\nself.events = events\nself.timerEvents = timerEvents\nself.short_window = short_window\nself.long_window = long_window\nself.bought = self._calculate_initial_bought()",
"bought = {}\nfor s in self.conf.symbol_list:\n bought[s] = 'OUT'\nreturn bought",
"if event.type == 'M... | <|body_start_0|>
self.conf = conf
self.bars = bars
self.events = events
self.timerEvents = timerEvents
self.short_window = short_window
self.long_window = long_window
self.bought = self._calculate_initial_bought()
<|end_body_0|>
<|body_start_1|>
bought = ... | Default window is 34/144 | MovingAverageCrossStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverageCrossStrategy:
"""Default window is 34/144"""
def __init__(self, conf, bars, events, timerEvents, short_window=34, long_window=144):
"""Initializes the buy and hold strategy Parameters: bars - DataHandler object that provides bar info events - Event queue object short/lo... | stack_v2_sparse_classes_36k_train_022987 | 6,163 | no_license | [
{
"docstring": "Initializes the buy and hold strategy Parameters: bars - DataHandler object that provides bar info events - Event queue object short/long windows - moving average lookbacks",
"name": "__init__",
"signature": "def __init__(self, conf, bars, events, timerEvents, short_window=34, long_windo... | 3 | stack_v2_sparse_classes_30k_train_016231 | Implement the Python class `MovingAverageCrossStrategy` described below.
Class description:
Default window is 34/144
Method signatures and docstrings:
- def __init__(self, conf, bars, events, timerEvents, short_window=34, long_window=144): Initializes the buy and hold strategy Parameters: bars - DataHandler object th... | Implement the Python class `MovingAverageCrossStrategy` described below.
Class description:
Default window is 34/144
Method signatures and docstrings:
- def __init__(self, conf, bars, events, timerEvents, short_window=34, long_window=144): Initializes the buy and hold strategy Parameters: bars - DataHandler object th... | 85f5f08192b136b65136d0cb145026cb81b3f56c | <|skeleton|>
class MovingAverageCrossStrategy:
"""Default window is 34/144"""
def __init__(self, conf, bars, events, timerEvents, short_window=34, long_window=144):
"""Initializes the buy and hold strategy Parameters: bars - DataHandler object that provides bar info events - Event queue object short/lo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverageCrossStrategy:
"""Default window is 34/144"""
def __init__(self, conf, bars, events, timerEvents, short_window=34, long_window=144):
"""Initializes the buy and hold strategy Parameters: bars - DataHandler object that provides bar info events - Event queue object short/long windows - ... | the_stack_v2_python_sparse | backtest/mac_bt.py | cujeu/quantocean | train | 0 |
6fb9f6b37b51175a50b6eb401bd7aeef7f00d6e2 | [
"if (self.logits_train is None) != (self.logits_test is None):\n raise ValueError('logits_train and logits_test should both be either set or unset')\nif (self.labels_train is None) != (self.labels_test is None):\n raise ValueError('labels_train and labels_test should both be either set or unset')\nif self.log... | <|body_start_0|>
if (self.logits_train is None) != (self.logits_test is None):
raise ValueError('logits_train and logits_test should both be either set or unset')
if (self.labels_train is None) != (self.labels_test is None):
raise ValueError('labels_train and labels_test should b... | Input data for running an attack on seq2seq models. This includes only the data, and not configuration. | Seq2SeqAttackInputData | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2SeqAttackInputData:
"""Input data for running an attack on seq2seq models. This includes only the data, and not configuration."""
def validate(self):
"""Validates the inputs."""
<|body_0|>
def __str__(self):
"""Returns the shapes of variables that are not Non... | stack_v2_sparse_classes_36k_train_022988 | 11,489 | permissive | [
{
"docstring": "Validates the inputs.",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "Returns the shapes of variables that are not None.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `Seq2SeqAttackInputData` described below.
Class description:
Input data for running an attack on seq2seq models. This includes only the data, and not configuration.
Method signatures and docstrings:
- def validate(self): Validates the inputs.
- def __str__(self): Returns the shapes of varia... | Implement the Python class `Seq2SeqAttackInputData` described below.
Class description:
Input data for running an attack on seq2seq models. This includes only the data, and not configuration.
Method signatures and docstrings:
- def validate(self): Validates the inputs.
- def __str__(self): Returns the shapes of varia... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class Seq2SeqAttackInputData:
"""Input data for running an attack on seq2seq models. This includes only the data, and not configuration."""
def validate(self):
"""Validates the inputs."""
<|body_0|>
def __str__(self):
"""Returns the shapes of variables that are not Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seq2SeqAttackInputData:
"""Input data for running an attack on seq2seq models. This includes only the data, and not configuration."""
def validate(self):
"""Validates the inputs."""
if (self.logits_train is None) != (self.logits_test is None):
raise ValueError('logits_train an... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/privacy_tests/membership_inference_attack/seq2seq_mia.py | tensorflow/privacy | train | 1,881 |
ee2c16e77bae27854b7f286bbcd6490cc65b4467 | [
"dict_ql = {}\ndict_qu = {}\ncount = int_fmt % 10\nfor i in range(0, count):\n str_qu = str_quanta[i * 3:i * 3 + 2]\n str_ql = str_quanta[(i + count) * 3:(i + count) * 3 + 2]\n headers = quanta_headers(int_fmt)\n dict_ql[headers[i]] = int(str_ql)\n dict_qu[headers[i]] = int(str_qu)\nreturn (dict_qu, ... | <|body_start_0|>
dict_ql = {}
dict_qu = {}
count = int_fmt % 10
for i in range(0, count):
str_qu = str_quanta[i * 3:i * 3 + 2]
str_ql = str_quanta[(i + count) * 3:(i + count) * 3 + 2]
headers = quanta_headers(int_fmt)
dict_ql[headers[i]] = ... | Manages entries of .lin files | PGopherLinConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PGopherLinConverter:
"""Manages entries of .lin files"""
def __read_quanta(str_quanta, int_fmt):
"""convert quanta from .cat to dict returns (dict_upper, dict_lower)"""
<|body_0|>
def str2line(str_line, int_fmt):
"""str to Line object"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_022989 | 11,597 | no_license | [
{
"docstring": "convert quanta from .cat to dict returns (dict_upper, dict_lower)",
"name": "__read_quanta",
"signature": "def __read_quanta(str_quanta, int_fmt)"
},
{
"docstring": "str to Line object",
"name": "str2line",
"signature": "def str2line(str_line, int_fmt)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019980 | Implement the Python class `PGopherLinConverter` described below.
Class description:
Manages entries of .lin files
Method signatures and docstrings:
- def __read_quanta(str_quanta, int_fmt): convert quanta from .cat to dict returns (dict_upper, dict_lower)
- def str2line(str_line, int_fmt): str to Line object | Implement the Python class `PGopherLinConverter` described below.
Class description:
Manages entries of .lin files
Method signatures and docstrings:
- def __read_quanta(str_quanta, int_fmt): convert quanta from .cat to dict returns (dict_upper, dict_lower)
- def str2line(str_line, int_fmt): str to Line object
<|skel... | 57bda76b211c8efd3bd24bd2895bd57ea855003e | <|skeleton|>
class PGopherLinConverter:
"""Manages entries of .lin files"""
def __read_quanta(str_quanta, int_fmt):
"""convert quanta from .cat to dict returns (dict_upper, dict_lower)"""
<|body_0|>
def str2line(str_line, int_fmt):
"""str to Line object"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PGopherLinConverter:
"""Manages entries of .lin files"""
def __read_quanta(str_quanta, int_fmt):
"""convert quanta from .cat to dict returns (dict_upper, dict_lower)"""
dict_ql = {}
dict_qu = {}
count = int_fmt % 10
for i in range(0, count):
str_qu = st... | the_stack_v2_python_sparse | pickett/converters.py | kiraboris/scanner | train | 0 |
a66ac323516cf0027e565878a732a98c63e61971 | [
"organization = Organization.objects.create(domain='example.org', fullname='Example Organisation')\nCommentForm = django_comments.get_form()\ndata = {'honeypot': '', 'comment': 'Content', 'name': 'Ron', **CommentForm(organization).generate_security_data()}\nform = CommentForm(organization, data)\nself.assertTrue(fo... | <|body_start_0|>
organization = Organization.objects.create(domain='example.org', fullname='Example Organisation')
CommentForm = django_comments.get_form()
data = {'honeypot': '', 'comment': 'Content', 'name': 'Ron', **CommentForm(organization).generate_security_data()}
form = CommentFor... | TestEmailFieldRequiredness | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEmailFieldRequiredness:
def test_email_field_requiredness(self):
"""Regression test for #1944. Previously a user without email address would not be able to add a comment."""
<|body_0|>
def test_email_field_requiredness_POST(self):
"""Regression test for #1944. Pr... | stack_v2_sparse_classes_36k_train_022990 | 2,880 | permissive | [
{
"docstring": "Regression test for #1944. Previously a user without email address would not be able to add a comment.",
"name": "test_email_field_requiredness",
"signature": "def test_email_field_requiredness(self)"
},
{
"docstring": "Regression test for #1944. Previously a user without email a... | 2 | stack_v2_sparse_classes_30k_train_009145 | Implement the Python class `TestEmailFieldRequiredness` described below.
Class description:
Implement the TestEmailFieldRequiredness class.
Method signatures and docstrings:
- def test_email_field_requiredness(self): Regression test for #1944. Previously a user without email address would not be able to add a comment... | Implement the Python class `TestEmailFieldRequiredness` described below.
Class description:
Implement the TestEmailFieldRequiredness class.
Method signatures and docstrings:
- def test_email_field_requiredness(self): Regression test for #1944. Previously a user without email address would not be able to add a comment... | f97631b2f3dd8e8f502e90bdb04dd72f048d4837 | <|skeleton|>
class TestEmailFieldRequiredness:
def test_email_field_requiredness(self):
"""Regression test for #1944. Previously a user without email address would not be able to add a comment."""
<|body_0|>
def test_email_field_requiredness_POST(self):
"""Regression test for #1944. Pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestEmailFieldRequiredness:
def test_email_field_requiredness(self):
"""Regression test for #1944. Previously a user without email address would not be able to add a comment."""
organization = Organization.objects.create(domain='example.org', fullname='Example Organisation')
CommentFor... | the_stack_v2_python_sparse | amy/extcomments/tests.py | pbanaszkiewicz/amy | train | 0 | |
f3a1af44d78f155a2bb836d7c6e6df5183895472 | [
"if platform.platform().lower().startswith('windows'):\n cmd = 'ping -n 1 -w 1 '\nelse:\n cmd = 'ping -c 1 -W 1 '\nprocess = subprocess.Popen(cmd + ip_address, shell=True, stdout=subprocess.PIPE)\ntime.sleep(1.2)\nprocess.stdout.close()\nprocess.wait()\nreturn process.returncode",
"if ip_address in Ping.unr... | <|body_start_0|>
if platform.platform().lower().startswith('windows'):
cmd = 'ping -n 1 -w 1 '
else:
cmd = 'ping -c 1 -W 1 '
process = subprocess.Popen(cmd + ip_address, shell=True, stdout=subprocess.PIPE)
time.sleep(1.2)
process.stdout.close()
pro... | Platform-independent ping support. | Ping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ping:
"""Platform-independent ping support."""
def ping(ip_address):
"""Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames can be used, but are not recommended. :return: return co... | stack_v2_sparse_classes_36k_train_022991 | 2,321 | permissive | [
{
"docstring": "Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames can be used, but are not recommended. :return: return code of subprocess; 0 for success, anything else for failure :rtype: int",
"name":... | 2 | stack_v2_sparse_classes_30k_train_001956 | Implement the Python class `Ping` described below.
Class description:
Platform-independent ping support.
Method signatures and docstrings:
- def ping(ip_address): Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames... | Implement the Python class `Ping` described below.
Class description:
Platform-independent ping support.
Method signatures and docstrings:
- def ping(ip_address): Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames... | 9d87f324f91eb49795825f77d663f6ac46a1c5f4 | <|skeleton|>
class Ping:
"""Platform-independent ping support."""
def ping(ip_address):
"""Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames can be used, but are not recommended. :return: return co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ping:
"""Platform-independent ping support."""
def ping(ip_address):
"""Send a ping (ICMP ECHO request) to the given host. SpiNNaker boards support ICMP ECHO when booted. :param str ip_address: The IP address to ping. Hostnames can be used, but are not recommended. :return: return code of subproc... | the_stack_v2_python_sparse | spinn_utilities/ping.py | SpiNNakerManchester/SpiNNUtils | train | 1 |
2cb30ee03b2ab27963d6df28d3cc301c625ff216 | [
"self.N = N\nself.G = [[] for _ in range(self.N)]\nfor f, t, c in E:\n self.G[f].append([t, c, len(self.G[t])])\n self.G[t].append([f, 0, len(self.G[f]) - 1])",
"if s == g:\n return mincap\nself.used[s] = 1\nfor i, (to, cap, rev) in enumerate(self.G[s]):\n if self.used[to] == 0 and cap > 0:\n d... | <|body_start_0|>
self.N = N
self.G = [[] for _ in range(self.N)]
for f, t, c in E:
self.G[f].append([t, c, len(self.G[t])])
self.G[t].append([f, 0, len(self.G[f]) - 1])
<|end_body_0|>
<|body_start_1|>
if s == g:
return mincap
self.used[s] = 1
... | フローネットワークにおける最大フローを求めるアルゴリズム | FordFulkerson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FordFulkerson:
"""フローネットワークにおける最大フローを求めるアルゴリズム"""
def __init__(self, N: int, E: list):
"""N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地"""
<|body_0|>
def flow_dfs(self, s, g, mincap):
"""s から g へのパスを DFS ... | stack_v2_sparse_classes_36k_train_022992 | 1,775 | no_license | [
{
"docstring": "N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地",
"name": "__init__",
"signature": "def __init__(self, N: int, E: list)"
},
{
"docstring": "s から g へのパスを DFS で探し,そのパスに流せる最大流量を返す. mincap = 通った辺の中の最少容量",
"name": "flow_dfs"... | 3 | stack_v2_sparse_classes_30k_train_002768 | Implement the Python class `FordFulkerson` described below.
Class description:
フローネットワークにおける最大フローを求めるアルゴリズム
Method signatures and docstrings:
- def __init__(self, N: int, E: list): N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地
- def flow_dfs(self, s, g, minca... | Implement the Python class `FordFulkerson` described below.
Class description:
フローネットワークにおける最大フローを求めるアルゴリズム
Method signatures and docstrings:
- def __init__(self, N: int, E: list): N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地
- def flow_dfs(self, s, g, minca... | 34353647828de4907d8eddbaf4e4b5134d4a78fa | <|skeleton|>
class FordFulkerson:
"""フローネットワークにおける最大フローを求めるアルゴリズム"""
def __init__(self, N: int, E: list):
"""N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地"""
<|body_0|>
def flow_dfs(self, s, g, mincap):
"""s から g へのパスを DFS ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FordFulkerson:
"""フローネットワークにおける最大フローを求めるアルゴリズム"""
def __init__(self, N: int, E: list):
"""N: 頂点の数 E: 有向辺のリスト, (from, to, capacity) G: 有向グラフの隣接リスト表現, (to, capacity, rev) ※rev: 逆辺が保存されているG[to]での番地"""
self.N = N
self.G = [[] for _ in range(self.N)]
for f, t, c in E:
... | the_stack_v2_python_sparse | FordFulkerson.py | Ma-r-co/cp-utils-python | train | 0 |
ff0ef7f17eada7f72c0cdd64f2c51889fec843d7 | [
"assert isinstance(query, dict)\nself.queries = {}\nfor type_name, subqueries in list(query.items()):\n cls = model.get_model(type_name)\n for subquery in subqueries:\n if isinstance(subquery, str):\n subquery = jmespath.compile(subquery)\n else:\n subquery = DictSubQuery(s... | <|body_start_0|>
assert isinstance(query, dict)
self.queries = {}
for type_name, subqueries in list(query.items()):
cls = model.get_model(type_name)
for subquery in subqueries:
if isinstance(subquery, str):
subquery = jmespath.compile(s... | Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database. | Query | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
"""Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database."""
def __init__(self, query):
"""Accept dict as specified in configuration, compile all the JMESPath queries, and store it as internal immutable state. :param q... | stack_v2_sparse_classes_36k_train_022993 | 4,364 | permissive | [
{
"docstring": "Accept dict as specified in configuration, compile all the JMESPath queries, and store it as internal immutable state. :param query: query dictionary",
"name": "__init__",
"signature": "def __init__(self, query)"
},
{
"docstring": "Search through list of objects from database of ... | 2 | null | Implement the Python class `Query` described below.
Class description:
Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database.
Method signatures and docstrings:
- def __init__(self, query): Accept dict as specified in configuration, compile all the JMESPath qu... | Implement the Python class `Query` described below.
Class description:
Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database.
Method signatures and docstrings:
- def __init__(self, query): Accept dict as specified in configuration, compile all the JMESPath qu... | a62b29602244bd22ebfbf9ae4ff654dbc5dd34ce | <|skeleton|>
class Query:
"""Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database."""
def __init__(self, query):
"""Accept dict as specified in configuration, compile all the JMESPath queries, and store it as internal immutable state. :param q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Query:
"""Parsed and compiled query using which it is possible to filter instances of model.Model class stored in database."""
def __init__(self, query):
"""Accept dict as specified in configuration, compile all the JMESPath queries, and store it as internal immutable state. :param query: query d... | the_stack_v2_python_sparse | cloudferry/lib/utils/query.py | Python3pkg/CloudFerry | train | 0 |
8efb0e14597bbb9653723ddf2ee062aeaca6c49d | [
"parser.add_argument('subscription', nargs='+', help='One or more subscriptions to create.')\nparser.add_argument('--topic', required=True, help='The name of the topic from which this subscription is receiving messages. Each subscription is attached to a single topic.')\nparser.add_argument('--topic-project', defau... | <|body_start_0|>
parser.add_argument('subscription', nargs='+', help='One or more subscriptions to create.')
parser.add_argument('--topic', required=True, help='The name of the topic from which this subscription is receiving messages. Each subscription is attached to a single topic.')
parser.add... | Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified."""
def Args(parser):
"""Registers flags for this command."""
... | stack_v2_sparse_classes_36k_train_022994 | 4,149 | 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 2-tuple ... | 3 | null | Implement the Python class `Create` described below.
Class description:
Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified.
Method signatures and docstrings:
- def ... | Implement the Python class `Create` described below.
Class description:
Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified.
Method signatures and docstrings:
- def ... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class Create:
"""Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified."""
def Args(parser):
"""Registers flags for this command."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Creates one or more Cloud Pub/Sub subscriptions. Creates one or more Cloud Pub/Sub subscriptions for a given topic. The new subscription defaults to a PULL subscription unless a push endpoint is specified."""
def Args(parser):
"""Registers flags for this command."""
parser.add_... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/surface/pubsub/subscriptions/create.py | twistedpair/google-cloud-sdk | train | 58 |
8433f42efba5cb322971d35d899ceb0bb2514400 | [
"rtn = 0\n\ndef remove(i, j):\n odd = 0\n even = 0\n for p in range(i, j + 1):\n if p % 2 == 0:\n even += cost[p]\n else:\n odd += cost[p]\n return min(odd, even)\nl = 0\nr = 0\nlast = s[0]\nfor i in range(1, len(cost)):\n if s[i] == last:\n r += 1\n else... | <|body_start_0|>
rtn = 0
def remove(i, j):
odd = 0
even = 0
for p in range(i, j + 1):
if p % 2 == 0:
even += cost[p]
else:
odd += cost[p]
return min(odd, even)
l = 0
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCostold(self, s, cost):
""":type s: str :type cost: List[int] :rtype: int"""
<|body_0|>
def minCost(self, s, cost):
""":type s: str :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rtn = 0
d... | stack_v2_sparse_classes_36k_train_022995 | 1,533 | no_license | [
{
"docstring": ":type s: str :type cost: List[int] :rtype: int",
"name": "minCostold",
"signature": "def minCostold(self, s, cost)"
},
{
"docstring": ":type s: str :type cost: List[int] :rtype: int",
"name": "minCost",
"signature": "def minCost(self, s, cost)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostold(self, s, cost): :type s: str :type cost: List[int] :rtype: int
- def minCost(self, s, cost): :type s: str :type cost: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostold(self, s, cost): :type s: str :type cost: List[int] :rtype: int
- def minCost(self, s, cost): :type s: str :type cost: List[int] :rtype: int
<|skeleton|>
class Sol... | 196e58cd38db846653fb074cfd0363997121a7cf | <|skeleton|>
class Solution:
def minCostold(self, s, cost):
""":type s: str :type cost: List[int] :rtype: int"""
<|body_0|>
def minCost(self, s, cost):
""":type s: str :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCostold(self, s, cost):
""":type s: str :type cost: List[int] :rtype: int"""
rtn = 0
def remove(i, j):
odd = 0
even = 0
for p in range(i, j + 1):
if p % 2 == 0:
even += cost[p]
els... | the_stack_v2_python_sparse | Minimum Deletion Cost to Avoid Repeating Letters.py | nithinveer/leetcode-solutions | train | 0 | |
b90dbbdc3fbb2f9c7d1e2bb74b7d41c93996ba93 | [
"allWord = Word.__getAllWordForLevel(level)\nrandomNumber = randint(0, len(allWord) - 1)\nrandomWord = allWord[randomNumber]\nreturn randomWord",
"if level == 'easy':\n myWordFile = open('mot_pendu/word.easy.txt', 'r')\n allWord = myWordFile.readlines()\n myWordFile.close()\nelse:\n myWordFile = open(... | <|body_start_0|>
allWord = Word.__getAllWordForLevel(level)
randomNumber = randint(0, len(allWord) - 1)
randomWord = allWord[randomNumber]
return randomWord
<|end_body_0|>
<|body_start_1|>
if level == 'easy':
myWordFile = open('mot_pendu/word.easy.txt', 'r')
... | Word | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
<|body_0|>
def __getAllWordForLevel(level):
"""Return a list of all word according to the specified level in a list form"""
<|body_1|>
def getHiddenWordFromWord(correctWord, numberO... | stack_v2_sparse_classes_36k_train_022996 | 3,092 | no_license | [
{
"docstring": "Return a word from the specifed",
"name": "getWordFromLevel",
"signature": "def getWordFromLevel(level)"
},
{
"docstring": "Return a list of all word according to the specified level in a list form",
"name": "__getAllWordForLevel",
"signature": "def __getAllWordForLevel(l... | 5 | stack_v2_sparse_classes_30k_train_009108 | Implement the Python class `Word` described below.
Class description:
Implement the Word class.
Method signatures and docstrings:
- def getWordFromLevel(level): Return a word from the specifed
- def __getAllWordForLevel(level): Return a list of all word according to the specified level in a list form
- def getHiddenW... | Implement the Python class `Word` described below.
Class description:
Implement the Word class.
Method signatures and docstrings:
- def getWordFromLevel(level): Return a word from the specifed
- def __getAllWordForLevel(level): Return a list of all word according to the specified level in a list form
- def getHiddenW... | 303e333b9601d5be8f17e4de31a44a8bdb7c6a59 | <|skeleton|>
class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
<|body_0|>
def __getAllWordForLevel(level):
"""Return a list of all word according to the specified level in a list form"""
<|body_1|>
def getHiddenWordFromWord(correctWord, numberO... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Word:
def getWordFromLevel(level):
"""Return a word from the specifed"""
allWord = Word.__getAllWordForLevel(level)
randomNumber = randint(0, len(allWord) - 1)
randomWord = allWord[randomNumber]
return randomWord
def __getAllWordForLevel(level):
"""Return a... | the_stack_v2_python_sparse | python/mr_rochel/mot_pendu/Word.py | Ryuka25/leetCode-training | train | 0 | |
7a8d8347967bbf83a59207141c208a9d5bcbab33 | [
"l, r = (0, len(s) - 1)\nwhile l < r:\n while l < r and (not s[l].isalnum()):\n l += 1\n while l < r and (not s[r].isalnum()):\n r -= 1\n if s[l].lower() != s[r].lower():\n return False\n l += 1\n r -= 1\nreturn True",
"tmp = []\nfor c in s:\n if c.isalnum():\n tmp.ap... | <|body_start_0|>
l, r = (0, len(s) - 1)
while l < r:
while l < r and (not s[l].isalnum()):
l += 1
while l < r and (not s[r].isalnum()):
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isPalindrome2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, r = (0, len(s) - 1)
while l < r:
while l ... | stack_v2_sparse_classes_36k_train_022997 | 895 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome2",
"signature": "def isPalindrome2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008857 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def isPalindrome2(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def isPalindrome2(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isPalindrome2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
l, r = (0, len(s) - 1)
while l < r:
while l < r and (not s[l].isalnum()):
l += 1
while l < r and (not s[r].isalnum()):
r -= 1
if s[l].lower() != s[r]... | the_stack_v2_python_sparse | prob125_valid_palindrome.py | Hu-Wenchao/leetcode | train | 0 | |
0e1e742ad5c20220e73e583fdd26976f642601bc | [
"dp = [0] * (n + 1)\ndp[0] = dp[1] = 1\nfor i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[-1]",
"dp1 = dp2 = 1\nfor i in range(n - 1):\n dp2, dp1 = (dp1 + dp2, dp2)\nreturn dp2"
] | <|body_start_0|>
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
dp1 = dp2 = 1
for i in range(n - 1):
dp2, dp1 = (dp1 + dp2, dp2)
return dp2
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(... | stack_v2_sparse_classes_36k_train_022998 | 660 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001147 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs1(self, n): :type n: int :rtype: int
- def climbStairs(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs1(self, n):
"""... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def climbStairs1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs1(self, n):
""":type n: int :rtype: int"""
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[-1]
def climbStairs(self, n):
""":type n: int :rtype: int"""
dp1 =... | the_stack_v2_python_sparse | DynamicProgramming/q070_climbing_stairs.py | sevenhe716/LeetCode | train | 0 | |
52f225e4b58285928faa9ac996dda1cbb2ad79be | [
"ansible_hosts = get_value('ansible', 'ansible_host_path')\nre_pattern = '^\\\\s*\\\\[(?P<host>.*)\\\\]'\nhost_list = [{'name': 'all', 'children': [{'name': 'all'}]}]\nif File.if_file_exists(ansible_hosts):\n host_dic = {'name': File.get_file_name(ansible_hosts), 'children': []}\n with open(ansible_hosts) as ... | <|body_start_0|>
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<host>.*)\\]'
host_list = [{'name': 'all', 'children': [{'name': 'all'}]}]
if File.if_file_exists(ansible_hosts):
host_dic = {'name': File.get_file_name(ansible_hosts), 'childr... | Ansible | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|body_0|>
def get_hosts():
"""返回 ansible hosts file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<h... | stack_v2_sparse_classes_36k_train_022999 | 2,028 | no_license | [
{
"docstring": "返回 ansible hosts group",
"name": "get_group",
"signature": "def get_group()"
},
{
"docstring": "返回 ansible hosts file",
"name": "get_hosts",
"signature": "def get_hosts()"
}
] | 2 | stack_v2_sparse_classes_30k_test_000695 | Implement the Python class `Ansible` described below.
Class description:
Implement the Ansible class.
Method signatures and docstrings:
- def get_group(): 返回 ansible hosts group
- def get_hosts(): 返回 ansible hosts file | Implement the Python class `Ansible` described below.
Class description:
Implement the Ansible class.
Method signatures and docstrings:
- def get_group(): 返回 ansible hosts group
- def get_hosts(): 返回 ansible hosts file
<|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|b... | 60e9481ab84628cf817fde1c52f4a15d5085e503 | <|skeleton|>
class Ansible:
def get_group():
"""返回 ansible hosts group"""
<|body_0|>
def get_hosts():
"""返回 ansible hosts file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ansible:
def get_group():
"""返回 ansible hosts group"""
ansible_hosts = get_value('ansible', 'ansible_host_path')
re_pattern = '^\\s*\\[(?P<host>.*)\\]'
host_list = [{'name': 'all', 'children': [{'name': 'all'}]}]
if File.if_file_exists(ansible_hosts):
host_d... | the_stack_v2_python_sparse | common/ansible.py | qt-pay/python-devops | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.