blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1055bcd66eb26fd5f25bd9590d33ac8817681598 | [
"self.n_cv_flt = n_cv_flt\nself.n_cv_ln = n_cv_ln\nself.cv_activation = cv_activation\nself.mp = mp\nsuper().__init__(l=l)",
"n_cv_flt, n_cv_ln = (self.n_cv_flt, self.n_cv_ln)\ncv_activation = self.cv_activation\nmp = self.mp\nmodel = Sequential()\nmodel.add(Convolution1D(n_cv_flt, n_cv_ln, activation=cv_activati... | <|body_start_0|>
self.n_cv_flt = n_cv_flt
self.n_cv_ln = n_cv_ln
self.cv_activation = cv_activation
self.mp = mp
super().__init__(l=l)
<|end_body_0|>
<|body_start_1|>
n_cv_flt, n_cv_ln = (self.n_cv_flt, self.n_cv_ln)
cv_activation = self.cv_activation
mp ... | CNNC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNC:
def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1):
"""Convolutional neural networks"""
<|body_0|>
def modeling(self, l=[49, 30, 10, 3]):
"""generate model"""
<|body_1|>
def X_reshape(self, X_train_2D, X_val_2D... | stack_v2_sparse_classes_75kplus_train_007500 | 18,128 | permissive | [
{
"docstring": "Convolutional neural networks",
"name": "__init__",
"signature": "def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1)"
},
{
"docstring": "generate model",
"name": "modeling",
"signature": "def modeling(self, l=[49, 30, 10, 3])"
},
... | 3 | null | Implement the Python class `CNNC` described below.
Class description:
Implement the CNNC class.
Method signatures and docstrings:
- def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1): Convolutional neural networks
- def modeling(self, l=[49, 30, 10, 3]): generate model
- def X_re... | Implement the Python class `CNNC` described below.
Class description:
Implement the CNNC class.
Method signatures and docstrings:
- def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1): Convolutional neural networks
- def modeling(self, l=[49, 30, 10, 3]): generate model
- def X_re... | b7e3c860280581e37c7b5254e18ff4b19c112ded | <|skeleton|>
class CNNC:
def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1):
"""Convolutional neural networks"""
<|body_0|>
def modeling(self, l=[49, 30, 10, 3]):
"""generate model"""
<|body_1|>
def X_reshape(self, X_train_2D, X_val_2D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNNC:
def __init__(self, n_cv_flt=2, n_cv_ln=3, cv_activation='relu', l=[49, 30, 10, 3], mp=1):
"""Convolutional neural networks"""
self.n_cv_flt = n_cv_flt
self.n_cv_ln = n_cv_ln
self.cv_activation = cv_activation
self.mp = mp
super().__init__(l=l)
def mod... | the_stack_v2_python_sparse | dl/kkeras.py | jskDr/jamespy_py3 | train | 5 | |
ed6310c456b58a8070e811a9d500e491daa71e2e | [
"super().__init__(reduction_data, bandwidth=bandwidth, percentile=percentile, period=period, smoothing=smoothing, config=config)\nif percentile is None:\n raise PGMException('Percentile: The percentile value must be defined and of type float or int.')\nself.period = period\nself.percentile = percentile\nself.res... | <|body_start_0|>
super().__init__(reduction_data, bandwidth=bandwidth, percentile=percentile, period=period, smoothing=smoothing, config=config)
if percentile is None:
raise PGMException('Percentile: The percentile value must be defined and of type float or int.')
self.period = perio... | Percentile | [
"Unlicense",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Percentile:
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95], config=None):
"""Args: reduction_data (StationStream or ndarray): Intensity measurement component. bandwidth (float): Bandwidth for the smoothing operation. Defa... | stack_v2_sparse_classes_75kplus_train_007501 | 3,074 | permissive | [
{
"docstring": "Args: reduction_data (StationStream or ndarray): Intensity measurement component. bandwidth (float): Bandwidth for the smoothing operation. Default is None. percentile (float): Percentile for rotation calculations. period (float): Period for smoothing (Fourier amplitude spectra) calculations. De... | 2 | stack_v2_sparse_classes_30k_test_002016 | Implement the Python class `Percentile` described below.
Class description:
Implement the Percentile class.
Method signatures and docstrings:
- def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95], config=None): Args: reduction_data (StationStream or ndarra... | Implement the Python class `Percentile` described below.
Class description:
Implement the Percentile class.
Method signatures and docstrings:
- def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95], config=None): Args: reduction_data (StationStream or ndarra... | 944667e90b5a0a01f7017a676f60e2958b1eb902 | <|skeleton|>
class Percentile:
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95], config=None):
"""Args: reduction_data (StationStream or ndarray): Intensity measurement component. bandwidth (float): Bandwidth for the smoothing operation. Defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Percentile:
def __init__(self, reduction_data, bandwidth=None, percentile=None, period=None, smoothing=None, interval=[5, 95], config=None):
"""Args: reduction_data (StationStream or ndarray): Intensity measurement component. bandwidth (float): Bandwidth for the smoothing operation. Default is None. p... | the_stack_v2_python_sparse | src/gmprocess/metrics/reduction/percentile.py | mmoschetti-usgs/groundmotion-processing | train | 0 | |
5356c0ee44f62f2c08ff4ff75157e085f853766c | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.inst_lbl = Label(self, text='Enter password for the secret of longevity')\nself.pw_lbl = Label(self, text='Password: ')\nself.pw_lbl.grid(row=1, column=0, sticky=W)\nself.pw_ent = Entry(self)\nself.pw_ent.grid(row=1, column=1, ... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.inst_lbl = Label(self, text='Enter password for the secret of longevity')
self.pw_lbl = Label(self, text='Password: ')
self.pw_lbl.grid(row=1... | GUI application which can reveal the secret of longevity. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI application which can reveal the secret of longevity."""
def __init__(self, master):
"""Initialize the frame."""
<|body_0|>
def create_widgets(self):
"""Create button, text, and entry widgets."""
<|body_1|>
def reveal(self):
... | stack_v2_sparse_classes_75kplus_train_007502 | 1,917 | no_license | [
{
"docstring": "Initialize the frame.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create button, text, and entry widgets.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "Display message based on passwor... | 3 | stack_v2_sparse_classes_30k_train_051036 | Implement the Python class `Application` described below.
Class description:
GUI application which can reveal the secret of longevity.
Method signatures and docstrings:
- def __init__(self, master): Initialize the frame.
- def create_widgets(self): Create button, text, and entry widgets.
- def reveal(self): Display m... | Implement the Python class `Application` described below.
Class description:
GUI application which can reveal the secret of longevity.
Method signatures and docstrings:
- def __init__(self, master): Initialize the frame.
- def create_widgets(self): Create button, text, and entry widgets.
- def reveal(self): Display m... | e1947161426cf53eba96debc641f058ee8cf47e3 | <|skeleton|>
class Application:
"""GUI application which can reveal the secret of longevity."""
def __init__(self, master):
"""Initialize the frame."""
<|body_0|>
def create_widgets(self):
"""Create button, text, and entry widgets."""
<|body_1|>
def reveal(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""GUI application which can reveal the secret of longevity."""
def __init__(self, master):
"""Initialize the frame."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create button, text, a... | the_stack_v2_python_sparse | Python_Programming_for_the_Absolute_Beginner/10_logevity.py | wzlwit/python | train | 0 |
e6c97b98de218a4a1496b80d657ae048f70cd08a | [
"super().__init__()\nassert hid_dim % n_heads == 0\nself.hid_dim = hid_dim\nself.n_heads = n_heads\nself.head_dim = hid_dim // n_heads\nself.fc_q = nn.Linear(in_features=hid_dim, out_features=hid_dim)\nself.fc_k = nn.Linear(in_features=hid_dim, out_features=hid_dim)\nself.fc_v = nn.Linear(in_features=hid_dim, out_f... | <|body_start_0|>
super().__init__()
assert hid_dim % n_heads == 0
self.hid_dim = hid_dim
self.n_heads = n_heads
self.head_dim = hid_dim // n_heads
self.fc_q = nn.Linear(in_features=hid_dim, out_features=hid_dim)
self.fc_k = nn.Linear(in_features=hid_dim, out_featu... | MultiHeadAttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttentionLayer:
def __init__(self, hid_dim: int, n_heads: int, dropout: float, device: str):
"""Multi/single Head Attention Layer. This layer define Q,K,V of the GateEncoderLayer Parameters ---------- hid_dim: int input hidden dimension from the first layer norm n_heads: int num... | stack_v2_sparse_classes_75kplus_train_007503 | 14,453 | permissive | [
{
"docstring": "Multi/single Head Attention Layer. This layer define Q,K,V of the GateEncoderLayer Parameters ---------- hid_dim: int input hidden dimension from the first layer norm n_heads: int number of heads for attention mechanism dropout: float dropout rate = 0.1 device: str cpu or gpu",
"name": "__in... | 2 | stack_v2_sparse_classes_30k_val_001956 | Implement the Python class `MultiHeadAttentionLayer` described below.
Class description:
Implement the MultiHeadAttentionLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim: int, n_heads: int, dropout: float, device: str): Multi/single Head Attention Layer. This layer define Q,K,V of the GateE... | Implement the Python class `MultiHeadAttentionLayer` described below.
Class description:
Implement the MultiHeadAttentionLayer class.
Method signatures and docstrings:
- def __init__(self, hid_dim: int, n_heads: int, dropout: float, device: str): Multi/single Head Attention Layer. This layer define Q,K,V of the GateE... | a6c870d4ed0788f15cfdf58c85ed5201dff60ee9 | <|skeleton|>
class MultiHeadAttentionLayer:
def __init__(self, hid_dim: int, n_heads: int, dropout: float, device: str):
"""Multi/single Head Attention Layer. This layer define Q,K,V of the GateEncoderLayer Parameters ---------- hid_dim: int input hidden dimension from the first layer norm n_heads: int num... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttentionLayer:
def __init__(self, hid_dim: int, n_heads: int, dropout: float, device: str):
"""Multi/single Head Attention Layer. This layer define Q,K,V of the GateEncoderLayer Parameters ---------- hid_dim: int input hidden dimension from the first layer norm n_heads: int number of heads f... | the_stack_v2_python_sparse | src/gated_transformers_nlp/utils/gated_transformers/encoder.py | mnguyen0226/gated_transformers_nlp | train | 2 | |
c9b56ac550246e1b0d4e6898dc2761e2e7da3f26 | [
"super(ChamferDistKDTree, self).__init__()\nself.njobs = njobs\nself.set_reduction_method(reduction)\nif self.njobs != 1:\n self.p = multiprocessing.Pool(njobs)",
"b = src.shape[0]\nif njobs != 1:\n src_tar_pairs = tuple(zip(src, tar, range(b)))\n result = self.p.map(find_nn_id_parallel, src_tar_pairs)\n... | <|body_start_0|>
super(ChamferDistKDTree, self).__init__()
self.njobs = njobs
self.set_reduction_method(reduction)
if self.njobs != 1:
self.p = multiprocessing.Pool(njobs)
<|end_body_0|>
<|body_start_1|>
b = src.shape[0]
if njobs != 1:
src_tar_pai... | Compute chamfer distances on CPU using KDTree. | ChamferDistKDTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChamferDistKDTree:
"""Compute chamfer distances on CPU using KDTree."""
def __init__(self, reduction='mean', njobs=1):
"""Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, number of parallel workers to use during eval."""
... | stack_v2_sparse_classes_75kplus_train_007504 | 5,645 | permissive | [
{
"docstring": "Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, number of parallel workers to use during eval.",
"name": "__init__",
"signature": "def __init__(self, reduction='mean', njobs=1)"
},
{
"docstring": "Batched eval of distance be... | 4 | stack_v2_sparse_classes_30k_train_033325 | Implement the Python class `ChamferDistKDTree` described below.
Class description:
Compute chamfer distances on CPU using KDTree.
Method signatures and docstrings:
- def __init__(self, reduction='mean', njobs=1): Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, n... | Implement the Python class `ChamferDistKDTree` described below.
Class description:
Compute chamfer distances on CPU using KDTree.
Method signatures and docstrings:
- def __init__(self, reduction='mean', njobs=1): Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, n... | bf152f60f287a728cc782aa53f2930154f18b2a3 | <|skeleton|>
class ChamferDistKDTree:
"""Compute chamfer distances on CPU using KDTree."""
def __init__(self, reduction='mean', njobs=1):
"""Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, number of parallel workers to use during eval."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChamferDistKDTree:
"""Compute chamfer distances on CPU using KDTree."""
def __init__(self, reduction='mean', njobs=1):
"""Initialize loss module. Args: reduction: str, reduction method. choice of mean/sum/max/min. njobs: int, number of parallel workers to use during eval."""
super(Chamfer... | the_stack_v2_python_sparse | ShapeFlow/shapeflow/layers/chamfer_layer.py | vikasTmz/SP-GAN | train | 0 |
301dc93c58e8d714cc24d48b3237fa3a868e5249 | [
"super().__init__()\nprint(config)\nself.edge_lengthscale = config.edge_lengthscale\nself.weight_edges = config.weight_edges\nself.atom_embedding = nn.Linear(config.atom_input_features, config.node_features)\nself.bn = nn.BatchNorm1d(config.node_features)\nself.dense_layers = _DenseBlock(config.conv_layers, config.... | <|body_start_0|>
super().__init__()
print(config)
self.edge_lengthscale = config.edge_lengthscale
self.weight_edges = config.weight_edges
self.atom_embedding = nn.Linear(config.atom_input_features, config.node_features)
self.bn = nn.BatchNorm1d(config.node_features)
... | GraphConv GCN with DenseNet-style connections. | DenseGCN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseGCN:
"""GraphConv GCN with DenseNet-style connections."""
def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn')):
"""Initialize class with number of input features, conv layers."""
<|body_0|>
def forward(self, g):
"""Baseline SimpleGCN : ... | stack_v2_sparse_classes_75kplus_train_007505 | 3,937 | permissive | [
{
"docstring": "Initialize class with number of input features, conv layers.",
"name": "__init__",
"signature": "def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn'))"
},
{
"docstring": "Baseline SimpleGCN : start with `atom_features`.",
"name": "forward",
"signature... | 2 | stack_v2_sparse_classes_30k_train_031756 | Implement the Python class `DenseGCN` described below.
Class description:
GraphConv GCN with DenseNet-style connections.
Method signatures and docstrings:
- def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn')): Initialize class with number of input features, conv layers.
- def forward(self, g): ... | Implement the Python class `DenseGCN` described below.
Class description:
GraphConv GCN with DenseNet-style connections.
Method signatures and docstrings:
- def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn')): Initialize class with number of input features, conv layers.
- def forward(self, g): ... | 8f3ae89bf1e03b0d8b8f940414dea14ac54d98a0 | <|skeleton|>
class DenseGCN:
"""GraphConv GCN with DenseNet-style connections."""
def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn')):
"""Initialize class with number of input features, conv layers."""
<|body_0|>
def forward(self, g):
"""Baseline SimpleGCN : ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DenseGCN:
"""GraphConv GCN with DenseNet-style connections."""
def __init__(self, config: DenseGCNConfig=DenseGCNConfig(name='densegcn')):
"""Initialize class with number of input features, conv layers."""
super().__init__()
print(config)
self.edge_lengthscale = config.edg... | the_stack_v2_python_sparse | alignn/models/densegcn.py | xdmso/alignn | train | 0 |
be9af56f449fee7bca8ae45631eb110321075705 | [
"self.access_zone = access_zone\nself.cluster = cluster\nself.mount_point = mount_point\nself.name = name\nself.mtype = mtype",
"if dictionary is None:\n return None\naccess_zone = cohesity_management_sdk.models.isilon_access_zone.IsilonAccessZone.from_dictionary(dictionary.get('accessZone')) if dictionary.get... | <|body_start_0|>
self.access_zone = access_zone
self.cluster = cluster
self.mount_point = mount_point
self.name = name
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
access_zone = cohesity_management_sdk.models.i... | Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isi... | IsilonProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluste... | stack_v2_sparse_classes_75kplus_train_007506 | 3,446 | permissive | [
{
"docstring": "Constructor for the IsilonProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): ... | 2 | stack_v2_sparse_classes_30k_train_015452 | Implement the Python class `IsilonProtectionSource` described below.
Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only ... | Implement the Python class `IsilonProtectionSource` described below.
Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IsilonProtectionSource:
"""Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonClus... | the_stack_v2_python_sparse | cohesity_management_sdk/models/isilon_protection_source.py | cohesity/management-sdk-python | train | 24 |
5acecf522ddac81599535f7e3dcba1cb307db0c2 | [
"super(DeepLSTMSeq2Seq, self).__init__(name=name)\nself._core = core\nself._use_conv_lstm = use_conv_lstm\nself._data_format = data_format",
"if self._use_conv_lstm:\n if self._data_format == 'NCHW':\n initial_inputs_formatted = tf.transpose(initial_inputs, perm=[0, 2, 3, 1])\n lstm_input_shape =... | <|body_start_0|>
super(DeepLSTMSeq2Seq, self).__init__(name=name)
self._core = core
self._use_conv_lstm = use_conv_lstm
self._data_format = data_format
<|end_body_0|>
<|body_start_1|>
if self._use_conv_lstm:
if self._data_format == 'NCHW':
initial_inp... | A deep LSTM for seq2seq output. | DeepLSTMSeq2Seq | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepLSTMSeq2Seq:
"""A deep LSTM for seq2seq output."""
def __init__(self, core, use_conv_lstm=False, data_format='NCHW', name='deep_lstm_seq2seq'):
"""Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm: Whether to use convolutional LSTM. Defaults to False (u... | stack_v2_sparse_classes_75kplus_train_007507 | 38,890 | no_license | [
{
"docstring": "Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm: Whether to use convolutional LSTM. Defaults to False (uses standard, fully-connected LSTM). data_format: The format of the input images: 'NCHW' or 'NHWC'. name: The network name. Defaults to 'deep_lstm_seq2seq'. Raises... | 4 | null | Implement the Python class `DeepLSTMSeq2Seq` described below.
Class description:
A deep LSTM for seq2seq output.
Method signatures and docstrings:
- def __init__(self, core, use_conv_lstm=False, data_format='NCHW', name='deep_lstm_seq2seq'): Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm... | Implement the Python class `DeepLSTMSeq2Seq` described below.
Class description:
A deep LSTM for seq2seq output.
Method signatures and docstrings:
- def __init__(self, core, use_conv_lstm=False, data_format='NCHW', name='deep_lstm_seq2seq'): Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm... | 358a09d491aab0794df9cc7f3f8064430a78fbc3 | <|skeleton|>
class DeepLSTMSeq2Seq:
"""A deep LSTM for seq2seq output."""
def __init__(self, core, use_conv_lstm=False, data_format='NCHW', name='deep_lstm_seq2seq'):
"""Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm: Whether to use convolutional LSTM. Defaults to False (u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeepLSTMSeq2Seq:
"""A deep LSTM for seq2seq output."""
def __init__(self, core, use_conv_lstm=False, data_format='NCHW', name='deep_lstm_seq2seq'):
"""Constructs a DeepLSTMSeq2Seq. Args: core: The RNN core to run. use_conv_lstm: Whether to use convolutional LSTM. Defaults to False (uses standard,... | the_stack_v2_python_sparse | architectures/rnn_architectures.py | zwbgood6/temporal-hierarchy | train | 0 |
3d253f2c18f28956acc91f103fa970ccf1a9e4b8 | [
"self.sess = tf.Session()\nvocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)\nself.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)\nself.model = model_utils.create_model(self.sess, True)\nself.model.batch_size = 1",
"token_ids = data_utils.sentence_to_token_ids(sentenc... | <|body_start_0|>
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
self.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)
self.model = model_utils.create_model(self.sess, True)
self.model.batch_size = 1
<|end_bod... | ChatBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_75kplus_train_007508 | 2,435 | no_license | [
{
"docstring": "Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Talk with the chatbot! Args: sentence: Sentence to be... | 2 | stack_v2_sparse_classes_30k_train_018766 | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
... | the_stack_v2_python_sparse | python/gelsto_SpeakEasy-AI/SpeakEasy-AI-master/model/chat_bot.py | LiuFang816/SALSTM_py_data | train | 10 | |
0e7d7112e00f2ed69f89efce6ba7527a40cb9a7a | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nself.X_s = np.zeros((ac_samples, 1))\nself.X_s = np.linspace(start=bounds[0], stop=bounds[1], num=ac_samples, endpoint=True)\nself.X_s = self.X_s.reshape(ac_samples, 1)\nself.xsi = xsi\nself.minimize = minimize",
"m_sample, sigma = self.gp.predict(self.X_s)\n... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
self.X_s = np.zeros((ac_samples, 1))
self.X_s = np.linspace(start=bounds[0], stop=bounds[1], num=ac_samples, endpoint=True)
self.X_s = self.X_s.reshape(ac_samples, 1)
self.xsi = xsi
self.minimize... | Performs Bayesian optimization on a noiseless 1D Gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Arguments --------- - f : is the black-box function to be optimized -... | stack_v2_sparse_classes_75kplus_train_007509 | 5,622 | no_license | [
{
"docstring": "Class constructor Arguments --------- - f : is the black-box function to be optimized - X_init: : numpy.ndarray Array of shape (t, 1) representing the inputs already sampled with the black-box function - Y_init : numpy.ndarray Array of shape (t, 1) representing the outputs of the black-box funct... | 3 | stack_v2_sparse_classes_30k_train_021635 | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Arguments --... | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Arguments --... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Arguments --------- - f : is the black-box function to be optimized -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Arguments --------- - f : is the black-box function to be optimized - X_init: : nu... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
d6a973c68897573479cd19f74d891bd90cbae3e6 | [
"serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nself.perform_create(serializer)\nheaders = self.get_success_headers(serializer.data)\nuser = serializer.instance\nif user.email:\n url = get_password_reset_url(request, user)\n created_by_name = '{} {}'.format(req... | <|body_start_0|>
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
user = serializer.instance
if user.email:
url = get_password_rese... | ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens for a user. Attributes: queryset: django queryset, note 'auth_token' is selected w... | PFBUserViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PFBUserViewSet:
"""ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens for a user. Attributes: queryset: django... | stack_v2_sparse_classes_75kplus_train_007510 | 9,529 | permissive | [
{
"docstring": "Override create to send registration email after user creation Emails are only sent if the user is created with an email address Args: request (rest_framework.request.Request): request object for creation",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
... | 3 | stack_v2_sparse_classes_30k_train_004083 | Implement the Python class `PFBUserViewSet` described below.
Class description:
ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens f... | Implement the Python class `PFBUserViewSet` described below.
Class description:
ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens f... | 620a5f4dc975891aa3b1266ced3f331fc17de19d | <|skeleton|>
class PFBUserViewSet:
"""ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens for a user. Attributes: queryset: django... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PFBUserViewSet:
"""ViewSet responsible for creating/updating/deleting users/tokens This view set powers the `/api/users` endpoints. This includes creating, reading, updating, deleting users in addition to changing passwords and generating/retrieving tokens for a user. Attributes: queryset: django queryset, no... | the_stack_v2_python_sparse | src/django/users/views.py | azavea/pfb-network-connectivity | train | 41 |
f4f355201958c1663df5f801036af340cb2aa585 | [
"super(DiceLoss, self).__init__()\nself.soft_max = Softmax(dim=1)\nself.weights = weights",
"outputs = self.soft_max(outputs.float())\nfor i, w in enumerate(self.weights):\n targets[:, i, :, :] = targets[:, i, :, :] * w\noutputs = outputs.view(-1)\ntargets = targets.view(-1)\nintersection = (outputs * targets)... | <|body_start_0|>
super(DiceLoss, self).__init__()
self.soft_max = Softmax(dim=1)
self.weights = weights
<|end_body_0|>
<|body_start_1|>
outputs = self.soft_max(outputs.float())
for i, w in enumerate(self.weights):
targets[:, i, :, :] = targets[:, i, :, :] * w
... | Dice loss used for the segmentation tasks. | DiceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceLoss:
"""Dice loss used for the segmentation tasks."""
def __init__(self, weights: list=[]):
"""Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class."""
<|body_0|>
def forward(self, outputs: Tensor, targets: Ten... | stack_v2_sparse_classes_75kplus_train_007511 | 2,998 | permissive | [
{
"docstring": "Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class.",
"name": "__init__",
"signature": "def __init__(self, weights: list=[])"
},
{
"docstring": "Computes dice loss between the input and the target values. Parameters ------... | 2 | stack_v2_sparse_classes_30k_train_021792 | Implement the Python class `DiceLoss` described below.
Class description:
Dice loss used for the segmentation tasks.
Method signatures and docstrings:
- def __init__(self, weights: list=[]): Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class.
- def forward(sel... | Implement the Python class `DiceLoss` described below.
Class description:
Dice loss used for the segmentation tasks.
Method signatures and docstrings:
- def __init__(self, weights: list=[]): Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class.
- def forward(sel... | 7187b78463136eef140893b216d1d311b20c827e | <|skeleton|>
class DiceLoss:
"""Dice loss used for the segmentation tasks."""
def __init__(self, weights: list=[]):
"""Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class."""
<|body_0|>
def forward(self, outputs: Tensor, targets: Ten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiceLoss:
"""Dice loss used for the segmentation tasks."""
def __init__(self, weights: list=[]):
"""Initializes a dice loss function. Parameters ---------- weights : list Rescaling weights given to each class."""
super(DiceLoss, self).__init__()
self.soft_max = Softmax(dim=1)
... | the_stack_v2_python_sparse | carotids/segmentation/loss_functions.py | kostelansky17/carotids | train | 2 |
cc15c1862e71198d442b53395aa4b545857c9cbd | [
"self.env = env\nself.env_info = env_info\nself.hyper_params = hyper_params\nself.learner_cfg = learner_cfg\nself.worker_cfg = worker_cfg\nself.logger_cfg = logger_cfg\nself.comm_cfg = comm_cfg\nself.log_cfg = log_cfg\nself.is_test = is_test\nself.load_from = load_from\nself.is_render = is_render\nself.render_after... | <|body_start_0|>
self.env = env
self.env_info = env_info
self.hyper_params = hyper_params
self.learner_cfg = learner_cfg
self.worker_cfg = worker_cfg
self.logger_cfg = logger_cfg
self.comm_cfg = comm_cfg
self.log_cfg = log_cfg
self.is_test = is_tes... | General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs for worker class logger_cfg (Con... | ApeX | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs ... | stack_v2_sparse_classes_75kplus_train_007512 | 7,394 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, env_info: ConfigDict, hyper_params: ConfigDict, learner_cfg: ConfigDict, worker_cfg: ConfigDict, logger_cfg: ConfigDict, comm_cfg: ConfigDict, log_cfg: ConfigDict, is_test: bool, load_from: str, is_render: b... | 4 | stack_v2_sparse_classes_30k_train_026742 | Implement the Python class `ApeX` described below.
Class description:
General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner ... | Implement the Python class `ApeX` described below.
Class description:
General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner ... | fdfac4e7056ee5a9d5b48b7b9653ce844a03ca22 | <|skeleton|>
class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApeX:
"""General Ape-X architecture for distributed training. Attributes: rank (int): rank (ID) of worker env_info (ConfigDict): information about environment hyper_params (ConfigDict): algorithm hyperparameters learner_cfg (ConfigDict): configs for learner class worker_cfg (ConfigDict): configs for worker cl... | the_stack_v2_python_sparse | rl_algorithms/common/apex/architecture.py | medipixel/rl_algorithms | train | 525 |
38081f90707050b397ca7704e7d267b9cbaf43bf | [
"if translate and any(self.translation):\n glTranslated(*self.translation)\nif (scale or rotate) and any(self.center):\n glTranslated(*self.center)\n centered = 1\nelse:\n centered = 0\nrx, ry, rz, ra = self.rotation\nif rotate and ra:\n glRotated(ra * RADTODEG, rx, ry, rz)\nif 'scale' in self.__dict... | <|body_start_0|>
if translate and any(self.translation):
glTranslated(*self.translation)
if (scale or rotate) and any(self.center):
glTranslated(*self.center)
centered = 1
else:
centered = 0
rx, ry, rz, ra = self.rotation
if rotate ... | Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly setup and restored (even when you have exceeded the matrix stack depth). Refer... | Transform | [
"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 Transform:
"""Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly setup and restored (even when you have ex... | stack_v2_sparse_classes_75kplus_train_007513 | 4,428 | permissive | [
{
"docstring": "Perform the actual alteration of the current matrix",
"name": "transform",
"signature": "def transform(self, mode=None, translate=1, scale=1, rotate=1)"
},
{
"docstring": "Calculate the bounding volume for this node The bounding volume for a grouping node is the union of it's chi... | 3 | stack_v2_sparse_classes_30k_val_001233 | Implement the Python class `Transform` described below.
Class description:
Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly se... | Implement the Python class `Transform` described below.
Class description:
Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly se... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class Transform:
"""Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly setup and restored (even when you have ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transform:
"""Transform node based on VRML 97 Transform The Transform node provides a fairly robust implementation of encapsulated local coordinate setup. You can set translation, rotation, scale, scaleOrientation and center and have the matrices properly setup and restored (even when you have exceeded the ma... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/transform.py | alexus37/AugmentedRealityChess | train | 1 |
8a5ddf7986876a6b80557d93135cfa1e5dc3105a | [
"keys = ['Injuries', 'Deaths', 'Number of Events']\nfile = './FilteredData/filteredData.csv'\nagg = YearlyEventAggregator(file)\nk = agg.getKeys()\nself.assertEqual(len(keys), len(k))\nself.assertEqual(set(keys), set(k))",
"file = './FilteredData/filteredData.csv'\nagg = YearlyEventAggregator(file)\nfor a in agg.... | <|body_start_0|>
keys = ['Injuries', 'Deaths', 'Number of Events']
file = './FilteredData/filteredData.csv'
agg = YearlyEventAggregator(file)
k = agg.getKeys()
self.assertEqual(len(keys), len(k))
self.assertEqual(set(keys), set(k))
<|end_body_0|>
<|body_start_1|>
... | AggregatorTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregatorTests:
def test_keysValid(self):
"""Tests keys valid"""
<|body_0|>
def test_lengthAll(self):
"""Tests length valid with each key type"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
keys = ['Injuries', 'Deaths', 'Number of Events']
... | stack_v2_sparse_classes_75kplus_train_007514 | 750 | no_license | [
{
"docstring": "Tests keys valid",
"name": "test_keysValid",
"signature": "def test_keysValid(self)"
},
{
"docstring": "Tests length valid with each key type",
"name": "test_lengthAll",
"signature": "def test_lengthAll(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047050 | Implement the Python class `AggregatorTests` described below.
Class description:
Implement the AggregatorTests class.
Method signatures and docstrings:
- def test_keysValid(self): Tests keys valid
- def test_lengthAll(self): Tests length valid with each key type | Implement the Python class `AggregatorTests` described below.
Class description:
Implement the AggregatorTests class.
Method signatures and docstrings:
- def test_keysValid(self): Tests keys valid
- def test_lengthAll(self): Tests length valid with each key type
<|skeleton|>
class AggregatorTests:
def test_keys... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class AggregatorTests:
def test_keysValid(self):
"""Tests keys valid"""
<|body_0|>
def test_lengthAll(self):
"""Tests length valid with each key type"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AggregatorTests:
def test_keysValid(self):
"""Tests keys valid"""
keys = ['Injuries', 'Deaths', 'Number of Events']
file = './FilteredData/filteredData.csv'
agg = YearlyEventAggregator(file)
k = agg.getKeys()
self.assertEqual(len(keys), len(k))
self.asse... | the_stack_v2_python_sparse | rb2540/AggregatorTests.py | ds-ga-1007/final_project | train | 0 | |
24ea3049febb0612e9732a32fba56af2ee94e844 | [
"profile = self.get_object()\nmanager = get_object_or_404(User, pk=manager_pk)\nprofile.managers.add(manager)\nprofile.save()\nreturn Response('success')",
"profile = self.get_object()\nmanager = get_object_or_404(User, pk=manager_pk)\nprofile.managers.remove(manager)\nprofile.save()\nreturn Response('success')"
... | <|body_start_0|>
profile = self.get_object()
manager = get_object_or_404(User, pk=manager_pk)
profile.managers.add(manager)
profile.save()
return Response('success')
<|end_body_0|>
<|body_start_1|>
profile = self.get_object()
manager = get_object_or_404(User, pk=... | ServiceViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceViewSet:
def add_manager(self, request, manager_pk, pk=None):
"""TODO: restrict access to only certain admin levels"""
<|body_0|>
def remove_manager(self, request, manager_pk, pk=None):
"""TODO: restrict access to only certain admin levels"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_007515 | 1,703 | permissive | [
{
"docstring": "TODO: restrict access to only certain admin levels",
"name": "add_manager",
"signature": "def add_manager(self, request, manager_pk, pk=None)"
},
{
"docstring": "TODO: restrict access to only certain admin levels",
"name": "remove_manager",
"signature": "def remove_manage... | 2 | null | Implement the Python class `ServiceViewSet` described below.
Class description:
Implement the ServiceViewSet class.
Method signatures and docstrings:
- def add_manager(self, request, manager_pk, pk=None): TODO: restrict access to only certain admin levels
- def remove_manager(self, request, manager_pk, pk=None): TODO... | Implement the Python class `ServiceViewSet` described below.
Class description:
Implement the ServiceViewSet class.
Method signatures and docstrings:
- def add_manager(self, request, manager_pk, pk=None): TODO: restrict access to only certain admin levels
- def remove_manager(self, request, manager_pk, pk=None): TODO... | 2ae6e287266262557268f080cff821a736d6ec8b | <|skeleton|>
class ServiceViewSet:
def add_manager(self, request, manager_pk, pk=None):
"""TODO: restrict access to only certain admin levels"""
<|body_0|>
def remove_manager(self, request, manager_pk, pk=None):
"""TODO: restrict access to only certain admin levels"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServiceViewSet:
def add_manager(self, request, manager_pk, pk=None):
"""TODO: restrict access to only certain admin levels"""
profile = self.get_object()
manager = get_object_or_404(User, pk=manager_pk)
profile.managers.add(manager)
profile.save()
return Respons... | the_stack_v2_python_sparse | backend/service/viewsets.py | adabutch/account_tracker | train | 0 | |
8abc9a42bca7cc67b42d28144749bd41945ad14d | [
"nums = list(range(1, n + 1))\nnums.sort(key=str)\nreturn nums",
"stack = list(range(min(9, n), 0, -1))\nres = []\nwhile len(stack) > 0:\n num = stack.pop()\n stack.extend(filter(lambda x: x <= n, range(num * 10 + 9, num * 10 - 1, -1)))\n res.append(num)\nreturn res",
"if n < 1:\n return []\n\ndef a... | <|body_start_0|>
nums = list(range(1, n + 1))
nums.sort(key=str)
return nums
<|end_body_0|>
<|body_start_1|>
stack = list(range(min(9, n), 0, -1))
res = []
while len(stack) > 0:
num = stack.pop()
stack.extend(filter(lambda x: x <= n, range(num * 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrder2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder3(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_007516 | 1,999 | no_license | [
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrder",
"signature": "def lexicalOrder(self, n)"
},
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrder2",
"signature": "def lexicalOrder2(self, n)"
},
{
"docstring": ":type n: int :rtype: List[in... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): :type n: int :rtype: List[int]
- def lexicalOrder2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder3(self, n): :type n: int :rtype: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrder(self, n): :type n: int :rtype: List[int]
- def lexicalOrder2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder3(self, n): :type n: int :rtype: List[int... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrder2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder3(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
nums = list(range(1, n + 1))
nums.sort(key=str)
return nums
def lexicalOrder2(self, n):
""":type n: int :rtype: List[int]"""
stack = list(range(min(9, n), 0, -1))
res = []
... | the_stack_v2_python_sparse | code386LexicographicalNumbers.py | cybelewang/leetcode-python | train | 0 | |
e0efc7641d507687254166a292d25c5d7c10e96e | [
"super().__init__('pod_process_smap_{}_kb'.format(memory_type), 'Container smap used {}'.format(memory_type.capitalize()))\nself.memory_type = memory_type\nself.pids = pids",
"results: List[Tuple[Dict[str, Any], Union[int, float]]] = []\nfor pid in [p for p in listdir('/proc/') if NUMBER_RE.match(p)] if self.pids... | <|body_start_0|>
super().__init__('pod_process_smap_{}_kb'.format(memory_type), 'Container smap used {}'.format(memory_type.capitalize()))
self.memory_type = memory_type
self.pids = pids
<|end_body_0|>
<|body_start_1|>
results: List[Tuple[Dict[str, Any], Union[int, float]]] = []
... | MemoryMapProvider | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoryMapProvider:
def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None):
"""memory_type: can be rss, pss or size pids: the list of pids or none"""
<|body_0|>
def get_data(self) -> List[Tuple[Dict[str, Any], Union[int, float]]]:
"""Should be defi... | stack_v2_sparse_classes_75kplus_train_007517 | 3,137 | permissive | [
{
"docstring": "memory_type: can be rss, pss or size pids: the list of pids or none",
"name": "__init__",
"signature": "def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None)"
},
{
"docstring": "Should be defined in the specific provider",
"name": "get_data",
"signatu... | 2 | null | Implement the Python class `MemoryMapProvider` described below.
Class description:
Implement the MemoryMapProvider class.
Method signatures and docstrings:
- def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None): memory_type: can be rss, pss or size pids: the list of pids or none
- def get_data(s... | Implement the Python class `MemoryMapProvider` described below.
Class description:
Implement the MemoryMapProvider class.
Method signatures and docstrings:
- def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None): memory_type: can be rss, pss or size pids: the list of pids or none
- def get_data(s... | 733f3eace5393539a170455038a27d42682bf4f5 | <|skeleton|>
class MemoryMapProvider:
def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None):
"""memory_type: can be rss, pss or size pids: the list of pids or none"""
<|body_0|>
def get_data(self) -> List[Tuple[Dict[str, Any], Union[int, float]]]:
"""Should be defi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemoryMapProvider:
def __init__(self, memory_type: str='pss', pids: Optional[List[str]]=None):
"""memory_type: can be rss, pss or size pids: the list of pids or none"""
super().__init__('pod_process_smap_{}_kb'.format(memory_type), 'Container smap used {}'.format(memory_type.capitalize()))
... | the_stack_v2_python_sparse | c2cwsgiutils/metrics.py | jhutchings1/c2cwsgiutils | train | 0 | |
d30b470e4a85426f9466269f5dc90980267a1fcc | [
"ret = []\np_counter = collections.Counter(p)\ns_counter = collections.Counter(s[:len(p) - 1])\nfor i in range(len(p) - 1, len(s)):\n s_counter[s[i]] += 1\n pre_i = i - len(p) + 1\n if s_counter == p_counter:\n ret.append(pre_i)\n s_counter[s[pre_i]] -= 1\n if s_counter[s[pre_i]] == 0:\n ... | <|body_start_0|>
ret = []
p_counter = collections.Counter(p)
s_counter = collections.Counter(s[:len(p) - 1])
for i in range(len(p) - 1, len(s)):
s_counter[s[i]] += 1
pre_i = i - len(p) + 1
if s_counter == p_counter:
ret.append(pre_i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
p_coun... | stack_v2_sparse_classes_75kplus_train_007518 | 1,384 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002097 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
class Solution... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
ret = []
p_counter = collections.Counter(p)
s_counter = collections.Counter(s[:len(p) - 1])
for i in range(len(p) - 1, len(s)):
s_counter[s[i]] += 1
pre_i =... | the_stack_v2_python_sparse | problems/findAnagrams.py | joddiy/leetcode | train | 1 | |
96c56b5e1318bb37994c1186f8e6027a9be4ca12 | [
"if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:\n logger.debug('Redirect to home/rsp/login/init...')\n return redirect('vfw_home:watts_rsp:login_init')\nelif settings.DEBUG:\n return redirect('vfw_home:login')\nelse:\n raise Http404",
"if not request.user.is_authenticated:\n ... | <|body_start_0|>
if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:
logger.debug('Redirect to home/rsp/login/init...')
return redirect('vfw_home:watts_rsp:login_init')
elif settings.DEBUG:
return redirect('vfw_home:login')
else:
... | LoginView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post a... | stack_v2_sparse_classes_75kplus_train_007519 | 37,263 | permissive | [
{
"docstring": ":param request: :type request: :return: :rtype:",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post and redirect to watts (django-watts-rsp/... | 2 | stack_v2_sparse_classes_30k_train_035429 | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def post(self, request): :param request: :type request: :return: :rtype:
- def dispatch(self, request, *args, **kwargs): When clicked on login, this is the first(?) function to... | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def post(self, request): :param request: :type request: :return: :rtype:
- def dispatch(self, request, *args, **kwargs): When clicked on login, this is the first(?) function to... | 9055095cbe796d6d6e2ce744d727ff60e27e09ed | <|skeleton|>
class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:
logger.debug('Redirect to home/rsp/login/init...')
return redirect('vfw_home:watts_rsp:login_init')
el... | the_stack_v2_python_sparse | vfw_home/views.py | VForWaTer/vforwater-portal | train | 8 | |
19b4d6d334a37f3ae4c63af5eca2faa5c9d9946c | [
"self.n_state = n_state\nself.n_mess = n_mess\nself.n_act = n_act\nself.n_runs = n_runs\nself.alpha = alpha0\nself.eps = eps0\nself.eps_decay = eps0_decay\nself.mode = mode\nself.q0 = np.zeros((n_runs, n_state, n_mess))\nself.q1 = np.zeros((n_runs, n_mess, n_act))\nself.s0 = None\nself.s1 = None\nself.m0 = None\nse... | <|body_start_0|>
self.n_state = n_state
self.n_mess = n_mess
self.n_act = n_act
self.n_runs = n_runs
self.alpha = alpha0
self.eps = eps0
self.eps_decay = eps0_decay
self.mode = mode
self.q0 = np.zeros((n_runs, n_state, n_mess))
self.q1 = np... | Independent Q-Learning. | IQL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IQL:
"""Independent Q-Learning."""
def __init__(self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0.1, eps0_decay=0, mode=0, **kwargs):
"""Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int): Number of actions n_runs (int): Number of runs alpha0 (f... | stack_v2_sparse_classes_75kplus_train_007520 | 12,421 | permissive | [
{
"docstring": "Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int): Number of actions n_runs (int): Number of runs alpha0 (float): Step size eps0 (float): Initial exploration rate eps0_decay (float): Decay of exploration rate per step mode (int): 0 for communication, 1 for fixed ... | 4 | stack_v2_sparse_classes_30k_train_002084 | Implement the Python class `IQL` described below.
Class description:
Independent Q-Learning.
Method signatures and docstrings:
- def __init__(self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0.1, eps0_decay=0, mode=0, **kwargs): Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int):... | Implement the Python class `IQL` described below.
Class description:
Independent Q-Learning.
Method signatures and docstrings:
- def __init__(self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0.1, eps0_decay=0, mode=0, **kwargs): Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int):... | 323438a2ff5814712faf1be80048459c1a556d72 | <|skeleton|>
class IQL:
"""Independent Q-Learning."""
def __init__(self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0.1, eps0_decay=0, mode=0, **kwargs):
"""Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int): Number of actions n_runs (int): Number of runs alpha0 (f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IQL:
"""Independent Q-Learning."""
def __init__(self, n_state, n_mess, n_act, n_runs, alpha0=0.1, eps0=0.1, eps0_decay=0, mode=0, **kwargs):
"""Args: n_state (int): Number of states n_mess (int): Number of messages n_act (int): Number of actions n_runs (int): Number of runs alpha0 (float): Step s... | the_stack_v2_python_sparse | signaling-games/algs/model_free_value/q_learning.py | vbhatt-cs/inference-based-messaging | train | 4 |
dd8cb901314d01bc94555425be18fac77e4339af | [
"if not s:\n return ''\nn, length, start, end = (len(s), 0, 0, 0)\nmemo = {}\nfor j in range(n):\n for i in range(j, -1, -1):\n memo[i, j] = i == j or (s[i] == s[j] and (i + 1 == j or memo[i + 1, j - 1]))\n if memo[i, j] and j - i >= length:\n start, end = (i, j)\n length =... | <|body_start_0|>
if not s:
return ''
n, length, start, end = (len(s), 0, 0, 0)
memo = {}
for j in range(n):
for i in range(j, -1, -1):
memo[i, j] = i == j or (s[i] == s[j] and (i + 1 == j or memo[i + 1, j - 1]))
if memo[i, j] and j ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_007521 | 3,483 | permissive | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
},
{
"docstring": ":type s: str :rtype:... | 4 | stack_v2_sparse_classes_30k_train_042766 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str
-... | fb8cf0e64606a2a76a6141bb0e9ccd143c30f07c | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return ''
n, length, start, end = (len(s), 0, 0, 0)
memo = {}
for j in range(n):
for i in range(j, -1, -1):
memo[i, j] = i == j or (s[i] == s[j] an... | the_stack_v2_python_sparse | leetcode/M0005_Longest_Palindromic_Substring.py | jjmoo/daily | train | 1 | |
406e7a662ebcb8b3caa23df4ad31700577c9f085 | [
"self.fets_eval = FETS3D8H(mats_eval=self.mats_eval)\nsupport_slices = [[(0, slice(None), slice(None), 0, slice(None), slice(None))], [(slice(None), 0, slice(None), slice(None), 0, slice(None))], [(slice(None), slice(None), 0, slice(None), slice(None), 0)]]\nsupport_dirs = [[0, 1, 2]]\nloading_slices = [(-1, slice(... | <|body_start_0|>
self.fets_eval = FETS3D8H(mats_eval=self.mats_eval)
support_slices = [[(0, slice(None), slice(None), 0, slice(None), slice(None))], [(slice(None), 0, slice(None), slice(None), 0, slice(None))], [(slice(None), slice(None), 0, slice(None), slice(None), 0)]]
support_dirs = [[0, 1, ... | TestMATS3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMATS3D:
def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001):
"""Assert that the symmetry is given for the applied loadings."""
<|body_0|>
def assert_stress_value(self, sig_expected, n_steps=3, load=0.0001):
"""Assert that the symmetry is gi... | stack_v2_sparse_classes_75kplus_train_007522 | 7,937 | no_license | [
{
"docstring": "Assert that the symmetry is given for the applied loadings.",
"name": "assert_symmetry_on_cube_with_clamped_face",
"signature": "def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001)"
},
{
"docstring": "Assert that the symmetry is given for the applied loadin... | 3 | stack_v2_sparse_classes_30k_train_034915 | Implement the Python class `TestMATS3D` described below.
Class description:
Implement the TestMATS3D class.
Method signatures and docstrings:
- def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001): Assert that the symmetry is given for the applied loadings.
- def assert_stress_value(self, sig_ex... | Implement the Python class `TestMATS3D` described below.
Class description:
Implement the TestMATS3D class.
Method signatures and docstrings:
- def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001): Assert that the symmetry is given for the applied loadings.
- def assert_stress_value(self, sig_ex... | 00de9f0eec52835d839a3c6c1407cac11a496339 | <|skeleton|>
class TestMATS3D:
def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001):
"""Assert that the symmetry is given for the applied loadings."""
<|body_0|>
def assert_stress_value(self, sig_expected, n_steps=3, load=0.0001):
"""Assert that the symmetry is gi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMATS3D:
def assert_symmetry_on_cube_with_clamped_face(self, load_dirs, load=0.001):
"""Assert that the symmetry is given for the applied loadings."""
self.fets_eval = FETS3D8H(mats_eval=self.mats_eval)
support_slices = [[(0, slice(None), slice(None), 0, slice(None), slice(None))], ... | the_stack_v2_python_sparse | ibvpy/mats/mats3D/__test__.py | simvisage/bmcs | train | 1 | |
77c151472b7b18dbd8968fe653f75a97aa4cd29f | [
"response = ultsys_user(request.args)\nif response or response == []:\n return (response, status.HTTP_200_OK)\nreturn (None, status.HTTP_500_INTERNAL_SERVER_ERROR)",
"response = ultsys_user(request.json)\nif response or response == []:\n return (response, status.HTTP_200_OK)\nreturn (None, status.HTTP_500_I... | <|body_start_0|>
response = ultsys_user(request.args)
if response or response == []:
return (response, status.HTTP_200_OK)
return (None, status.HTTP_500_INTERNAL_SERVER_ERROR)
<|end_body_0|>
<|body_start_1|>
response = ultsys_user(request.json)
if response or respons... | Flask-RESTful resource endpoints for Drupal/Ultsys user services. | UltsysUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UltsysUser:
"""Flask-RESTful resource endpoints for Drupal/Ultsys user services."""
def get(self):
"""Simple endpoint to handle Ultsys user database calls."""
<|body_0|>
def put(self):
"""Simple endpoint to handle user update in Ultsys."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_007523 | 1,277 | no_license | [
{
"docstring": "Simple endpoint to handle Ultsys user database calls.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Simple endpoint to handle user update in Ultsys.",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "Simple endpoint to handle creat... | 3 | stack_v2_sparse_classes_30k_train_009813 | Implement the Python class `UltsysUser` described below.
Class description:
Flask-RESTful resource endpoints for Drupal/Ultsys user services.
Method signatures and docstrings:
- def get(self): Simple endpoint to handle Ultsys user database calls.
- def put(self): Simple endpoint to handle user update in Ultsys.
- def... | Implement the Python class `UltsysUser` described below.
Class description:
Flask-RESTful resource endpoints for Drupal/Ultsys user services.
Method signatures and docstrings:
- def get(self): Simple endpoint to handle Ultsys user database calls.
- def put(self): Simple endpoint to handle user update in Ultsys.
- def... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class UltsysUser:
"""Flask-RESTful resource endpoints for Drupal/Ultsys user services."""
def get(self):
"""Simple endpoint to handle Ultsys user database calls."""
<|body_0|>
def put(self):
"""Simple endpoint to handle user update in Ultsys."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UltsysUser:
"""Flask-RESTful resource endpoints for Drupal/Ultsys user services."""
def get(self):
"""Simple endpoint to handle Ultsys user database calls."""
response = ultsys_user(request.args)
if response or response == []:
return (response, status.HTTP_200_OK)
... | the_stack_v2_python_sparse | application/resources/user.py | transreductionist/API-Project-1 | train | 0 |
980f1d2c2d9074f31fb8d00b25cfe405686a42f1 | [
"Kp = 1.0\nKi = 1.0\nKd = 1.1\ncontroller = PIDController.PIDcontroller(Kp, Ki, Kd)\nself.assertEquals(Kp, controller.Kp)\nself.assertEquals(Ki, controller.Ki)\nself.assertEquals(Kd, controller.Kd)",
"Kp = 1.0\nKi = 1.0\nKd = 1.1\ncontroller = PIDController.PIDcontroller(Kp, Ki, Kd)\noutput = controller.update(10... | <|body_start_0|>
Kp = 1.0
Ki = 1.0
Kd = 1.1
controller = PIDController.PIDcontroller(Kp, Ki, Kd)
self.assertEquals(Kp, controller.Kp)
self.assertEquals(Ki, controller.Ki)
self.assertEquals(Kd, controller.Kd)
<|end_body_0|>
<|body_start_1|>
Kp = 1.0
... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def testConstructor(self):
"""Tests if the constructor assign the right variables"""
<|body_0|>
def testSisoControllerFirstStep(self):
"""Tests if the controller reacts as expected in a SISO model"""
<|body_1|>
def testMiMoControllerFirstStep(self)... | stack_v2_sparse_classes_75kplus_train_007524 | 1,904 | no_license | [
{
"docstring": "Tests if the constructor assign the right variables",
"name": "testConstructor",
"signature": "def testConstructor(self)"
},
{
"docstring": "Tests if the controller reacts as expected in a SISO model",
"name": "testSisoControllerFirstStep",
"signature": "def testSisoContr... | 4 | stack_v2_sparse_classes_30k_train_009944 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testConstructor(self): Tests if the constructor assign the right variables
- def testSisoControllerFirstStep(self): Tests if the controller reacts as expected in a SISO model
- def t... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def testConstructor(self): Tests if the constructor assign the right variables
- def testSisoControllerFirstStep(self): Tests if the controller reacts as expected in a SISO model
- def t... | 93fafa6d0cc39d1e312890c6ddeecb1437b9a7ce | <|skeleton|>
class Test:
def testConstructor(self):
"""Tests if the constructor assign the right variables"""
<|body_0|>
def testSisoControllerFirstStep(self):
"""Tests if the controller reacts as expected in a SISO model"""
<|body_1|>
def testMiMoControllerFirstStep(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test:
def testConstructor(self):
"""Tests if the constructor assign the right variables"""
Kp = 1.0
Ki = 1.0
Kd = 1.1
controller = PIDController.PIDcontroller(Kp, Ki, Kd)
self.assertEquals(Kp, controller.Kp)
self.assertEquals(Ki, controller.Ki)
s... | the_stack_v2_python_sparse | src/Control/PIDControllerTest.py | faitdivers/pyao | train | 2 | |
d9b8f35463710c70cbe96422806787e9e2d5641c | [
"res = super(sale_order, self).action_button_confirm(cr, uid, ids, context=context)\norder = self.browse(cr, uid, ids[0], context=context)\nif order.draft_auto_ship and (not order.auto_ship_id):\n self.create_auto_ship(cr, uid, order.id, order.draft_auto_ship_interval, order.draft_auto_ship_end_date, context=con... | <|body_start_0|>
res = super(sale_order, self).action_button_confirm(cr, uid, ids, context=context)
order = self.browse(cr, uid, ids[0], context=context)
if order.draft_auto_ship and (not order.auto_ship_id):
self.create_auto_ship(cr, uid, order.id, order.draft_auto_ship_interval, or... | sale_order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sale_order:
def action_button_confirm(self, cr, uid, ids, context=None):
"""Override action_button_confirm to create auto_ship if necessary on SO confirmation"""
<|body_0|>
def button_create_auto_ship(self, cr, uid, ids, context=None):
"""Form view button for creatin... | stack_v2_sparse_classes_75kplus_train_007525 | 2,947 | no_license | [
{
"docstring": "Override action_button_confirm to create auto_ship if necessary on SO confirmation",
"name": "action_button_confirm",
"signature": "def action_button_confirm(self, cr, uid, ids, context=None)"
},
{
"docstring": "Form view button for creating an auto ship from a sales order",
... | 3 | stack_v2_sparse_classes_30k_train_025327 | Implement the Python class `sale_order` described below.
Class description:
Implement the sale_order class.
Method signatures and docstrings:
- def action_button_confirm(self, cr, uid, ids, context=None): Override action_button_confirm to create auto_ship if necessary on SO confirmation
- def button_create_auto_ship(... | Implement the Python class `sale_order` described below.
Class description:
Implement the sale_order class.
Method signatures and docstrings:
- def action_button_confirm(self, cr, uid, ids, context=None): Override action_button_confirm to create auto_ship if necessary on SO confirmation
- def button_create_auto_ship(... | cf187a322335d4d0fc1e8cd2ccdace1633618ea3 | <|skeleton|>
class sale_order:
def action_button_confirm(self, cr, uid, ids, context=None):
"""Override action_button_confirm to create auto_ship if necessary on SO confirmation"""
<|body_0|>
def button_create_auto_ship(self, cr, uid, ids, context=None):
"""Form view button for creatin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sale_order:
def action_button_confirm(self, cr, uid, ids, context=None):
"""Override action_button_confirm to create auto_ship if necessary on SO confirmation"""
res = super(sale_order, self).action_button_confirm(cr, uid, ids, context=context)
order = self.browse(cr, uid, ids[0], cont... | the_stack_v2_python_sparse | ip_web_addons/models/auto_ship/sale_order.py | genpexdeveloper/gabriel_modules | train | 0 | |
f606276318a2351fc6e94fa08af7095cc6f451bc | [
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nmy_survey.store_response('English')\nself.assertIn('English', my_survey.responses)",
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nresponses = ['English', 'Spanish'... | <|body_start_0|>
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'What language did you first learn to spea... | 针对AnonymousSurvey类的测试 | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
<|body_0|>
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
question = 'What languag... | stack_v2_sparse_classes_75kplus_train_007526 | 1,576 | no_license | [
{
"docstring": "测试单个答案会被妥善地存储",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "测试三个答案会被妥善地存储",
"name": "test_store_three_responses",
"signature": "def test_store_three_responses(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000288 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对AnonymousSurvey类的测试
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案会被妥善地存储
- def test_store_three_responses(self): 测试三个答案会被妥善地存储 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
针对AnonymousSurvey类的测试
Method signatures and docstrings:
- def test_store_single_response(self): 测试单个答案会被妥善地存储
- def test_store_three_responses(self): 测试三个答案会被妥善地存储
<|skeleton|>
class TestAnonymousSurvey:
"""针对AnonymousSurvey类的测试... | e4b5b0ca9e59eeae5299f6b82783debd280ac3fc | <|skeleton|>
class TestAnonymousSurvey:
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
<|body_0|>
def test_store_three_responses(self):
"""测试三个答案会被妥善地存储"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAnonymousSurvey:
"""针对AnonymousSurvey类的测试"""
def test_store_single_response(self):
"""测试单个答案会被妥善地存储"""
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my... | the_stack_v2_python_sparse | PythonCC/Chapter11/e10_test_survey.py | geometryolife/Python_Learning | train | 0 |
d127c165eba319ac8887fa626ad397bd735ca06d | [
"hanlp.set_nature('tech', ['苹果电脑', '阿尔法狗'])\nresult, conll = hanlp.parse_tree(sentence)\nprint(result)\nhanlp.print_deps(conll)",
"sentence = hanlp.j.HanLP.parseDependency(raw)\nwordArray = sentence.getWordArray()\nhead = wordArray[index]\nwhile head is not None:\n if head == hanlp.j.CoNLLWord.ROOT:\n p... | <|body_start_0|>
hanlp.set_nature('tech', ['苹果电脑', '阿尔法狗'])
result, conll = hanlp.parse_tree(sentence)
print(result)
hanlp.print_deps(conll)
<|end_body_0|>
<|body_start_1|>
sentence = hanlp.j.HanLP.parseDependency(raw)
wordArray = sentence.getWordArray()
head = w... | HanlpProcs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HanlpProcs:
def tree(self, sentence):
"""$ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:"""
<|body_0|>
def backtrace(self, raw, index=0):
"""$ python -m sagas.bots.hanlp_procs backtrace '苹果电脑可以运行开源阿尔法狗代码吗' :param raw: :param inde... | stack_v2_sparse_classes_75kplus_train_007527 | 5,034 | permissive | [
{
"docstring": "$ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:",
"name": "tree",
"signature": "def tree(self, sentence)"
},
{
"docstring": "$ python -m sagas.bots.hanlp_procs backtrace '苹果电脑可以运行开源阿尔法狗代码吗' :param raw: :param index: :return:",
"name": "ba... | 3 | stack_v2_sparse_classes_30k_val_000567 | Implement the Python class `HanlpProcs` described below.
Class description:
Implement the HanlpProcs class.
Method signatures and docstrings:
- def tree(self, sentence): $ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:
- def backtrace(self, raw, index=0): $ python -m sagas.bots.ha... | Implement the Python class `HanlpProcs` described below.
Class description:
Implement the HanlpProcs class.
Method signatures and docstrings:
- def tree(self, sentence): $ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:
- def backtrace(self, raw, index=0): $ python -m sagas.bots.ha... | 9958d18ee5e75cf9794f546c904097dc1ff4f3a0 | <|skeleton|>
class HanlpProcs:
def tree(self, sentence):
"""$ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:"""
<|body_0|>
def backtrace(self, raw, index=0):
"""$ python -m sagas.bots.hanlp_procs backtrace '苹果电脑可以运行开源阿尔法狗代码吗' :param raw: :param inde... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HanlpProcs:
def tree(self, sentence):
"""$ python -m sagas.bots.hanlp_procs tree '苹果电脑可以运行开源阿尔法狗代码吗' :param sentence: :return:"""
hanlp.set_nature('tech', ['苹果电脑', '阿尔法狗'])
result, conll = hanlp.parse_tree(sentence)
print(result)
hanlp.print_deps(conll)
def backtra... | the_stack_v2_python_sparse | sagas/bots/hanlp_procs.py | samlet/stack | train | 3 | |
1c3dadd83631edc3c3d4db0ff8e1fc4abe279bac | [
"node = TreeNode(1)\nleftNode = TreeNode(2)\nrightNode = TreeNode(2)\nnode.left = leftNode\nnode.right = rightNode\nsol = Solution()\nself.assertEqual(sol.isSymmetric(node), True)",
"node = TreeNode(1)\nleftNode = TreeNode(2)\nrightNode = TreeNode(2)\nnode.left = leftNode\nnode.right = rightNode\nthirdLevelRightN... | <|body_start_0|>
node = TreeNode(1)
leftNode = TreeNode(2)
rightNode = TreeNode(2)
node.left = leftNode
node.right = rightNode
sol = Solution()
self.assertEqual(sol.isSymmetric(node), True)
<|end_body_0|>
<|body_start_1|>
node = TreeNode(1)
leftNo... | TestSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSolution:
def test_symmetricTreeCase1(self):
"""1 / 2 2"""
<|body_0|>
def test_symmetricTreeCase2(self):
"""1 / 2 2 / \\ / 3 3"""
<|body_1|>
def test_symmetricTreeCase3(self):
"""1 / 2 2 / \\ / 3 4 3"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_007528 | 1,844 | no_license | [
{
"docstring": "1 / 2 2",
"name": "test_symmetricTreeCase1",
"signature": "def test_symmetricTreeCase1(self)"
},
{
"docstring": "1 / 2 2 / \\\\ / 3 3",
"name": "test_symmetricTreeCase2",
"signature": "def test_symmetricTreeCase2(self)"
},
{
"docstring": "1 / 2 2 / \\\\ / 3 4 3",
... | 3 | stack_v2_sparse_classes_30k_train_003188 | Implement the Python class `TestSolution` described below.
Class description:
Implement the TestSolution class.
Method signatures and docstrings:
- def test_symmetricTreeCase1(self): 1 / 2 2
- def test_symmetricTreeCase2(self): 1 / 2 2 / \\ / 3 3
- def test_symmetricTreeCase3(self): 1 / 2 2 / \\ / 3 4 3 | Implement the Python class `TestSolution` described below.
Class description:
Implement the TestSolution class.
Method signatures and docstrings:
- def test_symmetricTreeCase1(self): 1 / 2 2
- def test_symmetricTreeCase2(self): 1 / 2 2 / \\ / 3 3
- def test_symmetricTreeCase3(self): 1 / 2 2 / \\ / 3 4 3
<|skeleton|>... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class TestSolution:
def test_symmetricTreeCase1(self):
"""1 / 2 2"""
<|body_0|>
def test_symmetricTreeCase2(self):
"""1 / 2 2 / \\ / 3 3"""
<|body_1|>
def test_symmetricTreeCase3(self):
"""1 / 2 2 / \\ / 3 4 3"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSolution:
def test_symmetricTreeCase1(self):
"""1 / 2 2"""
node = TreeNode(1)
leftNode = TreeNode(2)
rightNode = TreeNode(2)
node.left = leftNode
node.right = rightNode
sol = Solution()
self.assertEqual(sol.isSymmetric(node), True)
def t... | the_stack_v2_python_sparse | tree/test_symmetricTree.py | gerrycfchang/leetcode-python | train | 2 | |
9ab363e3c0bf7f9a5cf2c6c7b25269eae61f7c20 | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"seq_len = x.sh... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
self.dr... | Encoder class | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask):
"""Call Method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
supe... | stack_v2_sparse_classes_75kplus_train_007529 | 8,232 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1)"
},
{
"docstring": "Call Method",
"name": "call",
"signature": "def call(self, x, training, mask)"
}
] | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor
- def call(self, x, training, mask): Call Method | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor
- def call(self, x, training, mask): Call Method
<|skeleton|>
class Encoder:
"""Encoder class... | 131be8fcf61aafb5a4ddc0b3853ba625560eb786 | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask):
"""Call Method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encodi... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | zahraaassaad/holbertonschool-machine_learning | train | 1 |
f16c84514defbbc1319eead11515ff60d318300d | [
"self.min_val = min_val\nself.max_val = max_val\nself.alpha = alpha\nself.beta = beta",
"if X.pixeltype != 'float':\n raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')\ninsuffix = X._libsuffix\ncast_fn = utils.get_lib_fn('sigmoidAntsImage%s' % insuffix)\ncasted_ptr ... | <|body_start_0|>
self.min_val = min_val
self.max_val = max_val
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
if X.pixeltype != 'float':
raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')
insuff... | Transform an image using a sigmoid function | SigmoidIntensity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SigmoidIntensity:
"""Transform an image using a sigmoid function"""
def __init__(self, min_val, max_val, alpha, beta):
"""Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta... | stack_v2_sparse_classes_75kplus_train_007530 | 24,297 | permissive | [
{
"docstring": "Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta : flaot beta value for sigmoid Example ------- >>> import ants >>> sigscaler = ants.contrib.SigmoidIntensity(0,1,1,1)",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_049162 | Implement the Python class `SigmoidIntensity` described below.
Class description:
Transform an image using a sigmoid function
Method signatures and docstrings:
- def __init__(self, min_val, max_val, alpha, beta): Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float... | Implement the Python class `SigmoidIntensity` described below.
Class description:
Transform an image using a sigmoid function
Method signatures and docstrings:
- def __init__(self, min_val, max_val, alpha, beta): Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class SigmoidIntensity:
"""Transform an image using a sigmoid function"""
def __init__(self, min_val, max_val, alpha, beta):
"""Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SigmoidIntensity:
"""Transform an image using a sigmoid function"""
def __init__(self, min_val, max_val, alpha, beta):
"""Initialize a SigmoidIntensity transform Arguments --------- min_val : float minimum value max_val : float maximum value alpha : float alpha value for sigmoid beta : flaot beta... | the_stack_v2_python_sparse | ants/contrib/sampling/transforms.py | ANTsX/ANTsPy | train | 483 |
426b8b52dbe77606a7859c50635fd81da02f943a | [
"super(TurbiniaCeleryWorker, self).__init__()\njob_manager.JobsManager.DeregisterJobs(jobs_denylist, jobs_allowlist)\ndisabled_jobs = list(config.DISABLED_JOBS) if config.DISABLED_JOBS else []\ndisabled_jobs = [j.lower() for j in disabled_jobs]\nif jobs_allowlist:\n disabled_jobs = list(set(disabled_jobs) - set(... | <|body_start_0|>
super(TurbiniaCeleryWorker, self).__init__()
job_manager.JobsManager.DeregisterJobs(jobs_denylist, jobs_allowlist)
disabled_jobs = list(config.DISABLED_JOBS) if config.DISABLED_JOBS else []
disabled_jobs = [j.lower() for j in disabled_jobs]
if jobs_allowlist:
... | Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app | TurbiniaCeleryWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TurbiniaCeleryWorker:
"""Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app"""
def __init__(self, jobs_denylist=None, jobs_allowlist=None):
"""Initialization for celery worker. Args: jobs_denylist (Optional[list[str]]): Jobs we will exclude from running ... | stack_v2_sparse_classes_75kplus_train_007531 | 46,828 | permissive | [
{
"docstring": "Initialization for celery worker. Args: jobs_denylist (Optional[list[str]]): Jobs we will exclude from running jobs_allowlist (Optional[list[str]]): The only Jobs we will include to run",
"name": "__init__",
"signature": "def __init__(self, jobs_denylist=None, jobs_allowlist=None)"
},
... | 2 | stack_v2_sparse_classes_30k_train_036273 | Implement the Python class `TurbiniaCeleryWorker` described below.
Class description:
Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app
Method signatures and docstrings:
- def __init__(self, jobs_denylist=None, jobs_allowlist=None): Initialization for celery worker. Args: jobs_denylist ... | Implement the Python class `TurbiniaCeleryWorker` described below.
Class description:
Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app
Method signatures and docstrings:
- def __init__(self, jobs_denylist=None, jobs_allowlist=None): Initialization for celery worker. Args: jobs_denylist ... | e73717549c6919e869ce4963449c36f227e3ccd6 | <|skeleton|>
class TurbiniaCeleryWorker:
"""Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app"""
def __init__(self, jobs_denylist=None, jobs_allowlist=None):
"""Initialization for celery worker. Args: jobs_denylist (Optional[list[str]]): Jobs we will exclude from running ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TurbiniaCeleryWorker:
"""Turbinia Celery Worker class. Attributes: worker (celery.app): Celery worker app"""
def __init__(self, jobs_denylist=None, jobs_allowlist=None):
"""Initialization for celery worker. Args: jobs_denylist (Optional[list[str]]): Jobs we will exclude from running jobs_allowlis... | the_stack_v2_python_sparse | turbinia/client.py | Ash515/turbinia | train | 6 |
1cc66265260411785fdf064e6a78036c7597c54a | [
"slug = self.kwargs.get('slug')\narticle = ArticleModel.objects.all().filter(slug=slug).first()\nuser = request.user\nif article is None:\n response = {'error': 'Article with slug {} not found'.format(slug)}\n return Response(data=response, status=status.HTTP_404_NOT_FOUND)\nif user == article.author:\n re... | <|body_start_0|>
slug = self.kwargs.get('slug')
article = ArticleModel.objects.all().filter(slug=slug).first()
user = request.user
if article is None:
response = {'error': 'Article with slug {} not found'.format(slug)}
return Response(data=response, status=status.... | Favorite an article | FavoriteArticle | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteArticle:
"""Favorite an article"""
def create(self, request, *args, **kwargs):
"""post: Create favorite endpoint"""
<|body_0|>
def list(self, request, slug):
"""get: The get all articles favorited endpoint"""
<|body_1|>
def destroy(self, requ... | stack_v2_sparse_classes_75kplus_train_007532 | 28,321 | permissive | [
{
"docstring": "post: Create favorite endpoint",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
"docstring": "get: The get all articles favorited endpoint",
"name": "list",
"signature": "def list(self, request, slug)"
},
{
"docstring": "delete: U... | 3 | null | Implement the Python class `FavoriteArticle` described below.
Class description:
Favorite an article
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): post: Create favorite endpoint
- def list(self, request, slug): get: The get all articles favorited endpoint
- def destroy(self, request,... | Implement the Python class `FavoriteArticle` described below.
Class description:
Favorite an article
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): post: Create favorite endpoint
- def list(self, request, slug): get: The get all articles favorited endpoint
- def destroy(self, request,... | ba429dfcec577bd6d52052673c1c413835f65988 | <|skeleton|>
class FavoriteArticle:
"""Favorite an article"""
def create(self, request, *args, **kwargs):
"""post: Create favorite endpoint"""
<|body_0|>
def list(self, request, slug):
"""get: The get all articles favorited endpoint"""
<|body_1|>
def destroy(self, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteArticle:
"""Favorite an article"""
def create(self, request, *args, **kwargs):
"""post: Create favorite endpoint"""
slug = self.kwargs.get('slug')
article = ArticleModel.objects.all().filter(slug=slug).first()
user = request.user
if article is None:
... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-the-jedi-backend | train | 1 |
8745911e30bc4037b7358f129c6405bc59188895 | [
"self.horizon = horizon\nself.policy = policy\nself.environment = environment\nself.state = self.environment.reset()\nself.logger = logger_",
"rollout = Rollout(self.environment.num_envs, self.horizon, self.state, self.policy.device)\nfor time_step in range(self.horizon):\n with torch.no_grad():\n actio... | <|body_start_0|>
self.horizon = horizon
self.policy = policy
self.environment = environment
self.state = self.environment.reset()
self.logger = logger_
<|end_body_0|>
<|body_start_1|>
rollout = Rollout(self.environment.num_envs, self.horizon, self.state, self.policy.devi... | Runner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Runner:
def __init__(self, horizon: int, policy: Policy, environment: StackEnv, logger_: AbstractLogger):
"""Runs the environments for horizon time steps generating a rollout class containing the observed data. :param horizon: number of time steps the training shall take :param policy: t... | stack_v2_sparse_classes_75kplus_train_007533 | 1,951 | permissive | [
{
"docstring": "Runs the environments for horizon time steps generating a rollout class containing the observed data. :param horizon: number of time steps the training shall take :param policy: the policy used for generating the training :param environment: the gym environment the policy is trained on :param lo... | 2 | stack_v2_sparse_classes_30k_train_036523 | Implement the Python class `Runner` described below.
Class description:
Implement the Runner class.
Method signatures and docstrings:
- def __init__(self, horizon: int, policy: Policy, environment: StackEnv, logger_: AbstractLogger): Runs the environments for horizon time steps generating a rollout class containing t... | Implement the Python class `Runner` described below.
Class description:
Implement the Runner class.
Method signatures and docstrings:
- def __init__(self, horizon: int, policy: Policy, environment: StackEnv, logger_: AbstractLogger): Runs the environments for horizon time steps generating a rollout class containing t... | b3fb6bdb466056cf84115ca7b0af21d2b48185ae | <|skeleton|>
class Runner:
def __init__(self, horizon: int, policy: Policy, environment: StackEnv, logger_: AbstractLogger):
"""Runs the environments for horizon time steps generating a rollout class containing the observed data. :param horizon: number of time steps the training shall take :param policy: t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Runner:
def __init__(self, horizon: int, policy: Policy, environment: StackEnv, logger_: AbstractLogger):
"""Runs the environments for horizon time steps generating a rollout class containing the observed data. :param horizon: number of time steps the training shall take :param policy: the policy used... | the_stack_v2_python_sparse | source/training/runner.py | Aethiles/ppo-pytorch | train | 0 | |
0bdf3d7eea0c43a39508a459cde812069258b8cc | [
"dp = [False for _ in range(len(s))]\nfor i in range(len(s)):\n for item in wordDict:\n if i - len(item) + 1 >= 0 and s[i - len(item) + 1:i + 1] == item and (i - len(item) < 0 or dp[i - len(item)] == True):\n dp[i] = True\nreturn dp[-1]",
"if not self.wordBreak_one(s, wordDict):\n return [... | <|body_start_0|>
dp = [False for _ in range(len(s))]
for i in range(len(s)):
for item in wordDict:
if i - len(item) + 1 >= 0 and s[i - len(item) + 1:i + 1] == item and (i - len(item) < 0 or dp[i - len(item)] == True):
dp[i] = True
return dp[-1]
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak_one(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_007534 | 1,870 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak_one",
"signature": "def wordBreak_one(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: List[str]",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordD... | 2 | stack_v2_sparse_classes_30k_train_050771 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_one(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_one(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: List[... | ede2a2e19f27ef4adf6e57d6692216b8990cf62b | <|skeleton|>
class Solution:
def wordBreak_one(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak_one(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
dp = [False for _ in range(len(s))]
for i in range(len(s)):
for item in wordDict:
if i - len(item) + 1 >= 0 and s[i - len(item) + 1:i + 1] == item and (... | the_stack_v2_python_sparse | word_break_II.py | ShunKaiZhang/LeetCode | train | 0 | |
fca30438264e9d7a46ef929081c82b97cf1328ed | [
"cache_key = calendar_year\nif cache_key not in UpstreamMethods._cache:\n start_years = np.atleast_1d(UpstreamMethods._data['start_year'])\n if len(start_years[start_years <= calendar_year]) > 0:\n calendar_year = max(start_years[start_years <= calendar_year])\n method = UpstreamMethods._data['u... | <|body_start_0|>
cache_key = calendar_year
if cache_key not in UpstreamMethods._cache:
start_years = np.atleast_1d(UpstreamMethods._data['start_year'])
if len(start_years[start_years <= calendar_year]) > 0:
calendar_year = max(start_years[start_years <= calendar_y... | **Loads and provides access to upstream calculation methods by start year.** | UpstreamMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for ... | stack_v2_sparse_classes_75kplus_train_007535 | 8,672 | no_license | [
{
"docstring": "Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: A callable python function used to calculate upstream cert emissions for the given calendar year",
"name": "get_upstream_method",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_025503 | Implement the Python class `UpstreamMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def get_upstream_method(calendar_year): Get the cert upstream calculation function for the given calendar year. Args: calend... | Implement the Python class `UpstreamMethods` described below.
Class description:
**Loads and provides access to upstream calculation methods by start year.**
Method signatures and docstrings:
- def get_upstream_method(calendar_year): Get the cert upstream calculation function for the given calendar year. Args: calend... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpstreamMethods:
"""**Loads and provides access to upstream calculation methods by start year.**"""
def get_upstream_method(calendar_year):
"""Get the cert upstream calculation function for the given calendar year. Args: calendar_year (int): the calendar year to get the function for Returns: A ca... | the_stack_v2_python_sparse | omega_model/policy/upstream_methods.py | USEPA/EPA_OMEGA_Model | train | 17 |
7cf42c64086a3eda3ab17f0bb67fc59ab889c088 | [
"self.crypto_controller = crypto_controller\nsuper(BulkTransformer, self).__init__(**kwargs)\nself.deleted_sets_transformer = DeleteSetsTransformer(storage=self.storage, account_manager=self.account_manager)",
"models = {i: [] for i in self.mapping}\nmodels['last_synced'] = payload.pop('now')\nbad_encrypted_model... | <|body_start_0|>
self.crypto_controller = crypto_controller
super(BulkTransformer, self).__init__(**kwargs)
self.deleted_sets_transformer = DeleteSetsTransformer(storage=self.storage, account_manager=self.account_manager)
<|end_body_0|>
<|body_start_1|>
models = {i: [] for i in self.map... | Transformer for entry list. | BulkTransformer | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkTransformer:
"""Transformer for entry list."""
def __init__(self, crypto_controller, **kwargs):
"""Construct new transformer for entry list."""
<|body_0|>
def to_model(self, payload):
"""Convert payload with set list."""
<|body_1|>
def to_payload... | stack_v2_sparse_classes_75kplus_train_007536 | 7,569 | permissive | [
{
"docstring": "Construct new transformer for entry list.",
"name": "__init__",
"signature": "def __init__(self, crypto_controller, **kwargs)"
},
{
"docstring": "Convert payload with set list.",
"name": "to_model",
"signature": "def to_model(self, payload)"
},
{
"docstring": "Con... | 5 | stack_v2_sparse_classes_30k_train_025557 | Implement the Python class `BulkTransformer` described below.
Class description:
Transformer for entry list.
Method signatures and docstrings:
- def __init__(self, crypto_controller, **kwargs): Construct new transformer for entry list.
- def to_model(self, payload): Convert payload with set list.
- def to_payload(sel... | Implement the Python class `BulkTransformer` described below.
Class description:
Transformer for entry list.
Method signatures and docstrings:
- def __init__(self, crypto_controller, **kwargs): Construct new transformer for entry list.
- def to_model(self, payload): Convert payload with set list.
- def to_payload(sel... | 2664d0c70d3d682ad931b885b4965447b156c280 | <|skeleton|>
class BulkTransformer:
"""Transformer for entry list."""
def __init__(self, crypto_controller, **kwargs):
"""Construct new transformer for entry list."""
<|body_0|>
def to_model(self, payload):
"""Convert payload with set list."""
<|body_1|>
def to_payload... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BulkTransformer:
"""Transformer for entry list."""
def __init__(self, crypto_controller, **kwargs):
"""Construct new transformer for entry list."""
self.crypto_controller = crypto_controller
super(BulkTransformer, self).__init__(**kwargs)
self.deleted_sets_transformer = De... | the_stack_v2_python_sparse | termius/cloud/client/transformers/many.py | termius/termius-cli | train | 262 |
8d13e9e9517feb63f9e3f69015eab608b2de472c | [
"try:\n if self.id is None:\n return self.query.all()\n if self.id is not None and type(self.id) is int and (self.id >= 0):\n return self.query.get(self.id)\nexcept Exception as e:\n return e.__cause__.args[1]",
"try:\n db.session.add(self)\n return db.session.commit()\nexcept Excepti... | <|body_start_0|>
try:
if self.id is None:
return self.query.all()
if self.id is not None and type(self.id) is int and (self.id >= 0):
return self.query.get(self.id)
except Exception as e:
return e.__cause__.args[1]
<|end_body_0|>
<|bod... | Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hyperlink to the component] status {[in... | Component | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hy... | stack_v2_sparse_classes_75kplus_train_007537 | 10,042 | no_license | [
{
"docstring": "Using get all component or get a single component. [description] Keyword Arguments: id {[int]} -- [Component ID] (default: {None}) Returns: [Information about component(s)] -- [When successed] [Message] -- [When failed]",
"name": "get",
"signature": "def get(self)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_val_000978 | Implement the Python class `Component` described below.
Class description:
Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description o... | Implement the Python class `Component` described below.
Class description:
Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description o... | 052956e5006f7d274d19a43b061c2fe4a6456cc0 | <|skeleton|>
class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hyperlink to th... | the_stack_v2_python_sparse | models/components.py | BoTranVan/statuspage | train | 0 |
1e4f57fd43102995def013c4e353cc922058582b | [
"super(BIM, self).__init__(model, device)\nself.device = device\nself.eps = eps\nself.loss = CrossEntropyLoss()\nself.itr_numbers = itr_numbers",
"xs = xs.to(self.device)\nperturbtion = torch.zeros(xs.shape).to(self.device)\nxs.requires_grad = True\nfor i in range(self.itr_numbers):\n output = self.model_forwa... | <|body_start_0|>
super(BIM, self).__init__(model, device)
self.device = device
self.eps = eps
self.loss = CrossEntropyLoss()
self.itr_numbers = itr_numbers
<|end_body_0|>
<|body_start_1|>
xs = xs.to(self.device)
perturbtion = torch.zeros(xs.shape).to(self.device)... | BIM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BIM:
def __init__(self, model, device, eps=0.001, itr_numbers=20):
"""Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration number"""
<|body_0|>
def attack(self, xs: torch.tensor, ys: torch.tensor):
... | stack_v2_sparse_classes_75kplus_train_007538 | 2,821 | permissive | [
{
"docstring": "Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration number",
"name": "__init__",
"signature": "def __init__(self, model, device, eps=0.001, itr_numbers=20)"
},
{
"docstring": "Attacking the victim model by add... | 2 | stack_v2_sparse_classes_30k_train_023862 | Implement the Python class `BIM` described below.
Class description:
Implement the BIM class.
Method signatures and docstrings:
- def __init__(self, model, device, eps=0.001, itr_numbers=20): Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration num... | Implement the Python class `BIM` described below.
Class description:
Implement the BIM class.
Method signatures and docstrings:
- def __init__(self, model, device, eps=0.001, itr_numbers=20): Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration num... | 3230044473614d2dd931d96cbd6a3bc974eff926 | <|skeleton|>
class BIM:
def __init__(self, model, device, eps=0.001, itr_numbers=20):
"""Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration number"""
<|body_0|>
def attack(self, xs: torch.tensor, ys: torch.tensor):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BIM:
def __init__(self, model, device, eps=0.001, itr_numbers=20):
"""Initializing the BIM class. Args: model: victim model device: torch.device eps: float, epsilon itr_numbers: int, iteration number"""
super(BIM, self).__init__(model, device)
self.device = device
self.eps = ep... | the_stack_v2_python_sparse | advt/attack/bim.py | WindFantasy98/ADVT | train | 0 | |
89272bb16a1a6d6e609bbc091f224660b5061ede | [
"super().__init__(name=name, **kwargs)\nself._output_last_dim = output_last_dim\nself._output_w_init = output_w_init\nself._use_query_residual = use_query_residual\nself._qk_last_dim = qk_last_dim\nself._v_last_dim = v_last_dim\nself._final_project = False\nself._num_heads = num_heads",
"decoder_query_shape = inp... | <|body_start_0|>
super().__init__(name=name, **kwargs)
self._output_last_dim = output_last_dim
self._output_w_init = output_w_init
self._use_query_residual = use_query_residual
self._qk_last_dim = qk_last_dim
self._v_last_dim = v_last_dim
self._final_project = Fal... | Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https://arxiv.org/abs/1706.03762) [Perceiver: General Perception with Iterative... | Decoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https://arxiv.org/abs/1706.03762) [Perceiver... | stack_v2_sparse_classes_75kplus_train_007539 | 5,196 | permissive | [
{
"docstring": "Init. Args: output_last_dim: Last dim size for output. qk_last_dim: When set, determines the last dimension of the attention score output. Check `qk_last_dim` doc in `utils.build_cross_attention_block_args`. v_last_dim: When set, determines the value's last dimension in the multi-head attention.... | 3 | stack_v2_sparse_classes_30k_train_012302 | Implement the Python class `Decoder` described below.
Class description:
Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https... | Implement the Python class `Decoder` described below.
Class description:
Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class Decoder:
"""Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https://arxiv.org/abs/1706.03762) [Perceiver... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""Perceiver Decoder layer. Uses cross attention decoder layer. This layer implements a Perceiver Decoder from "Perceiver: General Perception with Iterative Attention". (https://arxiv.org/abs/2103.03206) References: [Attention Is All You Need](https://arxiv.org/abs/1706.03762) [Perceiver: General Per... | the_stack_v2_python_sparse | official/projects/perceiver/modeling/layers/decoder.py | jianzhnie/models | train | 2 |
dc0bad733412b879276d63997ab6146f8829b854 | [
"beam_factor_file = Path(beam_factor_file).expanduser()\nif str(beam_factor_file).startswith(':'):\n beam_factor_file = Path(config['paths']['beams']) / band / 'beam_factors' / str(beam_factor_file)[1:]\nif not beam_factor_file.exists():\n raise ValueError(f'The beam factor file {beam_factor_file} does not ex... | <|body_start_0|>
beam_factor_file = Path(beam_factor_file).expanduser()
if str(beam_factor_file).startswith(':'):
beam_factor_file = Path(config['paths']['beams']) / band / 'beam_factors' / str(beam_factor_file)[1:]
if not beam_factor_file.exists():
raise ValueError(f'The... | InterpolatedBeamFactor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolatedBeamFactor:
def from_beam_factor(cls, beam_factor_file, band: str | None=None, lst_new: np.ndarray | None=None, f_new: np.ndarray | None=None):
"""Interpolate beam factor to a new set of LSTs and frequencies. The LST interpolation is done using `griddata`, whilst the frequenc... | stack_v2_sparse_classes_75kplus_train_007540 | 37,442 | permissive | [
{
"docstring": "Interpolate beam factor to a new set of LSTs and frequencies. The LST interpolation is done using `griddata`, whilst the frequency interpolation is done using a polynomial fit. Parameters ---------- beam_factor_file : path Path to a file containing beam factors produced by :func:`antenna_beam_fa... | 2 | stack_v2_sparse_classes_30k_train_042665 | Implement the Python class `InterpolatedBeamFactor` described below.
Class description:
Implement the InterpolatedBeamFactor class.
Method signatures and docstrings:
- def from_beam_factor(cls, beam_factor_file, band: str | None=None, lst_new: np.ndarray | None=None, f_new: np.ndarray | None=None): Interpolate beam f... | Implement the Python class `InterpolatedBeamFactor` described below.
Class description:
Implement the InterpolatedBeamFactor class.
Method signatures and docstrings:
- def from_beam_factor(cls, beam_factor_file, band: str | None=None, lst_new: np.ndarray | None=None, f_new: np.ndarray | None=None): Interpolate beam f... | 79fe4fd8d92230771b007555fff837dc510eeca5 | <|skeleton|>
class InterpolatedBeamFactor:
def from_beam_factor(cls, beam_factor_file, band: str | None=None, lst_new: np.ndarray | None=None, f_new: np.ndarray | None=None):
"""Interpolate beam factor to a new set of LSTs and frequencies. The LST interpolation is done using `griddata`, whilst the frequenc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpolatedBeamFactor:
def from_beam_factor(cls, beam_factor_file, band: str | None=None, lst_new: np.ndarray | None=None, f_new: np.ndarray | None=None):
"""Interpolate beam factor to a new set of LSTs and frequencies. The LST interpolation is done using `griddata`, whilst the frequency interpolatio... | the_stack_v2_python_sparse | src/edges_analysis/beams.py | edges-collab/edges-analysis | train | 1 | |
0eec3fc54e993c2984c11d1ea7dd9763b509714b | [
"\"\"\"\n Constructor\n \"\"\"\nself.log = LoggingService(logfile=logfile, msg_identifier=f'chop_spectrograms')\nif not os.path.exists(snippet_outdir):\n os.makedirs(snippet_outdir)\n'\\n Open the spect file and corresponding label and then CHOP, CHOP, CHOP\\n '\ntry:\n spectro... | <|body_start_0|>
"""
Constructor
"""
self.log = LoggingService(logfile=logfile, msg_identifier=f'chop_spectrograms')
if not os.path.exists(snippet_outdir):
os.makedirs(snippet_outdir)
'\n Open the spect file and corresponding label a... | Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise | SpectrogramChopper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrogramChopper:
"""Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise"""
def __init__(self, spect_file, spect_label_file, snippet_outdir, w... | stack_v2_sparse_classes_75kplus_train_007541 | 6,601 | no_license | [
{
"docstring": "@param spect_file: The spectrogram file we want to chop @type spect_file: str @param spect_label_file: The spectrogram label file with 0/1 binary labels @type spect_label_file: str @param snippet_outdir: where the snippets are to be placed. This is likely to be either in the training / test fold... | 2 | stack_v2_sparse_classes_30k_train_051611 | Implement the Python class `SpectrogramChopper` described below.
Class description:
Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise
Method signatures and docstrings:
... | Implement the Python class `SpectrogramChopper` described below.
Class description:
Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise
Method signatures and docstrings:
... | e513df821a5261913be677023ab1e0e65099f0b9 | <|skeleton|>
class SpectrogramChopper:
"""Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise"""
def __init__(self, spect_file, spect_label_file, snippet_outdir, w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectrogramChopper:
"""Given a single spectrogram and the corresponding labeling, chop the spectrograms into the specified window size! NOTE: For now avoid doing any parallelization to just get this done functionality wise"""
def __init__(self, spect_file, spect_label_file, snippet_outdir, window_size=25... | the_stack_v2_python_sparse | src/Refactored/spectrogram_chopper.py | jonathangomesselman/ElephantCallAI | train | 0 |
62e2e89457b99a554f399862454490b58fafda11 | [
"super(NameGenerator, self).__init__()\nself.lstm_dims = n_hidden_dims\nself.lstm_layers = n_lstm_layers\nself.input_lookup = nn.Embedding(num_embeddings=input_vocab_size, embedding_dim=n_embedding_dims)\nself.lstm = nn.LSTM(input_size=n_embedding_dims, hidden_size=n_hidden_dims, num_layers=n_lstm_layers, batch_fir... | <|body_start_0|>
super(NameGenerator, self).__init__()
self.lstm_dims = n_hidden_dims
self.lstm_layers = n_lstm_layers
self.input_lookup = nn.Embedding(num_embeddings=input_vocab_size, embedding_dim=n_embedding_dims)
self.lstm = nn.LSTM(input_size=n_embedding_dims, hidden_size=n_... | NameGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and ... | stack_v2_sparse_classes_75kplus_train_007542 | 5,650 | no_license | [
{
"docstring": "Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and LogSoftmax layer. Note: Remember to set batch_first=True when initializing your LSTM layer! Also note: When you build your LogSoftm... | 3 | stack_v2_sparse_classes_30k_train_041686 | Implement the Python class `NameGenerator` described below.
Class description:
Implement the NameGenerator class.
Method signatures and docstrings:
- def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size): Initialize our name generator, following the equations laid out... | Implement the Python class `NameGenerator` described below.
Class description:
Implement the NameGenerator class.
Method signatures and docstrings:
- def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size): Initialize our name generator, following the equations laid out... | 2ded61191a5e5ec215ec187c468a1f1ae1adf412 | <|skeleton|>
class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NameGenerator:
def __init__(self, input_vocab_size, n_embedding_dims, n_hidden_dims, n_lstm_layers, output_vocab_size):
"""Initialize our name generator, following the equations laid out in the assignment. In other words, we'll need an Embedding layer, an LSTM layer, a Linear layer, and LogSoftmax lay... | the_stack_v2_python_sparse | OHSU_Winter_2019/CS562/HW3/hw3_utils/lm.py | Eric-D-Stevens/OHSU | train | 1 | |
fbf7c2ec8207f0f4f3e1a4fbde785d9f16fd6251 | [
"from .models import Filing\ncmte = self.get_committee(obj_or_id)\nfiling_list = Filing.real.by_committee(cmte)\nqs = self.get_queryset().filter(committee=cmte, filing__in=filing_list)\nreturn qs",
"from .models import Filing\ncmte = self.get_committee(obj_or_id)\nfiling_list = Filing.real.by_committee(cmte)\nqs ... | <|body_start_0|>
from .models import Filing
cmte = self.get_committee(obj_or_id)
filing_list = Filing.real.by_committee(cmte)
qs = self.get_queryset().filter(committee=cmte, filing__in=filing_list)
return qs
<|end_body_0|>
<|body_start_1|>
from .models import Filing
... | Only returns records that are not duplicates. | RealExpenditureManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealExpenditureManager:
"""Only returns records that are not duplicates."""
def by_committee_to(self, obj_or_id):
"""Returns the "real" or valid expenditures received by a particular committee."""
<|body_0|>
def by_committee_from(self, obj_or_id):
"""Returns the ... | stack_v2_sparse_classes_75kplus_train_007543 | 4,937 | permissive | [
{
"docstring": "Returns the \"real\" or valid expenditures received by a particular committee.",
"name": "by_committee_to",
"signature": "def by_committee_to(self, obj_or_id)"
},
{
"docstring": "Returns the \"real\" or valid expenditures made by a particular committee.",
"name": "by_committe... | 2 | stack_v2_sparse_classes_30k_train_019695 | Implement the Python class `RealExpenditureManager` described below.
Class description:
Only returns records that are not duplicates.
Method signatures and docstrings:
- def by_committee_to(self, obj_or_id): Returns the "real" or valid expenditures received by a particular committee.
- def by_committee_from(self, obj... | Implement the Python class `RealExpenditureManager` described below.
Class description:
Only returns records that are not duplicates.
Method signatures and docstrings:
- def by_committee_to(self, obj_or_id): Returns the "real" or valid expenditures received by a particular committee.
- def by_committee_from(self, obj... | 69f7d6f1c64e45c85656af3003b1beed2fb55362 | <|skeleton|>
class RealExpenditureManager:
"""Only returns records that are not duplicates."""
def by_committee_to(self, obj_or_id):
"""Returns the "real" or valid expenditures received by a particular committee."""
<|body_0|>
def by_committee_from(self, obj_or_id):
"""Returns the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RealExpenditureManager:
"""Only returns records that are not duplicates."""
def by_committee_to(self, obj_or_id):
"""Returns the "real" or valid expenditures received by a particular committee."""
from .models import Filing
cmte = self.get_committee(obj_or_id)
filing_list ... | the_stack_v2_python_sparse | calaccess_campaign_browser/managers.py | livlab/django-calaccess-campaign-browser | train | 1 |
3bb4c540c6228caf391df1c6531106d2f31b3623 | [
"if auth.get_user(request) != auth_models.AnonymousUser():\n return redirect('index')\nform = forms.LoginForm()\nreturn render(request, 'login.html', {'form': form})",
"authorization = request.META.get('HTTP_AUTHORIZATION')\nauthorization = re.findall('^Basic(.*?)$', authorization, re.S)[0]\nbase64byte = base6... | <|body_start_0|>
if auth.get_user(request) != auth_models.AnonymousUser():
return redirect('index')
form = forms.LoginForm()
return render(request, 'login.html', {'form': form})
<|end_body_0|>
<|body_start_1|>
authorization = request.META.get('HTTP_AUTHORIZATION')
au... | this is login view | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
"""this is login view"""
def get(self, request, *args, **kwargs):
"""get login page 如果当前用户已经登陆,则跳转到首页"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""user login 账号和密码通过HTTP_AUTHORIZATION传递,base64加密, 密文前添加了个Basic字符串,解密后结构:"username:password" ... | stack_v2_sparse_classes_75kplus_train_007544 | 9,185 | no_license | [
{
"docstring": "get login page 如果当前用户已经登陆,则跳转到首页",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "user login 账号和密码通过HTTP_AUTHORIZATION传递,base64加密, 密文前添加了个Basic字符串,解密后结构:\"username:password\" 由于username是不允许出现\":\",所以第一个\":\"之前表示username,之后表示password",
... | 2 | null | Implement the Python class `LoginView` described below.
Class description:
this is login view
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): get login page 如果当前用户已经登陆,则跳转到首页
- def post(self, request, *args, **kwargs): user login 账号和密码通过HTTP_AUTHORIZATION传递,base64加密, 密文前添加了个Basic字符串,解密后结构... | Implement the Python class `LoginView` described below.
Class description:
this is login view
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): get login page 如果当前用户已经登陆,则跳转到首页
- def post(self, request, *args, **kwargs): user login 账号和密码通过HTTP_AUTHORIZATION传递,base64加密, 密文前添加了个Basic字符串,解密后结构... | 4656d410ef5e747c7c4e6c1f6b64b3d75a1a56c2 | <|skeleton|>
class LoginView:
"""this is login view"""
def get(self, request, *args, **kwargs):
"""get login page 如果当前用户已经登陆,则跳转到首页"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""user login 账号和密码通过HTTP_AUTHORIZATION传递,base64加密, 密文前添加了个Basic字符串,解密后结构:"username:password" ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
"""this is login view"""
def get(self, request, *args, **kwargs):
"""get login page 如果当前用户已经登陆,则跳转到首页"""
if auth.get_user(request) != auth_models.AnonymousUser():
return redirect('index')
form = forms.LoginForm()
return render(request, 'login.html', ... | the_stack_v2_python_sparse | common/views.py | hao45e/remember | train | 0 |
1f2e00b403a4679e26d794b4b5c759bf5b905d39 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Manages documents of a knowledge base. | DocumentsServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentsServicer:
"""Manages documents of a knowledge base."""
def ListDocuments(self, request, context):
"""Returns the list of all documents of the knowledge base."""
<|body_0|>
def GetDocument(self, request, context):
"""Retrieves the specified document."""
... | stack_v2_sparse_classes_75kplus_train_007545 | 5,127 | permissive | [
{
"docstring": "Returns the list of all documents of the knowledge base.",
"name": "ListDocuments",
"signature": "def ListDocuments(self, request, context)"
},
{
"docstring": "Retrieves the specified document.",
"name": "GetDocument",
"signature": "def GetDocument(self, request, context)... | 4 | stack_v2_sparse_classes_30k_train_036212 | Implement the Python class `DocumentsServicer` described below.
Class description:
Manages documents of a knowledge base.
Method signatures and docstrings:
- def ListDocuments(self, request, context): Returns the list of all documents of the knowledge base.
- def GetDocument(self, request, context): Retrieves the spe... | Implement the Python class `DocumentsServicer` described below.
Class description:
Manages documents of a knowledge base.
Method signatures and docstrings:
- def ListDocuments(self, request, context): Returns the list of all documents of the knowledge base.
- def GetDocument(self, request, context): Retrieves the spe... | c9c830feb6b66c2e362f8fb5d147ef0c4f4a08cf | <|skeleton|>
class DocumentsServicer:
"""Manages documents of a knowledge base."""
def ListDocuments(self, request, context):
"""Returns the list of all documents of the knowledge base."""
<|body_0|>
def GetDocument(self, request, context):
"""Retrieves the specified document."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentsServicer:
"""Manages documents of a knowledge base."""
def ListDocuments(self, request, context):
"""Returns the list of all documents of the knowledge base."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise No... | the_stack_v2_python_sparse | pyenv/lib/python3.6/site-packages/dialogflow_v2beta1/proto/document_pb2_grpc.py | ronald-rgr/ai-chatbot-smartguide | train | 0 |
18c315d07db54d08b61c874d2bbed06f81a90ca2 | [
"QWidget.__init__(self)\nself.prevision = prevision\nself.__init_UI()",
"layout = QHBoxLayout()\nself.label = QLabel(self)\nself.__update_label()\nself.slider = SliderWidget(1, 4, 3)\nself.button = QPushButton('Réapprovisionner', self)\nself.button.clicked.connect(self.__button_clicked_to_refill)\nlayout.addWidge... | <|body_start_0|>
QWidget.__init__(self)
self.prevision = prevision
self.__init_UI()
<|end_body_0|>
<|body_start_1|>
layout = QHBoxLayout()
self.label = QLabel(self)
self.__update_label()
self.slider = SliderWidget(1, 4, 3)
self.button = QPushButton('Réapp... | Class defining the notification widget for a prevision. | PrevisionWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrevisionWidget:
"""Class defining the notification widget for a prevision."""
def __init__(self, prevision):
"""Constructor"""
<|body_0|>
def __init_UI(self):
"""Method creating the UI of the prevision label"""
<|body_1|>
def __button_clicked_to_ref... | stack_v2_sparse_classes_75kplus_train_007546 | 8,936 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, prevision)"
},
{
"docstring": "Method creating the UI of the prevision label",
"name": "__init_UI",
"signature": "def __init_UI(self)"
},
{
"docstring": "Method called when the button is clicked to... | 5 | null | Implement the Python class `PrevisionWidget` described below.
Class description:
Class defining the notification widget for a prevision.
Method signatures and docstrings:
- def __init__(self, prevision): Constructor
- def __init_UI(self): Method creating the UI of the prevision label
- def __button_clicked_to_refill(... | Implement the Python class `PrevisionWidget` described below.
Class description:
Class defining the notification widget for a prevision.
Method signatures and docstrings:
- def __init__(self, prevision): Constructor
- def __init_UI(self): Method creating the UI of the prevision label
- def __button_clicked_to_refill(... | d445c3539b8bb6c180e23618b493c4a51cc12903 | <|skeleton|>
class PrevisionWidget:
"""Class defining the notification widget for a prevision."""
def __init__(self, prevision):
"""Constructor"""
<|body_0|>
def __init_UI(self):
"""Method creating the UI of the prevision label"""
<|body_1|>
def __button_clicked_to_ref... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrevisionWidget:
"""Class defining the notification widget for a prevision."""
def __init__(self, prevision):
"""Constructor"""
QWidget.__init__(self)
self.prevision = prevision
self.__init_UI()
def __init_UI(self):
"""Method creating the UI of the prevision l... | the_stack_v2_python_sparse | serverWidget.py | KtfooassAM/Fignos217 | train | 0 |
daf2555f588e5844fdc7ad72dec7925fa3ef365b | [
"endpoint = '/models/{}/features-importances/download'.format(self._id)\nresponse = client.request(endpoint=endpoint, method=requests.get, message_prefix='Fetch feature importance')\ndf_feat_importance = zip_to_pandas(response)\nreturn df_feat_importance.sort_values(by='importance', ascending=False)",
"logger.deb... | <|body_start_0|>
endpoint = '/models/{}/features-importances/download'.format(self._id)
response = client.request(endpoint=endpoint, method=requests.get, message_prefix='Fetch feature importance')
df_feat_importance = zip_to_pandas(response)
return df_feat_importance.sort_values(by='impo... | ClassicModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassicModel:
def feature_importance(self) -> pd.DataFrame:
"""Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: Pre... | stack_v2_sparse_classes_75kplus_train_007547 | 22,840 | permissive | [
{
"docstring": "Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: PrevisionException: Any error while fetching data from the platform or par... | 3 | null | Implement the Python class `ClassicModel` described below.
Class description:
Implement the ClassicModel class.
Method signatures and docstrings:
- def feature_importance(self) -> pd.DataFrame: Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descendin... | Implement the Python class `ClassicModel` described below.
Class description:
Implement the ClassicModel class.
Method signatures and docstrings:
- def feature_importance(self) -> pd.DataFrame: Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descendin... | 1e955072057bc587530c34268bff328ef1e5a5a7 | <|skeleton|>
class ClassicModel:
def feature_importance(self) -> pd.DataFrame:
"""Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: Pre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassicModel:
def feature_importance(self) -> pd.DataFrame:
"""Return a dataframe of feature importances for the given model features, with their corresponding scores (sorted by descending feature importance scores). Returns: ``pd.DataFrame``: Dataframe of feature importances Raises: PrevisionExceptio... | the_stack_v2_python_sparse | previsionio/model.py | previsionio/prevision-python | train | 8 | |
92cac41738f1ab4e4a3f3d4cf304875e09f1a385 | [
"res = [1] * len(ratings)\nleft_base = right_base = 1\nfor i in xrange(1, len(ratings)):\n left_base = left_base + 1 if ratings[i] > ratings[i - 1] else 1\n res[i] = left_base\nfor i in xrange(len(ratings) - 2, -1, -1):\n right_base = right_base + 1 if ratings[i] > ratings[i + 1] else 1\n res[i] = max(r... | <|body_start_0|>
res = [1] * len(ratings)
left_base = right_base = 1
for i in xrange(1, len(ratings)):
left_base = left_base + 1 if ratings[i] > ratings[i - 1] else 1
res[i] = left_base
for i in xrange(len(ratings) - 2, -1, -1):
right_base = right_base... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def candy(self, ratings):
""":type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping Rain Water question @param {integer[]} ratings @return {integer} beats 47.64%"""
<|body_0... | stack_v2_sparse_classes_75kplus_train_007548 | 3,230 | no_license | [
{
"docstring": ":type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping Rain Water question @param {integer[]} ratings @return {integer} beats 47.64%",
"name": "candy",
"signature": "def candy(self, ratings)"... | 2 | stack_v2_sparse_classes_30k_train_026058 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def candy(self, ratings): :type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def candy(self, ratings): :type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping ... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def candy(self, ratings):
""":type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping Rain Water question @param {integer[]} ratings @return {integer} beats 47.64%"""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def candy(self, ratings):
""":type ratings: List[int] :rtype: int use two pass scan from left to right and vice versa to keep the candy level up to now similar to like the Trapping Rain Water question @param {integer[]} ratings @return {integer} beats 47.64%"""
res = [1] * len(rating... | the_stack_v2_python_sparse | LeetCode/135_candy.py | yao23/Machine_Learning_Playground | train | 12 | |
535a68cd42cce2992e64a00e659f362eb3c33268 | [
"docs = list(cls.all_raters(pylons.tmpl_context.db)[doc_id])\nif docs:\n for rating in docs[0]:\n if displayname == rating['displayname']:\n return rating['id']\nreturn False",
"rows = pylons.tmpl_context.db.view('rating/by_id', **options)[doc_id]\nif len(rows) > 0:\n return list(rows)[0].... | <|body_start_0|>
docs = list(cls.all_raters(pylons.tmpl_context.db)[doc_id])
if docs:
for rating in docs[0]:
if displayname == rating['displayname']:
return rating['id']
return False
<|end_body_0|>
<|body_start_1|>
rows = pylons.tmpl_conte... | Rating | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rating:
def has_rated(cls, doc_id, displayname, **options):
"""Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc"""
<|body_0|>
def by_id(cls, doc_id, **options):
"""Retrieves the overall rating for a... | stack_v2_sparse_classes_75kplus_train_007549 | 4,089 | permissive | [
{
"docstring": "Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc",
"name": "has_rated",
"signature": "def has_rated(cls, doc_id, displayname, **options)"
},
{
"docstring": "Retrieves the overall rating for a document",
"nam... | 3 | null | Implement the Python class `Rating` described below.
Class description:
Implement the Rating class.
Method signatures and docstrings:
- def has_rated(cls, doc_id, displayname, **options): Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc
- def by_id(... | Implement the Python class `Rating` described below.
Class description:
Implement the Rating class.
Method signatures and docstrings:
- def has_rated(cls, doc_id, displayname, **options): Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc
- def by_id(... | 8c843bdb7508a25dea094fdd38bd5b5cc521d486 | <|skeleton|>
class Rating:
def has_rated(cls, doc_id, displayname, **options):
"""Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc"""
<|body_0|>
def by_id(cls, doc_id, **options):
"""Retrieves the overall rating for a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rating:
def has_rated(cls, doc_id, displayname, **options):
"""Checks the document to see if the displayname has already rated the document, if so, returns the id of the rating doc"""
docs = list(cls.all_raters(pylons.tmpl_context.db)[doc_id])
if docs:
for rating in docs[0]... | the_stack_v2_python_sparse | kai/model/generics.py | Pylons/kai | train | 1 | |
5506856d790b0315ee9a2092553d08dae7830412 | [
"self._options = options\nself._preMessage = preMessage\nself._postMessage = postMessage\nself._selected = 0\nself._result = None",
"self._selected = 0\nself._show()\nreturn self._handleKeypresses()",
"combinedUpKeys = Constants.UP_KEYS + Constants.LEFT_KEYS\ncombinedDownKeys = Constants.DOWN_KEYS + Constants.R... | <|body_start_0|>
self._options = options
self._preMessage = preMessage
self._postMessage = postMessage
self._selected = 0
self._result = None
<|end_body_0|>
<|body_start_1|>
self._selected = 0
self._show()
return self._handleKeypresses()
<|end_body_1|>
<... | A menu (list of options) for a terminal interface | TerminalMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) p... | stack_v2_sparse_classes_75kplus_train_007550 | 7,322 | no_license | [
{
"docstring": "Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) postMessage -- the message to show below the menu (optional)",
"name": "__init__",
"signature": "def __init__(self, options, preMessage=None, ... | 5 | stack_v2_sparse_classes_30k_train_046760 | Implement the Python class `TerminalMenu` described below.
Class description:
A menu (list of options) for a terminal interface
Method signatures and docstrings:
- def __init__(self, options, preMessage=None, postMessage=None): Arguments: options -- the options the user can choose from as a collection of strings preM... | Implement the Python class `TerminalMenu` described below.
Class description:
A menu (list of options) for a terminal interface
Method signatures and docstrings:
- def __init__(self, options, preMessage=None, postMessage=None): Arguments: options -- the options the user can choose from as a collection of strings preM... | 46b7e084234227f925a24ea2eb41ed5d9ac14b7a | <|skeleton|>
class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) postMessage --... | the_stack_v2_python_sparse | Source/TerminalMenu.py | csahmad/291-Mini-Project-1 | train | 0 |
da04639a85eacda4fe96f3646033f00cf0c74b84 | [
"super(CtrTrainerCallback, self).__init__()\nself.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])\nself.selected_pairs = list()\nlogging.info('init autogate s2 trainer callback')",
"super().before_train(logs)\n'Be called before the training process.'\nhpo_result = FileOps.load_pickle(FileO... | <|body_start_0|>
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.selected_pairs = list()
logging.info('init autogate s2 trainer callback')
<|end_body_0|>
<|body_start_1|>
super().before_train(logs)
... | AutoGateS2TrainerCallback module. | AutoGateS2TrainerCallback | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
def aft... | stack_v2_sparse_classes_75kplus_train_007551 | 3,088 | permissive | [
{
"docstring": "Construct AutoGateS2TrainerCallback class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call before_train of the managed callbacks.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Call aft... | 3 | stack_v2_sparse_classes_30k_train_025502 | Implement the Python class `AutoGateS2TrainerCallback` described below.
Class description:
AutoGateS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
- def after_t... | Implement the Python class `AutoGateS2TrainerCallback` described below.
Class description:
AutoGateS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
- def after_t... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
def aft... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.selected_pai... | the_stack_v2_python_sparse | vega/algorithms/nas/fis/autogate_s2_trainer_callback.py | huawei-noah/vega | train | 850 |
83dd42ba86d0fec53aa5d496c211db78012e20ea | [
"if not root:\n return []\nself._findFrequentTreeSum(root)\nmost_frequent = []\nhighest_frequency = 0\nfor total_sum, frequency in counter.items():\n if frequency > highest_frequency:\n most_frequent = [total_sum]\n highest_frequency = frequency\n elif frequency == highest_frequency:\n ... | <|body_start_0|>
if not root:
return []
self._findFrequentTreeSum(root)
most_frequent = []
highest_frequency = 0
for total_sum, frequency in counter.items():
if frequency > highest_frequency:
most_frequent = [total_sum]
high... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def _findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_75kplus_train_007552 | 1,560 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findFrequentTreeSum",
"signature": "def findFrequentTreeSum(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "_findFrequentTreeSum",
"signature": "def _findFrequentTreeSum(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int]
- def _findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int]
- def _findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Sol... | 5128433c2c56d8470eb9c94268967294592df831 | <|skeleton|>
class Solution:
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def _findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
if not root:
return []
self._findFrequentTreeSum(root)
most_frequent = []
highest_frequency = 0
for total_sum, frequency in counter.items():
if fr... | the_stack_v2_python_sparse | most_frequent_subtree.py | enanablancaynumeros/interview_exercises | train | 0 | |
295047fc94bc33bb6ef83c5a907a8d8daefc7077 | [
"res = []\nnums1.sort()\nnums2.sort()\ni, j = (0, 0)\nwhile i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n res.append(nums1[i])\n i += 1\n j += 1\nreturn res",
"s, res = (set(), [])\nfor ele in nums1:... | <|body_start_0|>
res = []
nums1.sort()
nums2.sort()
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
res.append(nums1[i]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
<|body_0|>
def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns... | stack_v2_sparse_classes_75kplus_train_007553 | 2,414 | permissive | [
{
"docstring": "求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集",
"name": "intersection",
"signature": "def intersection(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组交集",
"name": "intersection2",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_002546 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1: List[int], nums2: List[int]) -> int: 求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集
- def intersection2(self, nums1: List[int], nums2: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1: List[int], nums2: List[int]) -> int: 求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集
- def intersection2(self, nums1: List[int], nums2: List[in... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
<|body_0|>
def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
res = []
nums1.sort()
nums2.sort()
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
... | the_stack_v2_python_sparse | src/leetcodepython/array/intersection_two_array_349.py | zhangyu345293721/leetcode | train | 101 | |
92f51d1ff3cb023652acb0fd95747702c23e4970 | [
"super().__init__()\nself.nlp = load_spacy_lexeme_prob(nlp)\nself.perturb_opts: Union[Dict, None] = perturb_opts\nself.words: List = []\nself.punctuation: List = []\nself.positions: List = []",
"processed = self.nlp(text)\nself.words = [x.text for x in processed]\nself.positions = [x.idx for x in processed]\nself... | <|body_start_0|>
super().__init__()
self.nlp = load_spacy_lexeme_prob(nlp)
self.perturb_opts: Union[Dict, None] = perturb_opts
self.words: List = []
self.punctuation: List = []
self.positions: List = []
<|end_body_0|>
<|body_start_1|>
processed = self.nlp(text)
... | UnknownSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnknownSampler:
def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict):
"""Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ---------- nlp `spaCy` object. perturb_opts Perturbation options."""
<|body_0|>
def set_text(sel... | stack_v2_sparse_classes_75kplus_train_007554 | 16,961 | permissive | [
{
"docstring": "Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ---------- nlp `spaCy` object. perturb_opts Perturbation options.",
"name": "__init__",
"signature": "def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_024529 | Implement the Python class `UnknownSampler` described below.
Class description:
Implement the UnknownSampler class.
Method signatures and docstrings:
- def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict): Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ------... | Implement the Python class `UnknownSampler` described below.
Class description:
Implement the UnknownSampler class.
Method signatures and docstrings:
- def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict): Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ------... | 54d0c957fb01c7ebba4e2a0d28fcbde52d9c6718 | <|skeleton|>
class UnknownSampler:
def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict):
"""Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ---------- nlp `spaCy` object. perturb_opts Perturbation options."""
<|body_0|>
def set_text(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnknownSampler:
def __init__(self, nlp: 'spacy.language.Language', perturb_opts: Dict):
"""Initialize unknown sampler. This sampler replaces word with the `UNK` token. Parameters ---------- nlp `spaCy` object. perturb_opts Perturbation options."""
super().__init__()
self.nlp = load_spa... | the_stack_v2_python_sparse | alibi/explainers/anchors/text_samplers.py | SeldonIO/alibi | train | 2,143 | |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"squad_id = request.GET.get('id', None)\nif squad_id is not None:\n squad = get_object_or_404(Squad, id=squad_id)\n serializer = SquadSerializer(squad)\n return JsonResponse({'squads': [serializer.data]}, safe=False)\ntutor_username = request.GET.get('tutor_username', None)\nif tutor_username is not None:\... | <|body_start_0|>
squad_id = request.GET.get('id', None)
if squad_id is not None:
squad = get_object_or_404(Squad, id=squad_id)
serializer = SquadSerializer(squad)
return JsonResponse({'squads': [serializer.data]}, safe=False)
tutor_username = request.GET.get('... | 班级view | Squads | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Squads:
"""班级view"""
def get(self, request):
"""查询班级"""
<|body_0|>
def put(self, request):
"""修改班级"""
<|body_1|>
def post(self, request):
"""增加班级"""
<|body_2|>
def delete(self, request):
"""删除班级"""
<|body_3|>
<|e... | stack_v2_sparse_classes_75kplus_train_007555 | 16,053 | permissive | [
{
"docstring": "查询班级",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改班级",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加班级",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除班级",
... | 4 | stack_v2_sparse_classes_30k_train_033416 | Implement the Python class `Squads` described below.
Class description:
班级view
Method signatures and docstrings:
- def get(self, request): 查询班级
- def put(self, request): 修改班级
- def post(self, request): 增加班级
- def delete(self, request): 删除班级 | Implement the Python class `Squads` described below.
Class description:
班级view
Method signatures and docstrings:
- def get(self, request): 查询班级
- def put(self, request): 修改班级
- def post(self, request): 增加班级
- def delete(self, request): 删除班级
<|skeleton|>
class Squads:
"""班级view"""
def get(self, request):
... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Squads:
"""班级view"""
def get(self, request):
"""查询班级"""
<|body_0|>
def put(self, request):
"""修改班级"""
<|body_1|>
def post(self, request):
"""增加班级"""
<|body_2|>
def delete(self, request):
"""删除班级"""
<|body_3|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Squads:
"""班级view"""
def get(self, request):
"""查询班级"""
squad_id = request.GET.get('id', None)
if squad_id is not None:
squad = get_object_or_404(Squad, id=squad_id)
serializer = SquadSerializer(squad)
return JsonResponse({'squads': [serializer.... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
ae5e204a7420278872d56d00fa5cb9e111b6d063 | [
"frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)\nm = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))\nlow, high, filtered = loudest_band(m, frame_rate, bandwidth)\nself.assertEqual(m.shape, filtered.shape)\nself.assertLessEqual(low, ftest, msg='low of band incorrect')\nself.assertLessEqua... | <|body_start_0|>
frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)
m = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))
low, high, filtered = loudest_band(m, frame_rate, bandwidth)
self.assertEqual(m.shape, filtered.shape)
self.assertLessEqual(low, ftest, m... | loudestTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
<|body_0|>
def test_find_energy(self):
"""b. cosines at 10 11 12 and 30"""
<|body_1|>
def test_find_band_split(self):
"""d. two sines 80% of bw apart"""
... | stack_v2_sparse_classes_75kplus_train_007556 | 4,240 | no_license | [
{
"docstring": "a. sine wave at 100 Hz, 1 kHz frame rate",
"name": "test_find_band",
"signature": "def test_find_band(self)"
},
{
"docstring": "b. cosines at 10 11 12 and 30",
"name": "test_find_energy",
"signature": "def test_find_energy(self)"
},
{
"docstring": "d. two sines 80... | 5 | stack_v2_sparse_classes_30k_train_036112 | Implement the Python class `loudestTestCase` described below.
Class description:
Implement the loudestTestCase class.
Method signatures and docstrings:
- def test_find_band(self): a. sine wave at 100 Hz, 1 kHz frame rate
- def test_find_energy(self): b. cosines at 10 11 12 and 30
- def test_find_band_split(self): d. ... | Implement the Python class `loudestTestCase` described below.
Class description:
Implement the loudestTestCase class.
Method signatures and docstrings:
- def test_find_band(self): a. sine wave at 100 Hz, 1 kHz frame rate
- def test_find_energy(self): b. cosines at 10 11 12 and 30
- def test_find_band_split(self): d. ... | 0c3afbbaf714d3a57e6347ea386f5cf86e4abb3c | <|skeleton|>
class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
<|body_0|>
def test_find_energy(self):
"""b. cosines at 10 11 12 and 30"""
<|body_1|>
def test_find_band_split(self):
"""d. two sines 80% of bw apart"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class loudestTestCase:
def test_find_band(self):
"""a. sine wave at 100 Hz, 1 kHz frame rate"""
frame_rate, T, ftest, bandwidth = (1000, 1, 100, 10)
m = sin(2 * pi * ftest * linspace(0, T, T * frame_rate, endpoint=False))
low, high, filtered = loudest_band(m, frame_rate, bandwidth)
... | the_stack_v2_python_sparse | Homework7/loudest_checker.py | Jasmine424/EC602-DesignBySoftware | train | 1 | |
f4222a37c013e8221851ba98eea7e8557f49fb6f | [
"super(LambertWGaussianizationTest, self).setUp()\nself.tailweight = 0.2\nself.loc = 2.0\nself.scale = 0.1",
"values = np.random.normal(loc=self.loc, scale=self.scale, size=10)\nlsht = lambertw_transform.LambertWTail(shift=self.loc, scale=self.scale, tailweight=0.0)\nself.assertAllClose(values, lsht.forward(value... | <|body_start_0|>
super(LambertWGaussianizationTest, self).setUp()
self.tailweight = 0.2
self.loc = 2.0
self.scale = 0.1
<|end_body_0|>
<|body_start_1|>
values = np.random.normal(loc=self.loc, scale=self.scale, size=10)
lsht = lambertw_transform.LambertWTail(shift=self.lo... | LambertWGaussianizationTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LambertWGaussianizationTest:
def setUp(self):
"""This method will be run before each of the test methods in the class."""
<|body_0|>
def testLambertWGaussianizationDeltaZero(self):
"""Tests that the output of ShiftScaleTail is correct when delta=0."""
<|body_... | stack_v2_sparse_classes_75kplus_train_007557 | 7,889 | permissive | [
{
"docstring": "This method will be run before each of the test methods in the class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests that the output of ShiftScaleTail is correct when delta=0.",
"name": "testLambertWGaussianizationDeltaZero",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_025246 | Implement the Python class `LambertWGaussianizationTest` described below.
Class description:
Implement the LambertWGaussianizationTest class.
Method signatures and docstrings:
- def setUp(self): This method will be run before each of the test methods in the class.
- def testLambertWGaussianizationDeltaZero(self): Tes... | Implement the Python class `LambertWGaussianizationTest` described below.
Class description:
Implement the LambertWGaussianizationTest class.
Method signatures and docstrings:
- def setUp(self): This method will be run before each of the test methods in the class.
- def testLambertWGaussianizationDeltaZero(self): Tes... | 42a64ba0d9e0973b1707fcd9b8bd8d14b2d4e3e5 | <|skeleton|>
class LambertWGaussianizationTest:
def setUp(self):
"""This method will be run before each of the test methods in the class."""
<|body_0|>
def testLambertWGaussianizationDeltaZero(self):
"""Tests that the output of ShiftScaleTail is correct when delta=0."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LambertWGaussianizationTest:
def setUp(self):
"""This method will be run before each of the test methods in the class."""
super(LambertWGaussianizationTest, self).setUp()
self.tailweight = 0.2
self.loc = 2.0
self.scale = 0.1
def testLambertWGaussianizationDeltaZero... | the_stack_v2_python_sparse | tensorflow_probability/python/bijectors/lambertw_transform_test.py | tensorflow/probability | train | 4,055 | |
6227349e50a3342bba8833ce3ea221cf5796cba0 | [
"super()._init_layers()\nself.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)\nself.norm = nn.LayerNorm(self.embed_dims)",
"intermediate = []\nintermediate_reference_points = [reference_points]\nfor lid, layer in enumerate(self.layers):\n if reference_points.shape[-1] == 4:\n ... | <|body_start_0|>
super()._init_layers()
self.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)
self.norm = nn.LayerNorm(self.embed_dims)
<|end_body_0|>
<|body_start_1|>
intermediate = []
intermediate_reference_points = [reference_points]
for ... | Transformer encoder of DINO. | DinoTransformerDecoder | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
<|body_0|>
def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, reference_points: Tensor, spatial_shap... | stack_v2_sparse_classes_75kplus_train_007558 | 26,710 | permissive | [
{
"docstring": "Initialize decoder layers.",
"name": "_init_layers",
"signature": "def _init_layers(self) -> None"
},
{
"docstring": "Forward function of Transformer encoder. Args: query (Tensor): The input query, has shape (num_queries, bs, dim). value (Tensor): The input values, has shape (num... | 2 | stack_v2_sparse_classes_30k_train_004557 | Implement the Python class `DinoTransformerDecoder` described below.
Class description:
Transformer encoder of DINO.
Method signatures and docstrings:
- def _init_layers(self) -> None: Initialize decoder layers.
- def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, refere... | Implement the Python class `DinoTransformerDecoder` described below.
Class description:
Transformer encoder of DINO.
Method signatures and docstrings:
- def _init_layers(self) -> None: Initialize decoder layers.
- def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, refere... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
<|body_0|>
def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, reference_points: Tensor, spatial_shap... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
super()._init_layers()
self.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)
self.norm = nn.LayerNorm(self.embed_dims)
... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/layers/transformer/dino_layers.py | alldatacenter/alldata | train | 774 |
e12791dbe28ed46541615678f51bd06cb032b84e | [
"super().__init__()\nself.device = device\nself.feature_dim = feature_dim\nself.none_action_vector = nn.parameter.Parameter(torch.randn(1, embedding_dim))\nself.with_feature = with_feature\nself.embedding_dim = embedding_dim\nself.seqlstm = nn.LSTM(input_size=embedding_dim, hidden_size=embedding_dim)\nself.parentls... | <|body_start_0|>
super().__init__()
self.device = device
self.feature_dim = feature_dim
self.none_action_vector = nn.parameter.Parameter(torch.randn(1, embedding_dim))
self.with_feature = with_feature
self.embedding_dim = embedding_dim
self.seqlstm = nn.LSTM(input... | Encoder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, embedding_dim, device, feature_dim, with_feature):
"""Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where model tensors are saved. feature_dim : int Number of features. For base model, 1 and for extende... | stack_v2_sparse_classes_75kplus_train_007559 | 14,357 | permissive | [
{
"docstring": "Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where model tensors are saved. feature_dim : int Number of features. For base model, 1 and for extended model, 3. with_feature : boolean Check whether to add features or not.",
"name": "__... | 3 | stack_v2_sparse_classes_30k_train_031986 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, embedding_dim, device, feature_dim, with_feature): Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where ... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, embedding_dim, device, feature_dim, with_feature): Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where ... | eb1bbf2f124db8dea143965e419e17cfb93b17f3 | <|skeleton|>
class Encoder:
def __init__(self, embedding_dim, device, feature_dim, with_feature):
"""Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where model tensors are saved. feature_dim : int Number of features. For base model, 1 and for extende... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
def __init__(self, embedding_dim, device, feature_dim, with_feature):
"""Constructor Parameters ---------- embedding_dim : int Embedding dimension. device : object torch device where model tensors are saved. feature_dim : int Number of features. For base model, 1 and for extended model, 3. wi... | the_stack_v2_python_sparse | Alignment_Model/model.py | TheresaSchmidt/ara | train | 0 | |
53ad3e903a693e5ddd68b3d4c0f1bcf2b8610c87 | [
"if self.get_text('latex') is not None:\n return True\nreturn False",
"if self.has_raw_latex():\n return self.get_text('latex')\nraise IllegalState()"
] | <|body_start_0|>
if self.get_text('latex') is not None:
return True
return False
<|end_body_0|>
<|body_start_1|>
if self.has_raw_latex():
return self.get_text('latex')
raise IllegalState()
<|end_body_1|>
| mecqbank answers | MecQBankAnswerRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MecQBankAnswerRecord:
"""mecqbank answers"""
def has_raw_latex(self):
"""stub"""
<|body_0|>
def get_raw_latex(self):
"""stub"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.get_text('latex') is not None:
return True
r... | stack_v2_sparse_classes_75kplus_train_007560 | 7,652 | permissive | [
{
"docstring": "stub",
"name": "has_raw_latex",
"signature": "def has_raw_latex(self)"
},
{
"docstring": "stub",
"name": "get_raw_latex",
"signature": "def get_raw_latex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053397 | Implement the Python class `MecQBankAnswerRecord` described below.
Class description:
mecqbank answers
Method signatures and docstrings:
- def has_raw_latex(self): stub
- def get_raw_latex(self): stub | Implement the Python class `MecQBankAnswerRecord` described below.
Class description:
mecqbank answers
Method signatures and docstrings:
- def has_raw_latex(self): stub
- def get_raw_latex(self): stub
<|skeleton|>
class MecQBankAnswerRecord:
"""mecqbank answers"""
def has_raw_latex(self):
"""stub"""... | 445f968a175d61c8d92c0f617a3c17dc1dc7c584 | <|skeleton|>
class MecQBankAnswerRecord:
"""mecqbank answers"""
def has_raw_latex(self):
"""stub"""
<|body_0|>
def get_raw_latex(self):
"""stub"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MecQBankAnswerRecord:
"""mecqbank answers"""
def has_raw_latex(self):
"""stub"""
if self.get_text('latex') is not None:
return True
return False
def get_raw_latex(self):
"""stub"""
if self.has_raw_latex():
return self.get_text('latex')
... | the_stack_v2_python_sparse | dlkit/records/assessment/mecqbank/item_records.py | mitsei/dlkit | train | 2 |
488e395dd50f4790c157692c02ed44c1b32b3b88 | [
"self._logger.debug('FGF inv line hook %s %s' % (line, value))\nchange = line.product_qty - line.product_qty_calc\nlocation_id = line.product_id.product_tmpl_id.property_stock_inventory.id\nif change > 0:\n value.update({'product_qty': change, 'location_id': location_id, 'location_dest_id': line.location_id.id})... | <|body_start_0|>
self._logger.debug('FGF inv line hook %s %s' % (line, value))
change = line.product_qty - line.product_qty_calc
location_id = line.product_id.product_tmpl_id.property_stock_inventory.id
if change > 0:
value.update({'product_qty': change, 'location_id': locati... | stock_inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_inventory:
def _inventory_line_hook(self, cr, uid, line, value):
"""Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_calc @param inventory_line: @param move_vals: @return:"""
<|body_0|>
def action_confirm(sel... | stack_v2_sparse_classes_75kplus_train_007561 | 31,618 | no_license | [
{
"docstring": "Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_calc @param inventory_line: @param move_vals: @return:",
"name": "_inventory_line_hook",
"signature": "def _inventory_line_hook(self, cr, uid, line, value)"
},
{
"docstri... | 3 | null | Implement the Python class `stock_inventory` described below.
Class description:
Implement the stock_inventory class.
Method signatures and docstrings:
- def _inventory_line_hook(self, cr, uid, line, value): Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_... | Implement the Python class `stock_inventory` described below.
Class description:
Implement the stock_inventory class.
Method signatures and docstrings:
- def _inventory_line_hook(self, cr, uid, line, value): Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_... | a077038fbafbdb0398aa4c2e068c45118ebccb93 | <|skeleton|>
class stock_inventory:
def _inventory_line_hook(self, cr, uid, line, value):
"""Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_calc @param inventory_line: @param move_vals: @return:"""
<|body_0|>
def action_confirm(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class stock_inventory:
def _inventory_line_hook(self, cr, uid, line, value):
"""Creates a stock move from an inventory line calculates the inv difference between product_qty and product_qty_calc @param inventory_line: @param move_vals: @return:"""
self._logger.debug('FGF inv line hook %s %s' % (line... | the_stack_v2_python_sparse | c2c_stock_accounting/stock.py | vauxoo-dev/c2c-randd-tmp | train | 0 | |
318101eff679c209f53cd1c542452e51b3cd0b3d | [
"self._command = None\nif 'command' in kw:\n self._command = kw.pop('command')\nkw['command'] = self.choosecolour\n_style = 'TButton'\nif 'style' in kw:\n _style = kw.pop('style')\nself._style = 'CB%i.%s' % (len(self._instance_styles), _style)\nkw['style'] = self._style\nttk.Button.__init__(self, master, **kw... | <|body_start_0|>
self._command = None
if 'command' in kw:
self._command = kw.pop('command')
kw['command'] = self.choosecolour
_style = 'TButton'
if 'style' in kw:
_style = kw.pop('style')
self._style = 'CB%i.%s' % (len(self._instance_styles), _styl... | Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face | ColourTtkButton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name t... | stack_v2_sparse_classes_75kplus_train_007562 | 3,242 | permissive | [
{
"docstring": "provide a name to save between script runs. a command callback can be provided.",
"name": "__init__",
"signature": "def __init__(self, master, **kw)"
},
{
"docstring": "invoked when button pushed to prompt user to select a colour",
"name": "choosecolour",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_test_000799 | Implement the Python class `ColourTtkButton` described below.
Class description:
Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face
Method signatures and docstri... | Implement the Python class `ColourTtkButton` described below.
Class description:
Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face
Method signatures and docstri... | c4e178b33f24e609c812b20bddfff7448782a192 | <|skeleton|>
class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColourTtkButton:
"""Simple colour picker control. ttk Button that uses the picked colour as background and makes text the complementary colour so it stands out. Note: ttk background is area around button rather than button face"""
def __init__(self, master, **kw):
"""provide a name to save betwee... | the_stack_v2_python_sparse | memtkinter/megawidgets/colourbutton.py | JamesGKent/memtkinter | train | 0 |
b978db0826b73b580f4d19c86880a25ec10a8417 | [
"from pages.regions.accordion import Accordion\nfrom pages.regions.treeaccordionitem import LegacyTreeAccordionItem\nreturn Accordion(self.testsetup, LegacyTreeAccordionItem)",
"self.click_on_catalog_item('All Catalog Items')\nself.get_element(*self._configuration_button_locator).click()\nself.get_element(*self._... | <|body_start_0|>
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
<|end_body_0|>
<|body_start_1|>
self.click_on_catalog_item('All Catalog Items')
self.get_e... | Catalog Item page | CatalogItems | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatalogItems:
"""Catalog Item page"""
def accordion(self):
"""accordion"""
<|body_0|>
def add_new_catalog_item(self):
"""click on Configuration and then Add new catalog item btn"""
<|body_1|>
def add_new_catalog_bundle(self):
"""Click on Conf... | stack_v2_sparse_classes_75kplus_train_007563 | 11,585 | no_license | [
{
"docstring": "accordion",
"name": "accordion",
"signature": "def accordion(self)"
},
{
"docstring": "click on Configuration and then Add new catalog item btn",
"name": "add_new_catalog_item",
"signature": "def add_new_catalog_item(self)"
},
{
"docstring": "Click on Configuratio... | 6 | stack_v2_sparse_classes_30k_train_013312 | Implement the Python class `CatalogItems` described below.
Class description:
Catalog Item page
Method signatures and docstrings:
- def accordion(self): accordion
- def add_new_catalog_item(self): click on Configuration and then Add new catalog item btn
- def add_new_catalog_bundle(self): Click on Configuration and t... | Implement the Python class `CatalogItems` described below.
Class description:
Catalog Item page
Method signatures and docstrings:
- def accordion(self): accordion
- def add_new_catalog_item(self): click on Configuration and then Add new catalog item btn
- def add_new_catalog_bundle(self): Click on Configuration and t... | 51bb86fda7d897e90444a6a0380a5aa2c61be6ff | <|skeleton|>
class CatalogItems:
"""Catalog Item page"""
def accordion(self):
"""accordion"""
<|body_0|>
def add_new_catalog_item(self):
"""click on Configuration and then Add new catalog item btn"""
<|body_1|>
def add_new_catalog_bundle(self):
"""Click on Conf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CatalogItems:
"""Catalog Item page"""
def accordion(self):
"""accordion"""
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
def add_new_catalog_i... | the_stack_v2_python_sparse | pages/services_subpages/catalog_subpages/catalog_items.py | sshveta/cfme_tests | train | 0 |
f017615d033168fc9b9492791ddf20715d8e80e2 | [
"if not root:\n return []\ncur_level = [root]\nret = []\nwhile cur_level:\n new_level = []\n ret.append([x.val for x in cur_level])\n for node in cur_level:\n if node.children:\n new_level += node.children\n cur_level = new_level\nreturn ret",
"if root is None or root.val is None:... | <|body_start_0|>
if not root:
return []
cur_level = [root]
ret = []
while cur_level:
new_level = []
ret.append([x.val for x in cur_level])
for node in cur_level:
if node.children:
new_level += node.childr... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder2(self, root: 'Node') -> List[List[int]]:
"""执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]"""
<|body_0|>
def l... | stack_v2_sparse_classes_75kplus_train_007564 | 2,746 | permissive | [
{
"docstring": "执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]",
"name": "levelOrder2",
"signature": "def levelOrder2(self, root: 'Node') -> List[List[int]]"
},
... | 2 | stack_v2_sparse_classes_30k_train_027315 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder2(self, root: 'Node') -> List[List[int]]: 执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less tha... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder2(self, root: 'Node') -> List[List[int]]: 执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less tha... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def levelOrder2(self, root: 'Node') -> List[List[int]]:
"""执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]"""
<|body_0|>
def l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrder2(self, root: 'Node') -> List[List[int]]:
"""执行用时:44 ms, 在所有 Python3 提交中击败了98.00%的用户 内存消耗:16.9 MB, 在所有 Python3 提交中击败了36.93%的用户 The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 104]"""
if not root:
return []
... | the_stack_v2_python_sparse | src/429-N-aryTreeLevelOrderTraversal.py | Jiezhi/myleetcode | train | 1 | |
d204ec37394ca3d9c23e39ec01cb9c303a9927e1 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Admin()",
"from .edge import Edge\nfrom .service_announcement import ServiceAnnouncement\nfrom .sharepoint import Sharepoint\nfrom .edge import Edge\nfrom .service_announcement import ServiceAnnouncement\nfrom .sharepoint import Sharep... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Admin()
<|end_body_0|>
<|body_start_1|>
from .edge import Edge
from .service_announcement import ServiceAnnouncement
from .sharepoint import Sharepoint
from .edge import ... | Admin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Admin:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Admin:
"""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: Admin"""
... | stack_v2_sparse_classes_75kplus_train_007565 | 3,415 | 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: Admin",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_n... | 3 | stack_v2_sparse_classes_30k_train_003171 | Implement the Python class `Admin` described below.
Class description:
Implement the Admin class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Admin: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | Implement the Python class `Admin` described below.
Class description:
Implement the Admin class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Admin: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Admin:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Admin:
"""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: Admin"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Admin:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Admin:
"""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: Admin"""
if not pars... | the_stack_v2_python_sparse | msgraph/generated/models/admin.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
69df24143142a72d0f241dadf0b865be7ea7f793 | [
"if level == 0:\n self.turtle.forward(length)\nelse:\n length = length / 3\n self.turtle.forward(length)\n self.turtle.left(KochCurve.angle)\n self.turtle.forward(length)\n self.turtle.right(2 * KochCurve.angle)\n self.turtle.forward(length)\n self.turtle.left(KochCurve.angle)\n self.turt... | <|body_start_0|>
if level == 0:
self.turtle.forward(length)
else:
length = length / 3
self.turtle.forward(length)
self.turtle.left(KochCurve.angle)
self.turtle.forward(length)
self.turtle.right(2 * KochCurve.angle)
self.... | Implements draw method so that a Koch curve is drawn. | KochCurve | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KochCurve:
"""Implements draw method so that a Koch curve is drawn."""
def draw_koch(self, level, length):
"""Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: divides length by 3 draws a (level-1) koch_curve then turns ... | stack_v2_sparse_classes_75kplus_train_007566 | 11,073 | no_license | [
{
"docstring": "Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: divides length by 3 draws a (level-1) koch_curve then turns KochCurve.angle degrees left draws a (level-1) koch_curve then turns 2*KochCurve.angle degrees right draws a (level-1) koc... | 2 | stack_v2_sparse_classes_30k_train_052561 | Implement the Python class `KochCurve` described below.
Class description:
Implements draw method so that a Koch curve is drawn.
Method signatures and docstrings:
- def draw_koch(self, level, length): Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: div... | Implement the Python class `KochCurve` described below.
Class description:
Implements draw method so that a Koch curve is drawn.
Method signatures and docstrings:
- def draw_koch(self, level, length): Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: div... | 18004379826f172ee42f991bacf769fef5e40ddd | <|skeleton|>
class KochCurve:
"""Implements draw method so that a Koch curve is drawn."""
def draw_koch(self, level, length):
"""Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: divides length by 3 draws a (level-1) koch_curve then turns ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KochCurve:
"""Implements draw method so that a Koch curve is drawn."""
def draw_koch(self, level, length):
"""Recursive function. At level zero just draws a forward line of given length. At higher levels does the following: divides length by 3 draws a (level-1) koch_curve then turns KochCurve.ang... | the_stack_v2_python_sparse | src_py/data structure/week4/fractal_drawing.py | awesome121/some_practice_source_code | train | 0 |
d005a681b544e2eb69e44eefbea590f9c6290906 | [
"schema = LoginSchema()\ndata, errors = schema.load(request.json)\nif errors:\n return (errors, 400)\ntry:\n session_token = auth.dataclient.login(data['email'], data['password'])\n SIG_LOGGED_IN.send(DataClient.query.filter_by(email=data['email']).first())\n return SessionSchema().dump({'session_token'... | <|body_start_0|>
schema = LoginSchema()
data, errors = schema.load(request.json)
if errors:
return (errors, 400)
try:
session_token = auth.dataclient.login(data['email'], data['password'])
SIG_LOGGED_IN.send(DataClient.query.filter_by(email=data['email... | SessionResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionResource:
def post(self):
"""Login route :return:"""
<|body_0|>
def delete(self):
"""Logout route :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
schema = LoginSchema()
data, errors = schema.load(request.json)
if erro... | stack_v2_sparse_classes_75kplus_train_007567 | 3,606 | no_license | [
{
"docstring": "Login route :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Logout route :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048610 | Implement the Python class `SessionResource` described below.
Class description:
Implement the SessionResource class.
Method signatures and docstrings:
- def post(self): Login route :return:
- def delete(self): Logout route :return: | Implement the Python class `SessionResource` described below.
Class description:
Implement the SessionResource class.
Method signatures and docstrings:
- def post(self): Login route :return:
- def delete(self): Logout route :return:
<|skeleton|>
class SessionResource:
def post(self):
"""Login route :ret... | e940e841a115bc7f3b9953ccb6815ae5470b29d2 | <|skeleton|>
class SessionResource:
def post(self):
"""Login route :return:"""
<|body_0|>
def delete(self):
"""Logout route :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionResource:
def post(self):
"""Login route :return:"""
schema = LoginSchema()
data, errors = schema.load(request.json)
if errors:
return (errors, 400)
try:
session_token = auth.dataclient.login(data['email'], data['password'])
SI... | the_stack_v2_python_sparse | backend/app/api/Session.py | yeldiRium/st3k101 | train | 1 | |
2fa417d4d0364590e2fedc09ccc1400d746d34ad | [
"super().__init__()\nself.enc_hidden_size = enc_hidden_size\nself.dec_hidden_size = dec_hidden_size\nself.rnn_type = rnn_type\nself.W = nn.Linear(enc_hidden_size + dec_hidden_size + embed_size, 1)\nself.sigmoid = nn.Sigmoid()",
"p_gen = self.W(torch.cat([context, decoder_state, decoder_input], dim=1))\np_gen = se... | <|body_start_0|>
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hidden_size = dec_hidden_size
self.rnn_type = rnn_type
self.W = nn.Linear(enc_hidden_size + dec_hidden_size + embed_size, 1)
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
... | PointerGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_75kplus_train_007568 | 49,575 | no_license | [
{
"docstring": "Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)",
"name": "__init__",
"signature": "def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM')"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_000577 | Implement the Python class `PointerGenerator` described below.
Class description:
Implement the PointerGenerator class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'): Estimation of Word Generation (vs Copying) Probability Get To The P... | Implement the Python class `PointerGenerator` described below.
Class description:
Implement the PointerGenerator class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'): Estimation of Word Generation (vs Copying) Probability Get To The P... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
super().__init__()
self.enc_hidden_si... | the_stack_v2_python_sparse | generated/test_clovaai_FocusSeq2Seq.py | jansel/pytorch-jit-paritybench | train | 35 | |
b2000e53f05576ee00e9bd057cbc3fb8a7df9e22 | [
"self.w = w\nn = len(w)\nself.r = [0] * n\nfor i in xrange(n):\n if i == 0:\n self.r[i] = w[i]\n else:\n self.r[i] = w[i] + self.r[i - 1]",
"n = len(self.w)\nran = random.randint(1, self.r[-1])\nreturn bisect.bisect_left(self.r, ran)"
] | <|body_start_0|>
self.w = w
n = len(w)
self.r = [0] * n
for i in xrange(n):
if i == 0:
self.r[i] = w[i]
else:
self.r[i] = w[i] + self.r[i - 1]
<|end_body_0|>
<|body_start_1|>
n = len(self.w)
ran = random.randint(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.w = w
n = len(w)
self.r = [0] * n
for i in xrange(n):
i... | stack_v2_sparse_classes_75kplus_train_007569 | 697 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044324 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.w = w
n = len(w)
self.r = [0] * n
for i in xrange(n):
if i == 0:
self.r[i] = w[i]
else:
self.r[i] = w[i] + self.r[i - 1]
def pickIndex(self):
... | the_stack_v2_python_sparse | python/leetcode.528.py | CalvinNeo/LeetCode | train | 3 | |
92cd4e9d5cfa0ea938d5b1ea4f8b8bc19d3fb439 | [
"stats = self._generate_stats(backend_state, filter_properties)\nLOG.debug(\"Checking backend '%s'\", stats[0]['backend_stats']['backend_id'])\nresult = any((self._check_filter_function(stat) for stat in stats))\nLOG.debug('Result: %s', result)\nLOG.debug(\"Done checking backend '%s'\", stats[0]['backend_stats']['b... | <|body_start_0|>
stats = self._generate_stats(backend_state, filter_properties)
LOG.debug("Checking backend '%s'", stats[0]['backend_stats']['backend_id'])
result = any((self._check_filter_function(stat) for stat in stats))
LOG.debug('Result: %s', result)
LOG.debug("Done checking... | DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics. | DriverFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverFilter:
"""DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics."""
def backend_passes(self, backend_state, filter_properties):
"""Determines if a backend has a passing filte... | stack_v2_sparse_classes_75kplus_train_007570 | 6,727 | permissive | [
{
"docstring": "Determines if a backend has a passing filter_function or not.",
"name": "backend_passes",
"signature": "def backend_passes(self, backend_state, filter_properties)"
},
{
"docstring": "Checks if a volume passes a backend's filter function. Returns a tuple in the format (filter_pass... | 4 | stack_v2_sparse_classes_30k_train_008587 | Implement the Python class `DriverFilter` described below.
Class description:
DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics.
Method signatures and docstrings:
- def backend_passes(self, backend_state, filter... | Implement the Python class `DriverFilter` described below.
Class description:
DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics.
Method signatures and docstrings:
- def backend_passes(self, backend_state, filter... | 04a5d6b8c28271f6aefe2bbae6a1e16c1c235835 | <|skeleton|>
class DriverFilter:
"""DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics."""
def backend_passes(self, backend_state, filter_properties):
"""Determines if a backend has a passing filte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DriverFilter:
"""DriverFilter filters backend based on a 'filter function' and metrics. DriverFilter filters based on volume backend's provided 'filter function' and metrics."""
def backend_passes(self, backend_state, filter_properties):
"""Determines if a backend has a passing filter_function or... | the_stack_v2_python_sparse | cinder/scheduler/filters/driver_filter.py | LINBIT/openstack-cinder | train | 9 |
18bc35cb56364350a67d86da166c6cbfda23e7a0 | [
"res = []\n\ndef dfs(node):\n if not node:\n res.append('null')\n return\n res.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ','.join(res)",
"def dfs(queue):\n val = queue.pop(0)\n if val == 'null':\n return None\n node = TreeNode(val)\n n... | <|body_start_0|>
res = []
def dfs(node):
if not node:
res.append('null')
return
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(res)
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_007571 | 1,223 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_047206 | 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:... | a390adeeb71e997b3c1a56c479825d4adda07ef9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def dfs(node):
if not node:
res.append('null')
return
res.append(str(node.val))
dfs(node.left)
... | the_stack_v2_python_sparse | algorithms/python/serializeandDeserializeBinaryTree/serializeandDeserializeBinaryTree.py | MichelleZ/leetcode | train | 3 | |
8d8fffdc351023aa2ebd3667b1db3d381da4a3a2 | [
"encoded_str = []\nfor word in strs:\n encoded_str.append(str(len(word)))\n encoded_str.append('/')\n encoded_str.append(word)\nreturn ''.join(encoded_str)",
"words = []\ni = 0\nwhile i < len(s):\n slash_index = s.find('/', i)\n size = int(s[i:slash_index])\n words.append(s[slash_index + 1:slash... | <|body_start_0|>
encoded_str = []
for word in strs:
encoded_str.append(str(len(word)))
encoded_str.append('/')
encoded_str.append(word)
return ''.join(encoded_str)
<|end_body_0|>
<|body_start_1|>
words = []
i = 0
while i < len(s):
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_007572 | 1,009 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_007772 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 9d0ff0f8705451947a6605ab5ef92bb3e27a7147 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
encoded_str = []
for word in strs:
encoded_str.append(str(len(word)))
encoded_str.append('/')
encoded_str.append(word)
return... | the_stack_v2_python_sparse | string/encode_and_decode_strings.py | rayt579/leetcode | train | 0 | |
2407e8609091d35de55ba356aac97355b16b79e3 | [
"self.avi = avi\nself.delimiter = delimiter\nself.header = header\nself.out = out\nself.threshold = threshold",
"if self.out == '':\n f = sys.stdout\nelse:\n f = open(self.out, 'w')\nif self.header:\n print(self.delimiter.join(('frame_index', 'moving_dots', 'judge')), file=f)\nfor ind, (r, b) in enumerat... | <|body_start_0|>
self.avi = avi
self.delimiter = delimiter
self.header = header
self.out = out
self.threshold = threshold
<|end_body_0|>
<|body_start_1|>
if self.out == '':
f = sys.stdout
else:
f = open(self.out, 'w')
if self.heade... | Make a csv file of results. | MakeCSV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeCSV:
"""Make a csv file of results."""
def __init__(self, avi: str, out: str, delimiter: str=',', header: bool=False, threshold: int=30):
"""Constructor. Args: avi (str): video path out (str): output file path. Defaults to stdout. delimiter (str, optional): delimiter separates va... | stack_v2_sparse_classes_75kplus_train_007573 | 1,362 | no_license | [
{
"docstring": "Constructor. Args: avi (str): video path out (str): output file path. Defaults to stdout. delimiter (str, optional): delimiter separates value. Defaults to ','. header (bool, optional): flag if it inserts a header row. Defaults to False. threshold (int, optional): threshold for judging if a mice... | 2 | stack_v2_sparse_classes_30k_train_030098 | Implement the Python class `MakeCSV` described below.
Class description:
Make a csv file of results.
Method signatures and docstrings:
- def __init__(self, avi: str, out: str, delimiter: str=',', header: bool=False, threshold: int=30): Constructor. Args: avi (str): video path out (str): output file path. Defaults to ... | Implement the Python class `MakeCSV` described below.
Class description:
Make a csv file of results.
Method signatures and docstrings:
- def __init__(self, avi: str, out: str, delimiter: str=',', header: bool=False, threshold: int=30): Constructor. Args: avi (str): video path out (str): output file path. Defaults to ... | e57ae67ef8dca64632c4422b7131e27b0c05cab4 | <|skeleton|>
class MakeCSV:
"""Make a csv file of results."""
def __init__(self, avi: str, out: str, delimiter: str=',', header: bool=False, threshold: int=30):
"""Constructor. Args: avi (str): video path out (str): output file path. Defaults to stdout. delimiter (str, optional): delimiter separates va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MakeCSV:
"""Make a csv file of results."""
def __init__(self, avi: str, out: str, delimiter: str=',', header: bool=False, threshold: int=30):
"""Constructor. Args: avi (str): video path out (str): output file path. Defaults to stdout. delimiter (str, optional): delimiter separates value. Defaults... | the_stack_v2_python_sparse | src/MakeCSV.py | eggplants/mice-freeze-detection | train | 0 |
3ba35986891079022fef3c9adc8aa60af64272f0 | [
"opts = self.get_model()._meta\nextra = ['%s/%s%s.html' % (opts.app_label, opts.object_name.lower(), self.template_name_suffix)]\nreturn extra + super(FlattenPicturesMixin, self).get_template_names()",
"app_label = self.get_model()._meta.app_label\nmodel_name = self.get_model()._meta.object_name.lower()\nattachme... | <|body_start_0|>
opts = self.get_model()._meta
extra = ['%s/%s%s.html' % (opts.app_label, opts.object_name.lower(), self.template_name_suffix)]
return extra + super(FlattenPicturesMixin, self).get_template_names()
<|end_body_0|>
<|body_start_1|>
app_label = self.get_model()._meta.app_la... | FlattenPicturesMixin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlattenPicturesMixin:
def get_template_names(self):
"""Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/17484"""
<|body_0|>
def get_queryset(self):
"""Override queryset to avoid attachment lookup... | stack_v2_sparse_classes_75kplus_train_007574 | 26,214 | permissive | [
{
"docstring": "Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/17484",
"name": "get_template_names",
"signature": "def get_template_names(self)"
},
{
"docstring": "Override queryset to avoid attachment lookup while seriali... | 2 | stack_v2_sparse_classes_30k_train_043520 | Implement the Python class `FlattenPicturesMixin` described below.
Class description:
Implement the FlattenPicturesMixin class.
Method signatures and docstrings:
- def get_template_names(self): Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/174... | Implement the Python class `FlattenPicturesMixin` described below.
Class description:
Implement the FlattenPicturesMixin class.
Method signatures and docstrings:
- def get_template_names(self): Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/174... | 7f2343db50e97bb407e66dc499ab3684e1629661 | <|skeleton|>
class FlattenPicturesMixin:
def get_template_names(self):
"""Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/17484"""
<|body_0|>
def get_queryset(self):
"""Override queryset to avoid attachment lookup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlattenPicturesMixin:
def get_template_names(self):
"""Due to bug in Django, providing get_queryset() method hides template_names lookup. https://code.djangoproject.com/ticket/17484"""
opts = self.get_model()._meta
extra = ['%s/%s%s.html' % (opts.app_label, opts.object_name.lower(), se... | the_stack_v2_python_sparse | geotrek/trekking/views.py | mviadere-openig/Geotrek-admin | train | 0 | |
e5d3246b5fabc31530d11689010a5d3e51035c6d | [
"if not pRoot:\n return True\nleft = self.TreeDepth(pRoot.left)\nright = self.TreeDepth(pRoot.right)\ndiff = left - right\nif diff > 1 or diff < -1:\n return False\nreturn self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)",
"depth = 0\nif not pRoot:\n return depth\nleft = sel... | <|body_start_0|>
if not pRoot:
return True
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
diff = left - right
if diff > 1 or diff < -1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRo... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def IsBalanced_Solution(self, pRoot):
"""在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高"""
<|body_0|>
def TreeDepth(self, pRoot):
"""计算树的深度"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not pRoo... | stack_v2_sparse_classes_75kplus_train_007575 | 2,102 | no_license | [
{
"docstring": "在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高",
"name": "IsBalanced_Solution",
"signature": "def IsBalanced_Solution(self, pRoot)"
},
{
"docstring": "计算树的深度",
"name": "TreeDepth",
"signature": "def TreeDepth(self, pRoot)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027398 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def IsBalanced_Solution(self, pRoot): 在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高
- def TreeDepth(self, pRoot): 计算树的深度 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def IsBalanced_Solution(self, pRoot): 在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高
- def TreeDepth(self, pRoot): 计算树的深度
<|skeleton|>
c... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution1:
def IsBalanced_Solution(self, pRoot):
"""在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高"""
<|body_0|>
def TreeDepth(self, pRoot):
"""计算树的深度"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def IsBalanced_Solution(self, pRoot):
"""在遍历树的每个节点的时候,分别计算以该节点的左右子结点为根结点的树的深度,如果每个节点的左右子树深度相差不超过1,就是平衡二叉树 缺点:一个节点会被重复遍历,时间效率不高"""
if not pRoot:
return True
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
diff = left - right
... | the_stack_v2_python_sparse | 剑指offer/第一遍/tree/18-2.平衡二叉树.py | leilalu/algorithm | train | 0 | |
8258840d056a1f3a19bb0fc4653e605211897320 | [
"method = 'account'\nresource = resources.AccountDetails\nif balance_only:\n method = 'account/balance'\n resource = resources.AccountBalance\ndate_time_sent = datetime.datetime.utcnow()\nresponse = self.request('GET', self.client.urn_edge, method, session=session)\ndate_time_received = datetime.datetime.utcn... | <|body_start_0|>
method = 'account'
resource = resources.AccountDetails
if balance_only:
method = 'account/balance'
resource = resources.AccountBalance
date_time_sent = datetime.datetime.utcnow()
response = self.request('GET', self.client.urn_edge, method,... | Account | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Account:
def get_account(self, balance_only=True, session=None):
"""Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type balance_only: bool :param session: requests session to be used. :type session: requests.Session :re... | stack_v2_sparse_classes_75kplus_train_007576 | 2,674 | permissive | [
{
"docstring": "Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type balance_only: bool :param session: requests session to be used. :type session: requests.Session :returns: Returns the account details for the logged-in user. :rtype: json :rai... | 3 | stack_v2_sparse_classes_30k_train_031240 | Implement the Python class `Account` described below.
Class description:
Implement the Account class.
Method signatures and docstrings:
- def get_account(self, balance_only=True, session=None): Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type bal... | Implement the Python class `Account` described below.
Class description:
Implement the Account class.
Method signatures and docstrings:
- def get_account(self, balance_only=True, session=None): Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type bal... | d29f4704a0f69fa623422243d0b8372c8c172a2d | <|skeleton|>
class Account:
def get_account(self, balance_only=True, session=None):
"""Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type balance_only: bool :param session: requests session to be used. :type session: requests.Session :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Account:
def get_account(self, balance_only=True, session=None):
"""Get account information for logged in user. :param balance_only: retrieve only account balance info subset or not. :type balance_only: bool :param session: requests session to be used. :type session: requests.Session :returns: Returns... | the_stack_v2_python_sparse | matchbook/endpoints/account.py | rozzac90/matchbook | train | 14 | |
edc9cd0a5e7420f36d3244a802e84151589982e9 | [
"try:\n sku = SKU.objects.filter(id=value)\nexcept:\n raise serializers.ValidationError('商品不存在!')\nreturn value",
"\"\"\"\n 获取用户id\n 读取验证后的sku_id\n 连接redis对象\n 去重\n 保存\n 截取前五个浏览记录\n 返回\n \"\"\"\nuser_id = self.context['request'].user.id\nsku_id = valid... | <|body_start_0|>
try:
sku = SKU.objects.filter(id=value)
except:
raise serializers.ValidationError('商品不存在!')
return value
<|end_body_0|>
<|body_start_1|>
"""
获取用户id
读取验证后的sku_id
连接redis对象
去重
... | 添加用户浏览记录校验 | UserBrowseHistorySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBrowseHistorySerializer:
"""添加用户浏览记录校验"""
def validate_sku_id(self, value):
"""校验"""
<|body_0|>
def create(self, validated_data):
"""存储浏览记录行为"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
sku = SKU.objects.filter(id=value)... | stack_v2_sparse_classes_75kplus_train_007577 | 8,286 | no_license | [
{
"docstring": "校验",
"name": "validate_sku_id",
"signature": "def validate_sku_id(self, value)"
},
{
"docstring": "存储浏览记录行为",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002663 | Implement the Python class `UserBrowseHistorySerializer` described below.
Class description:
添加用户浏览记录校验
Method signatures and docstrings:
- def validate_sku_id(self, value): 校验
- def create(self, validated_data): 存储浏览记录行为 | Implement the Python class `UserBrowseHistorySerializer` described below.
Class description:
添加用户浏览记录校验
Method signatures and docstrings:
- def validate_sku_id(self, value): 校验
- def create(self, validated_data): 存储浏览记录行为
<|skeleton|>
class UserBrowseHistorySerializer:
"""添加用户浏览记录校验"""
def validate_sku_id(s... | 61798f2c3624bfde540cfb7469d42564ffe674a6 | <|skeleton|>
class UserBrowseHistorySerializer:
"""添加用户浏览记录校验"""
def validate_sku_id(self, value):
"""校验"""
<|body_0|>
def create(self, validated_data):
"""存储浏览记录行为"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserBrowseHistorySerializer:
"""添加用户浏览记录校验"""
def validate_sku_id(self, value):
"""校验"""
try:
sku = SKU.objects.filter(id=value)
except:
raise serializers.ValidationError('商品不存在!')
return value
def create(self, validated_data):
"""存储浏览记... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/serializers.py | MEGALO-JOE/meiduo | train | 0 |
625a75bdb1290636b856394fe67b01093b214843 | [
"s = db.session()\ntry:\n result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder.id).all()\n return [value.to_json() for value in result]\nexcept Exception as e:\n print(e)\n return s... | <|body_start_0|>
s = db.session()
try:
result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder.id).all()
return [value.to_json() for value in result]
ex... | FolderModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FolderModel:
def QueryFolderByParamRequest(self, pid, admin_id):
"""文件夹列表"""
<|body_0|>
def CreateFolderRequest(self, params):
"""新建文件夹"""
<|body_1|>
def ModifyFolderRequest(self, folder_id, params):
"""修改文件夹"""
<|body_2|>
def DelFol... | stack_v2_sparse_classes_75kplus_train_007578 | 2,905 | permissive | [
{
"docstring": "文件夹列表",
"name": "QueryFolderByParamRequest",
"signature": "def QueryFolderByParamRequest(self, pid, admin_id)"
},
{
"docstring": "新建文件夹",
"name": "CreateFolderRequest",
"signature": "def CreateFolderRequest(self, params)"
},
{
"docstring": "修改文件夹",
"name": "Mo... | 4 | stack_v2_sparse_classes_30k_train_029782 | Implement the Python class `FolderModel` described below.
Class description:
Implement the FolderModel class.
Method signatures and docstrings:
- def QueryFolderByParamRequest(self, pid, admin_id): 文件夹列表
- def CreateFolderRequest(self, params): 新建文件夹
- def ModifyFolderRequest(self, folder_id, params): 修改文件夹
- def Del... | Implement the Python class `FolderModel` described below.
Class description:
Implement the FolderModel class.
Method signatures and docstrings:
- def QueryFolderByParamRequest(self, pid, admin_id): 文件夹列表
- def CreateFolderRequest(self, params): 新建文件夹
- def ModifyFolderRequest(self, folder_id, params): 修改文件夹
- def Del... | 62fe4b3e264176bb582a278c81814ed5ec13caec | <|skeleton|>
class FolderModel:
def QueryFolderByParamRequest(self, pid, admin_id):
"""文件夹列表"""
<|body_0|>
def CreateFolderRequest(self, params):
"""新建文件夹"""
<|body_1|>
def ModifyFolderRequest(self, folder_id, params):
"""修改文件夹"""
<|body_2|>
def DelFol... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FolderModel:
def QueryFolderByParamRequest(self, pid, admin_id):
"""文件夹列表"""
s = db.session()
try:
result = Folder.query.filter(or_(and_(Folder.is_sys == True, Folder.pid == pid), and_(Folder.is_sys == False, Folder.pid == pid, Folder.admin_id == admin_id))).order_by(Folder... | the_stack_v2_python_sparse | collection/v1/folder.py | huzidabanzhang/python-admin | train | 32 | |
d221c83d83f355279c80da21ad4abdc0fde49f50 | [
"ctree_visitor_t.__init__(self, CV_FAST)\nself.handler = handler\nself.item_list = item_list",
"e = HxCItem.from_citem(i)\nif isinstance(e, tuple(self.item_list)):\n self.handler(e)\nreturn 0",
"e = HxCItem.from_citem(i)\nif isinstance(e, tuple(self.item_list)):\n self.handler(e)\nreturn 0"
] | <|body_start_0|>
ctree_visitor_t.__init__(self, CV_FAST)
self.handler = handler
self.item_list = item_list
<|end_body_0|>
<|body_start_1|>
e = HxCItem.from_citem(i)
if isinstance(e, tuple(self.item_list)):
self.handler(e)
return 0
<|end_body_1|>
<|body_start... | Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`). | _hx_visitor_list_all | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _hx_visitor_list_all:
"""Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`)."""
def __init__(self, item_list, handler):
"""Creator for the visitor. :param item_list: A list of class which inherit from :class:`HxCItem`, only item in the lis... | stack_v2_sparse_classes_75kplus_train_007579 | 6,978 | permissive | [
{
"docstring": "Creator for the visitor. :param item_list: A list of class which inherit from :class:`HxCItem`, only item in the list will be visited. :param handler: A function which take as argument an :class:`HxCItem` object. This function will be called on :class:`HxCItem` which are in the ``item_list``.",
... | 3 | null | Implement the Python class `_hx_visitor_list_all` described below.
Class description:
Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`).
Method signatures and docstrings:
- def __init__(self, item_list, handler): Creator for the visitor. :param item_list: A list of class ... | Implement the Python class `_hx_visitor_list_all` described below.
Class description:
Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`).
Method signatures and docstrings:
- def __init__(self, item_list, handler): Creator for the visitor. :param item_list: A list of class ... | 6140165901cbfa91d08430ecddff2a25e2bcf4a7 | <|skeleton|>
class _hx_visitor_list_all:
"""Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`)."""
def __init__(self, item_list, handler):
"""Creator for the visitor. :param item_list: A list of class which inherit from :class:`HxCItem`, only item in the lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _hx_visitor_list_all:
"""Inherit from the ``ctree_visitor_t`` class and allow to visit all statements (:class:`HxCExpr`)."""
def __init__(self, item_list, handler):
"""Creator for the visitor. :param item_list: A list of class which inherit from :class:`HxCItem`, only item in the list will be vis... | the_stack_v2_python_sparse | bip/hexrays/hx_visitor.py | BrunoPujos/bip | train | 1 |
8a17a6b99abbd4cde8168519893b6bdfb2a3e165 | [
"if request.method != 'POST':\n return True\nreturn request.user.has_perm('VIEW_USERS')",
"if request.user.has_perm('EDIT_USERS'):\n return True\nif obj.id == request.user.id and request.method in permissions.SAFE_METHODS:\n return True\nif request.method == 'GET' and request.user.has_perm('VIEW_USERS'):... | <|body_start_0|>
if request.method != 'POST':
return True
return request.user.has_perm('VIEW_USERS')
<|end_body_0|>
<|body_start_1|>
if request.user.has_perm('EDIT_USERS'):
return True
if obj.id == request.user.id and request.method in permissions.SAFE_METHODS:
... | Used by Viewset to check permissions for API requests | UserPermissions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Check permiss... | stack_v2_sparse_classes_75kplus_train_007580 | 919 | permissive | [
{
"docstring": "Check permissions When an object does not yet exist (POST)",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Check permissions When an object does exist (PUT, GET)",
"name": "has_object_permission",
"signature": "def has... | 2 | null | Implement the Python class `UserPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def has_permission(self, request, view): Check permissions When an object does not yet exist (POST)
- def has_object_permission(self, request, view... | Implement the Python class `UserPermissions` described below.
Class description:
Used by Viewset to check permissions for API requests
Method signatures and docstrings:
- def has_permission(self, request, view): Check permissions When an object does not yet exist (POST)
- def has_object_permission(self, request, view... | b395efe620a1b82c2ecee2004cca358d8407397e | <|skeleton|>
class UserPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Check permiss... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserPermissions:
"""Used by Viewset to check permissions for API requests"""
def has_permission(self, request, view):
"""Check permissions When an object does not yet exist (POST)"""
if request.method != 'POST':
return True
return request.user.has_perm('VIEW_USERS')
... | the_stack_v2_python_sparse | backend/api/permissions/user.py | emi-hi/zeva | train | 0 |
2e867d88868fdbb71d511ae489fceb01ea398593 | [
"self.width = width\nself.height = height\nself.offset_width = offset_width\nself.offset_height = offset_height\nself.temps = temps\nself.dt = dt\nself.count = count\nself.pendulum_1 = pendulum_1\nself.pendulum_2 = pendulum_2\nself.gap = gap\nself.temps_exec = temps_exec\nself.escala_moviment = 0.9 * (width - escal... | <|body_start_0|>
self.width = width
self.height = height
self.offset_width = offset_width
self.offset_height = offset_height
self.temps = temps
self.dt = dt
self.count = count
self.pendulum_1 = pendulum_1
self.pendulum_2 = pendulum_2
self.g... | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap: float, temps_exec: float, temps: np.ndarray, width: int=1200, height: int=600, offset_width: int=600, offset_height: int=300, dt: float=0.05, count: int=0):
"""Initialize the widget for the double pendulum animation... | stack_v2_sparse_classes_75kplus_train_007581 | 6,624 | no_license | [
{
"docstring": "Initialize the widget for the double pendulum animation. offset_width and offset_height represent the x and y offsets from the top left corner of the canvas to place the first pendulum.",
"name": "__init__",
"signature": "def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap... | 4 | stack_v2_sparse_classes_30k_train_032513 | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap: float, temps_exec: float, temps: np.ndarray, width: int=1200, height: int=600, offset_width: int=600, offset_height: int... | Implement the Python class `App` described below.
Class description:
Implement the App class.
Method signatures and docstrings:
- def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap: float, temps_exec: float, temps: np.ndarray, width: int=1200, height: int=600, offset_width: int=600, offset_height: int... | 2551bb8d85d60268a1a80dd97d8dc66dbbe06888 | <|skeleton|>
class App:
def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap: float, temps_exec: float, temps: np.ndarray, width: int=1200, height: int=600, offset_width: int=600, offset_height: int=300, dt: float=0.05, count: int=0):
"""Initialize the widget for the double pendulum animation... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
def __init__(self, pendulum_1: Pendulum, pendulum_2: Pendulum, gap: float, temps_exec: float, temps: np.ndarray, width: int=1200, height: int=600, offset_width: int=600, offset_height: int=300, dt: float=0.05, count: int=0):
"""Initialize the widget for the double pendulum animation. offset_width... | the_stack_v2_python_sparse | Source/Animacio.py | srmarcballestero/Newtons-Cradle | train | 1 | |
f3ade12a4fbe6fb11c307efd69d468714a469d9b | [
"self.id = id\nself.mtype = mtype\nself.data = data\nself.status = status\nself.status_reasons = status_reasons",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nmtype = dictionary.get('type')\ndata = dictionary.get('data')\nstatus = dictionary.get('status')\nstatus_reasons = None\nif diction... | <|body_start_0|>
self.id = id
self.mtype = mtype
self.data = data
self.status = status
self.status_reasons = status_reasons
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
mtype = dictionary.get('ty... | Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (PaymentMethodStatusEnum): TODO: type description here. status_reasons (list of St... | PaymentMethod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentMethod:
"""Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (PaymentMethodStatusEnum): TODO: type des... | stack_v2_sparse_classes_75kplus_train_007582 | 2,493 | permissive | [
{
"docstring": "Constructor for the PaymentMethod class",
"name": "__init__",
"signature": "def __init__(self, id=None, mtype=None, data=None, status=None, status_reasons=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary rep... | 2 | stack_v2_sparse_classes_30k_train_002982 | Implement the Python class `PaymentMethod` described below.
Class description:
Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (P... | Implement the Python class `PaymentMethod` described below.
Class description:
Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (P... | e1ca52116aabfcdb2f36c24ebd866cf00bb5c6c9 | <|skeleton|>
class PaymentMethod:
"""Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (PaymentMethodStatusEnum): TODO: type des... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaymentMethod:
"""Implementation of the 'PaymentMethod' model. TODO: type model description here. Attributes: id (uuid|string): TODO: type description here. mtype (Type2Enum): TODO: type description here. data (object): TODO: type description here. status (PaymentMethodStatusEnum): TODO: type description here... | the_stack_v2_python_sparse | plastiqpublicapi/models/payment_method.py | jeffkynaston/sdk-spike-python-apimatic | train | 0 |
494967e79f0a9fa3e6333dfe2d57f191ece3b6e5 | [
"AxisFormat.__init__(self, 'clustersold')\nself._axes['energy'] = 0\nself._axes['vertexz'] = 1\nself._axes['pileup'] = 2\nself._axes['mbtrigger'] = 3",
"newobj = AxisFormatClustersOld()\nnewobj._Deepcopy(other, memo)\nreturn newobj",
"newobj = AxisFormatClustersOld()\nnewobj._Copy()\nreturn newobj"
] | <|body_start_0|>
AxisFormat.__init__(self, 'clustersold')
self._axes['energy'] = 0
self._axes['vertexz'] = 1
self._axes['pileup'] = 2
self._axes['mbtrigger'] = 3
<|end_body_0|>
<|body_start_1|>
newobj = AxisFormatClustersOld()
newobj._Deepcopy(other, memo)
... | Axis format for old cluster THnSparse | AxisFormatClustersOld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatClustersOld:
"""Axis format for old cluster THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy constru... | stack_v2_sparse_classes_75kplus_train_007583 | 5,256 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __deepcopy__(self, other, memo)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"sig... | 3 | stack_v2_sparse_classes_30k_train_017330 | Implement the Python class `AxisFormatClustersOld` described below.
Class description:
Axis format for old cluster THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor | Implement the Python class `AxisFormatClustersOld` described below.
Class description:
Axis format for old cluster THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, other, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor
<|skeleto... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatClustersOld:
"""Axis format for old cluster THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, other, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy constru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AxisFormatClustersOld:
"""Axis format for old cluster THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'clustersold')
self._axes['energy'] = 0
self._axes['vertexz'] = 1
self._axes['pileup'] = 2
self._axes['mbtrigger'] = 3
de... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/ClusterTHnSparse.py | alisw/AliPhysics | train | 129 |
f6de65b9d77c58b6396c7c3cea8068e5424a62d4 | [
"self.char_domain_size = char_domain_size\nself.embedding_size = char_embedding_dim\nself.hidden_dim = hidden_dim\nself.output_size = 2 * self.hidden_dim\nprint('Bi-LSTM char embedding model')\nprint('embedding dim: ', self.embedding_size)\nprint('out dim: ', self.output_size)\nself.input_chars = tf.placeholder(tf.... | <|body_start_0|>
self.char_domain_size = char_domain_size
self.embedding_size = char_embedding_dim
self.hidden_dim = hidden_dim
self.output_size = 2 * self.hidden_dim
print('Bi-LSTM char embedding model')
print('embedding dim: ', self.embedding_size)
print('out di... | A bidirectional LSTM for embedding tokens. | BiLSTMChar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTMChar:
"""A bidirectional LSTM for embedding tokens."""
def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None):
"""Initializing a Bi-LSTM layer for character embedding of a word :param char_domain_size: :param char_embedding_dim: :param hidden_dim:... | stack_v2_sparse_classes_75kplus_train_007584 | 16,396 | no_license | [
{
"docstring": "Initializing a Bi-LSTM layer for character embedding of a word :param char_domain_size: :param char_embedding_dim: :param hidden_dim: :param embeddings:",
"name": "__init__",
"signature": "def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_049358 | Implement the Python class `BiLSTMChar` described below.
Class description:
A bidirectional LSTM for embedding tokens.
Method signatures and docstrings:
- def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None): Initializing a Bi-LSTM layer for character embedding of a word :param char_d... | Implement the Python class `BiLSTMChar` described below.
Class description:
A bidirectional LSTM for embedding tokens.
Method signatures and docstrings:
- def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None): Initializing a Bi-LSTM layer for character embedding of a word :param char_d... | 74fa736cda906208c0ff792e10c7fa472859654a | <|skeleton|>
class BiLSTMChar:
"""A bidirectional LSTM for embedding tokens."""
def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None):
"""Initializing a Bi-LSTM layer for character embedding of a word :param char_domain_size: :param char_embedding_dim: :param hidden_dim:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiLSTMChar:
"""A bidirectional LSTM for embedding tokens."""
def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None):
"""Initializing a Bi-LSTM layer for character embedding of a word :param char_domain_size: :param char_embedding_dim: :param hidden_dim: :param embed... | the_stack_v2_python_sparse | src/models/bilstm.py | pj0616/entity_disambiguation | train | 0 |
77d008532919efcc6c3abc352c4d3b9d5e1c210e | [
"result = []\nif not root:\n return result\nstackOfNode = [root]\nstackOfString = [str(root.val)]\nwhile stackOfNode:\n currNode = stackOfNode.pop()\n currString = stackOfString.pop()\n if currNode.left:\n stackOfNode.append(currNode.left)\n stackOfString.append(currString + '->' + str(cur... | <|body_start_0|>
result = []
if not root:
return result
stackOfNode = [root]
stackOfString = [str(root.val)]
while stackOfNode:
currNode = stackOfNode.pop()
currString = stackOfString.pop()
if currNode.left:
stackOfN... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def binaryTreePaths_self(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
if... | stack_v2_sparse_classes_75kplus_train_007585 | 1,739 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths",
"signature": "def binaryTreePaths(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths_self",
"signature": "def binaryTreePaths_self(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014745 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def binaryTreePaths_self(self, root): :type root: TreeNode :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str]
- def binaryTreePaths_self(self, root): :type root: TreeNode :rtype: List[str]
<|skeleton|>
class Solutio... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_0|>
def binaryTreePaths_self(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
result = []
if not root:
return result
stackOfNode = [root]
stackOfString = [str(root.val)]
while stackOfNode:
currNode = stackOfNode.pop()
... | the_stack_v2_python_sparse | 257_binary_tree_paths/sol.py | lianke123321/leetcode_sol | train | 0 | |
f19998dd9491bfa17c56a9ea424afbaf2907d2d7 | [
"super().__init__()\nif hidden_dim != 0:\n self.fc = nn.Linear(input_dim, hidden_dim)\n self.fc_out = nn.Linear(hidden_dim, output_dim)\nelse:\n self.fc = None\n self.fc_out = nn.Linear(input_dim, output_dim)\nself.dropout = nn.Dropout(dropout)",
"if type(token_states) == list:\n token_states = tok... | <|body_start_0|>
super().__init__()
if hidden_dim != 0:
self.fc = nn.Linear(input_dim, hidden_dim)
self.fc_out = nn.Linear(hidden_dim, output_dim)
else:
self.fc = None
self.fc_out = nn.Linear(input_dim, output_dim)
self.dropout = nn.Dropout... | An unary factor for each token's dense representation. | UnaryFactor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnaryFactor:
"""An unary factor for each token's dense representation."""
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, dropout: float):
"""Args: input_dim: dimension of the representation for each token. output_dim: size of the label space. hidden_dim: size of... | stack_v2_sparse_classes_75kplus_train_007586 | 1,842 | permissive | [
{
"docstring": "Args: input_dim: dimension of the representation for each token. output_dim: size of the label space. hidden_dim: size of the hidden state in the fc layer. dropout: the dropout rate.",
"name": "__init__",
"signature": "def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, ... | 2 | stack_v2_sparse_classes_30k_train_033737 | Implement the Python class `UnaryFactor` described below.
Class description:
An unary factor for each token's dense representation.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, dropout: float): Args: input_dim: dimension of the representation for each token.... | Implement the Python class `UnaryFactor` described below.
Class description:
An unary factor for each token's dense representation.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, dropout: float): Args: input_dim: dimension of the representation for each token.... | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | <|skeleton|>
class UnaryFactor:
"""An unary factor for each token's dense representation."""
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, dropout: float):
"""Args: input_dim: dimension of the representation for each token. output_dim: size of the label space. hidden_dim: size of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnaryFactor:
"""An unary factor for each token's dense representation."""
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int, dropout: float):
"""Args: input_dim: dimension of the representation for each token. output_dim: size of the label space. hidden_dim: size of the hidden s... | the_stack_v2_python_sparse | nsr/model/unary_factor.py | GaoSida/Neural-SampleRank | train | 3 |
4f66e54fa3bcc32f894bf41c820bc313e319b963 | [
"self.suits = Hist()\nself.ranks = Hist()\nfor c in self.cards:\n self.suits.count(c.suit)\n self.ranks.count(c.rank)\nself.sets = list(self.ranks.values())\nself.sets.sort(reverse=True)",
"self.suits = {}\nfor card in self.cards:\n self.suits[card.suit] = self.suits.get(card.suit, 0) + 1",
"ranks = se... | <|body_start_0|>
self.suits = Hist()
self.ranks = Hist()
for c in self.cards:
self.suits.count(c.suit)
self.ranks.count(c.rank)
self.sets = list(self.ranks.values())
self.sets.sort(reverse=True)
<|end_body_0|>
<|body_start_1|>
self.suits = {}
... | Represents a poker hand. | PokerHand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PokerHand:
"""Represents a poker hand."""
def make_histograms(self):
"""Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted list of the rank sets in the hand."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_007587 | 3,720 | no_license | [
{
"docstring": "Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted list of the rank sets in the hand.",
"name": "make_histograms",
"signature": "def make_histograms(self)"
},
{
"docstring": "Bu... | 6 | stack_v2_sparse_classes_30k_train_043002 | Implement the Python class `PokerHand` described below.
Class description:
Represents a poker hand.
Method signatures and docstrings:
- def make_histograms(self): Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted l... | Implement the Python class `PokerHand` described below.
Class description:
Represents a poker hand.
Method signatures and docstrings:
- def make_histograms(self): Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted l... | 99014136922a16caa1f67db8027ff59a68d1bdcd | <|skeleton|>
class PokerHand:
"""Represents a poker hand."""
def make_histograms(self):
"""Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted list of the rank sets in the hand."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PokerHand:
"""Represents a poker hand."""
def make_histograms(self):
"""Computes histograms for suits and hands. Creates attributes: suits: a histogram of the suits in the hand. ranks: a histogram of the ranks. sets: a sorted list of the rank sets in the hand."""
self.suits = Hist()
... | the_stack_v2_python_sparse | lab10/PokerHand.py | nwu-cs/class-materials | train | 0 |
cd3e925a87b0c844c7356e4439c38ac16a41aa5f | [
"filetype = filename[-3:]\nif filetype == 'txt' or filetype == 'log':\n with open(os.path.join(filepath, filename), 'r') as file:\n data = [line.rstrip('\\n') for line in file]\n Cleanser.write(data, filename, filepath)\nelif filetype == 'csv':\n data_csv = []\n with open(os.path.join(filepath, f... | <|body_start_0|>
filetype = filename[-3:]
if filetype == 'txt' or filetype == 'log':
with open(os.path.join(filepath, filename), 'r') as file:
data = [line.rstrip('\n') for line in file]
Cleanser.write(data, filename, filepath)
elif filetype == 'csv':
... | Cleanser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cleanser:
def reader(filename, filepath):
"""Reads the lines from the file to be cleansed into a list."""
<|body_0|>
def write(lineList, filename, filepath):
"""Writes the cleansed lines into a new document."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007588 | 2,907 | no_license | [
{
"docstring": "Reads the lines from the file to be cleansed into a list.",
"name": "reader",
"signature": "def reader(filename, filepath)"
},
{
"docstring": "Writes the cleansed lines into a new document.",
"name": "write",
"signature": "def write(lineList, filename, filepath)"
}
] | 2 | null | Implement the Python class `Cleanser` described below.
Class description:
Implement the Cleanser class.
Method signatures and docstrings:
- def reader(filename, filepath): Reads the lines from the file to be cleansed into a list.
- def write(lineList, filename, filepath): Writes the cleansed lines into a new document... | Implement the Python class `Cleanser` described below.
Class description:
Implement the Cleanser class.
Method signatures and docstrings:
- def reader(filename, filepath): Reads the lines from the file to be cleansed into a list.
- def write(lineList, filename, filepath): Writes the cleansed lines into a new document... | 6d02efb4505c550a659bc68cb66385d00b4b6725 | <|skeleton|>
class Cleanser:
def reader(filename, filepath):
"""Reads the lines from the file to be cleansed into a list."""
<|body_0|>
def write(lineList, filename, filepath):
"""Writes the cleansed lines into a new document."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cleanser:
def reader(filename, filepath):
"""Reads the lines from the file to be cleansed into a list."""
filetype = filename[-3:]
if filetype == 'txt' or filetype == 'log':
with open(os.path.join(filepath, filename), 'r') as file:
data = [line.rstrip('\n') ... | the_stack_v2_python_sparse | src/Cleanser.py | CS4311-spring-2020/pick-tool-team03-we-showed-up | train | 2 | |
1e27a0cd7e1f975678c76f51b457b4892efc0954 | [
"if monosaccharide_codes is None:\n self.monosaccharide_codes = get_default_monosaccharide_codes()\nself.parser = self._create_gsl_parser()",
"glycan_string = glycosciences_to_cfg(glycan_string)\nparsed_result = self.parser.parseString(glycan_string)\nresults = parse_gsl_structure_to_graph(parsed_result, parse... | <|body_start_0|>
if monosaccharide_codes is None:
self.monosaccharide_codes = get_default_monosaccharide_codes()
self.parser = self._create_gsl_parser()
<|end_body_0|>
<|body_start_1|>
glycan_string = glycosciences_to_cfg(glycan_string)
parsed_result = self.parser.parseStrin... | A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings. | GSLGlycanParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GSLGlycanParser:
"""A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings."""
def __init__(self, monosaccharide_codes=None):
"""Create a parser object which can then be used to parse ... | stack_v2_sparse_classes_75kplus_train_007589 | 15,637 | permissive | [
{
"docstring": "Create a parser object which can then be used to parse multiple GSL glycan strings. Args: monosaccharide_codes (list, optional): A list of monosaccharide codes to initialise the parser with. If `None`, then uses the KEGG list of glycan codes, with the addition of `G-ol`, which appears in the CFG... | 3 | stack_v2_sparse_classes_30k_train_053445 | Implement the Python class `GSLGlycanParser` described below.
Class description:
A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings.
Method signatures and docstrings:
- def __init__(self, monosaccharide_codes=None)... | Implement the Python class `GSLGlycanParser` described below.
Class description:
A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings.
Method signatures and docstrings:
- def __init__(self, monosaccharide_codes=None)... | 2faa2856f370dbe5893d0e0f4e0082c956939335 | <|skeleton|>
class GSLGlycanParser:
"""A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings."""
def __init__(self, monosaccharide_codes=None):
"""Create a parser object which can then be used to parse ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GSLGlycanParser:
"""A parser for Glycoscience Laboratory (Imperial College London) glycan strings. Provides access to a parser object that can be used to parse glycan strings."""
def __init__(self, monosaccharide_codes=None):
"""Create a parser object which can then be used to parse multiple GSL ... | the_stack_v2_python_sparse | ccarl/glycan_parsers/gsl_parser.py | andrewguy/CCARL | train | 3 |
9bddf3dc21aed011de2bf79da434b0ade00c3668 | [
"words = re.split('\\\\W+', self.name)\nwords = list(filter(lambda word: len(word) > 3, words))\nreturn ' '.join(words).lower()",
"if not self.tags:\n tags = self._create_tags()\n if tags:\n self.tags = self._create_tags()\n'If no set meta-parameters html - title or description then\\n generat... | <|body_start_0|>
words = re.split('\\W+', self.name)
words = list(filter(lambda word: len(word) > 3, words))
return ' '.join(words).lower()
<|end_body_0|>
<|body_start_1|>
if not self.tags:
tags = self._create_tags()
if tags:
self.tags = self._cre... | Article | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Article:
def _create_tags(self):
"""Create tags from name of article"""
<|body_0|>
def save(self, *args, **kwargs):
"""If tags not determinated then generating their"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
words = re.split('\\W+', self.name)... | stack_v2_sparse_classes_75kplus_train_007590 | 5,531 | no_license | [
{
"docstring": "Create tags from name of article",
"name": "_create_tags",
"signature": "def _create_tags(self)"
},
{
"docstring": "If tags not determinated then generating their",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050995 | Implement the Python class `Article` described below.
Class description:
Implement the Article class.
Method signatures and docstrings:
- def _create_tags(self): Create tags from name of article
- def save(self, *args, **kwargs): If tags not determinated then generating their | Implement the Python class `Article` described below.
Class description:
Implement the Article class.
Method signatures and docstrings:
- def _create_tags(self): Create tags from name of article
- def save(self, *args, **kwargs): If tags not determinated then generating their
<|skeleton|>
class Article:
def _cr... | c4bb84cd3f3addf40cc27f0a8ee22fb77eff5456 | <|skeleton|>
class Article:
def _create_tags(self):
"""Create tags from name of article"""
<|body_0|>
def save(self, *args, **kwargs):
"""If tags not determinated then generating their"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Article:
def _create_tags(self):
"""Create tags from name of article"""
words = re.split('\\W+', self.name)
words = list(filter(lambda word: len(word) > 3, words))
return ' '.join(words).lower()
def save(self, *args, **kwargs):
"""If tags not determinated then gene... | the_stack_v2_python_sparse | src/apps/posts/models.py | artempy/tourism_django | train | 3 | |
aa6cea4db7feb61a837d7c248371e0283b3aa299 | [
"self.__width = width\nself.__height = height\nself.__score = 0\nself.__f = 0\nself.__food = food\nself.__snake = deque([(0, 0)])\nself.__direction = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nself.__lookup = {(0, 0)}",
"def valid(x, y):\n return 0 <= x < self.__height and 0 <= y < self.__width an... | <|body_start_0|>
self.__width = width
self.__height = height
self.__score = 0
self.__f = 0
self.__food = food
self.__snake = deque([(0, 0)])
self.__direction = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
self.__lookup = {(0, 0)}
<|end_body_0|>
... | SnakeGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus_train_007591 | 1,950 | permissive | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_029327 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | Python/design-snake-game.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
1cc4658348411f1a556b9ab87261f4116b5edb15 | [
"count = task_obj.find({'status': 1}).count()\nprint('queue status:1 count: {}'.format(count))\nwhile count >= max_enqueue_num:\n time.sleep(int(count) / 6)\n count = task_obj.find({'status': 1}).count()",
"try:\n print('获取爬虫: {} 的同步数据'.format(obj.__class__.__name__))\n result = obj.get_result()\n ... | <|body_start_0|>
count = task_obj.find({'status': 1}).count()
print('queue status:1 count: {}'.format(count))
while count >= max_enqueue_num:
time.sleep(int(count) / 6)
count = task_obj.find({'status': 1}).count()
<|end_body_0|>
<|body_start_1|>
try:
... | 爬虫项目的工具类 | CrawlerHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrawlerHelper:
"""爬虫项目的工具类"""
def delay_by_task_count(task_obj, max_enqueue_num=200):
"""根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:"""
<|body_0|>
def get_sync_result(cls, obj, retry=3, delay_time=20):
"""通用的获取同... | stack_v2_sparse_classes_75kplus_train_007592 | 1,942 | permissive | [
{
"docstring": "根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:",
"name": "delay_by_task_count",
"signature": "def delay_by_task_count(task_obj, max_enqueue_num=200)"
},
{
"docstring": "通用的获取同步爬虫请求的方法 :param obj: 同步爬虫的实例 :param retry: 重试次数,默认重试3次 :... | 3 | stack_v2_sparse_classes_30k_train_017572 | Implement the Python class `CrawlerHelper` described below.
Class description:
爬虫项目的工具类
Method signatures and docstrings:
- def delay_by_task_count(task_obj, max_enqueue_num=200): 根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:
- def get_sync_result(cls, obj, retry=3, d... | Implement the Python class `CrawlerHelper` described below.
Class description:
爬虫项目的工具类
Method signatures and docstrings:
- def delay_by_task_count(task_obj, max_enqueue_num=200): 根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:
- def get_sync_result(cls, obj, retry=3, d... | 29ba13905c73081097df9ef646a5c8194eb024be | <|skeleton|>
class CrawlerHelper:
"""爬虫项目的工具类"""
def delay_by_task_count(task_obj, max_enqueue_num=200):
"""根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:"""
<|body_0|>
def get_sync_result(cls, obj, retry=3, delay_time=20):
"""通用的获取同... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrawlerHelper:
"""爬虫项目的工具类"""
def delay_by_task_count(task_obj, max_enqueue_num=200):
"""根据task数量缓慢写入抓取任务 :param task_obj: 查询队列的task mongo实例 :param max_enqueue_num: 写入队列的队列最大值 :return:"""
count = task_obj.find({'status': 1}).count()
print('queue status:1 count: {}'.format(count))
... | the_stack_v2_python_sparse | pyspider/helper/crawler_utils.py | UoToGK/crawler-pyspider | train | 0 |
36a5f4a4e171ab61e5ff83028a4dd5b390fbb07c | [
"self.maxDiff = None\nindexer = Indexer()\nfor text in self.texts:\n text = text.strip()\n bag = BagOfWords(text, enable_stemming=False, filter_stopwords=False)\n indexer.index(bag)\nself.assertSequenceEqual(self.expected['docs_index'], indexer.docs_index)\nself.assertDictEqual(self.expected['words_index']... | <|body_start_0|>
self.maxDiff = None
indexer = Indexer()
for text in self.texts:
text = text.strip()
bag = BagOfWords(text, enable_stemming=False, filter_stopwords=False)
indexer.index(bag)
self.assertSequenceEqual(self.expected['docs_index'], indexer.... | Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf | TestIndexer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf... | stack_v2_sparse_classes_75kplus_train_007593 | 7,596 | permissive | [
{
"docstring": "Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf",
"name": "test_index_creation",
"signature": "def test_index_creation(self)"
},
{
"docstring": "Prueba los scores de una palabra ... | 3 | stack_v2_sparse_classes_30k_train_047996 | Implement the Python class `TestIndexer` described below.
Class description:
Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf
Method signatures and docstrings:
- def test_index_creation(self): Prueba la creación del indice Esta prueba usa el sigui... | Implement the Python class `TestIndexer` described below.
Class description:
Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf
Method signatures and docstrings:
- def test_index_creation(self): Prueba la creación del indice Esta prueba usa el sigui... | d3f24952cc0bd0f3f6ab7bae7428836511b3d67e | <|skeleton|>
class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestIndexer:
"""Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#Example_of_tf%E2%80%93idf"""
def test_index_creation(self):
"""Prueba la creación del indice Esta prueba usa el siguiente ejemplo como modelo https://en.wikipedia.org/wiki/Tf%E2%80%93idf#... | the_stack_v2_python_sparse | tfidf_index/TFIDF/tests.py | sankosk/SIW | train | 0 |
e209f379b7341a121a841b0c8a63b90365c113a9 | [
"self.path = path\nself.cf = ConfigParser.ConfigParser()\nself.cf.read(self.path)",
"try:\n result = self.cf.get(field, key)\nexcept:\n result = ''\nreturn result",
"try:\n self.cf.set(field, key, value)\n cf.write(open(self.path, 'w'))\nexcept:\n return False\nreturn True"
] | <|body_start_0|>
self.path = path
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.path)
<|end_body_0|>
<|body_start_1|>
try:
result = self.cf.get(field, key)
except:
result = ''
return result
<|end_body_1|>
<|body_start_2|>
try:
... | Config | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, path):
"""Config instance initialization."""
<|body_0|>
def get(self, field, key):
"""Get config value."""
<|body_1|>
def set(self, field, key, value):
"""Set config value."""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_007594 | 745 | permissive | [
{
"docstring": "Config instance initialization.",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Get config value.",
"name": "get",
"signature": "def get(self, field, key)"
},
{
"docstring": "Set config value.",
"name": "set",
"signature": ... | 3 | null | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, path): Config instance initialization.
- def get(self, field, key): Get config value.
- def set(self, field, key, value): Set config value. | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, path): Config instance initialization.
- def get(self, field, key): Get config value.
- def set(self, field, key, value): Set config value.
<|skeleton|>
class Con... | 46e79a9513d300182625c9a636e6d83e735f521c | <|skeleton|>
class Config:
def __init__(self, path):
"""Config instance initialization."""
<|body_0|>
def get(self, field, key):
"""Get config value."""
<|body_1|>
def set(self, field, key, value):
"""Set config value."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
def __init__(self, path):
"""Config instance initialization."""
self.path = path
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.path)
def get(self, field, key):
"""Get config value."""
try:
result = self.cf.get(field, key)
... | the_stack_v2_python_sparse | braincode/util/configParser.py | CASIANICA/brainCodingToolbox | train | 1 | |
ebe80767ea33ac0f78a5127e9a7a4a799da4957c | [
"self.data = list()\nself.data_len = 0\nself.start_idx = -1\nself.size = size\nself.average = None",
"self.data.append(val)\nself.data_len += 1\nprint(self.data_len, val, self.start_idx, self.size)\nif self.data_len <= self.size:\n if self.data_len == 1:\n self.average = self.data[0]\n else:\n ... | <|body_start_0|>
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
<|end_body_0|>
<|body_start_1|>
self.data.append(val)
self.data_len += 1
print(self.data_len, val, self.start_idx, self.size)
if self.da... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = list()
self.data_... | stack_v2_sparse_classes_75kplus_train_007595 | 1,298 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027663 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 5e48a72a20456d5c6ecbefe776a1c5e08d2c7e46 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.data = list()
self.data_len = 0
self.start_idx = -1
self.size = size
self.average = None
def next(self, val):
""":type val: int :rtype: float"""... | the_stack_v2_python_sparse | code_bases/python_coding_practice/moving_average.py | sgarg87/sahilgarg.github.io | train | 0 | |
5f36143ce6ac8912a92f1fc74193b40e0de86b37 | [
"raw_config = self.config.to_dict()\nraw_config.type = self.config.type\nmap_dict = LossMappingDict()\nself.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)\nself._cls = ClassFactory.get_cls(ClassType.LOSS, self.map_config.type)",
"params = se... | <|body_start_0|>
raw_config = self.config.to_dict()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_mapping_dict).backend_mapping(raw_config)
self._cls = ClassFactory.get_cls(ClassT... | Register and call loss class. | Loss | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
raw_config = self.config.to_dict()
raw_config.type = self.co... | stack_v2_sparse_classes_75kplus_train_007596 | 2,965 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call loss cls.",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040423 | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls. | Implement the Python class `Loss` described below.
Class description:
Register and call loss class.
Method signatures and docstrings:
- def __init__(self): Initialize.
- def __call__(self): Call loss cls.
<|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize.... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
<|body_0|>
def __call__(self):
"""Call loss cls."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Loss:
"""Register and call loss class."""
def __init__(self):
"""Initialize."""
raw_config = self.config.to_dict()
raw_config.type = self.config.type
map_dict = LossMappingDict()
self.map_config = ConfigBackendMapping(map_dict.type_mapping_dict, map_dict.params_map... | the_stack_v2_python_sparse | vega/modules/loss/loss.py | huawei-noah/vega | train | 850 |
3abf7081cf0de3d1ccf270926e286d92d80d0742 | [
"self.interp = interp\nself.limit_fun = limit_fun\nself.limit_grad = limit_grad\nself.grid_list = self.interp.grid_list\nself.upper_limits = np.array([x[-1] for x in self.grid_list])\nself.dim = len(self.grid_list)\nself.extrap_methods = {'decay_prop': self.extrap_decay_prop, 'decay_hark': self.extrap_decay_hark, '... | <|body_start_0|>
self.interp = interp
self.limit_fun = limit_fun
self.limit_grad = limit_grad
self.grid_list = self.interp.grid_list
self.upper_limits = np.array([x[-1] for x in self.grid_list])
self.dim = len(self.grid_list)
self.extrap_methods = {'decay_prop': s... | A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class. | DecayInterp | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecayInterp:
"""A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class."""
def __init__(self, interp, limit_fun, limit_grad=None, extrap_method='decay_prop'):
"""Parameters -----... | stack_v2_sparse_classes_75kplus_train_007597 | 12,737 | permissive | [
{
"docstring": "Parameters ---------- interp : N-dim LinearFast object Linear interpolator limit_fun : N-dim function Limiting function to be used when extrapolating limit_grad : function, optional Function that returns the gradient of the limiting function. Must follow the convention of LinearFast's gradients,... | 5 | stack_v2_sparse_classes_30k_train_003699 | Implement the Python class `DecayInterp` described below.
Class description:
A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class.
Method signatures and docstrings:
- def __init__(self, interp, limit_fun, limit... | Implement the Python class `DecayInterp` described below.
Class description:
A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class.
Method signatures and docstrings:
- def __init__(self, interp, limit_fun, limit... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class DecayInterp:
"""A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class."""
def __init__(self, interp, limit_fun, limit_grad=None, extrap_method='decay_prop'):
"""Parameters -----... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecayInterp:
"""A class of interpolators that use a limiting function for extrapolation. See HARK/examples/Interpolation/DecayInterp.ipynb for examples of how to use this class."""
def __init__(self, interp, limit_fun, limit_grad=None, extrap_method='decay_prop'):
"""Parameters ---------- interp ... | the_stack_v2_python_sparse | HARK/econforgeinterp.py | econ-ark/HARK | train | 315 |
de901e2e4b141fa03540b43024e16ab0f62b2fd1 | [
"self.grammar = grammar\nself.implicit_terminals = implicit_terminals or False\nself.implicit_non_terminals = implicit_non_terminals or False\nself.attribute_naming_scheme = attribute_naming_scheme or SnakeCase()\nself.class_naming_scheme = class_naming_scheme or Identity()\nself.type_field = class_identifier or 'n... | <|body_start_0|>
self.grammar = grammar
self.implicit_terminals = implicit_terminals or False
self.implicit_non_terminals = implicit_non_terminals or False
self.attribute_naming_scheme = attribute_naming_scheme or SnakeCase()
self.class_naming_scheme = class_naming_scheme or Iden... | Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This process is applied recursively to the dictionary entries. Dictionary entries will be ... | DictTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictTransformer:
"""Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This process is applied recursively to the dict... | stack_v2_sparse_classes_75kplus_train_007598 | 5,821 | permissive | [
{
"docstring": "Instantiate a new DictTransformer with given parameters. Parameters ---------- module Module defining the class definitions to use for instantiation. class_identifier Name of the class identifier field in the dictionaries. implicit_attributes If false, only explicitly declared attributes will be... | 4 | null | Implement the Python class `DictTransformer` described below.
Class description:
Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This pro... | Implement the Python class `DictTransformer` described below.
Class description:
Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This pro... | def1e30ba9198828d048fbba5fbb6cd27f7e1b04 | <|skeleton|>
class DictTransformer:
"""Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This process is applied recursively to the dict... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DictTransformer:
"""Transforms dicts into class-instance representations according to a given grammar. Transforms dicts to actual class instances when they define a "node type" entry that can be matched to a particular symbol of a specified grammar. This process is applied recursively to the dictionary entrie... | the_stack_v2_python_sparse | securify/grammar/transformer.py | readygo67/securify2 | train | 0 |
4686f6e5d567a321d2c44bd161d17808b55ca3c5 | [
"self.log = logging.getLogger('OpenPixelLED')\nself.opc_client = opc_client\nself.debug = debug\nself.channel = int(channel)\nself.led = int(led)\nself.opc_client.add_pixel(self.channel, self.led)",
"if self.debug:\n self.log.debug('Setting color: %s', color)\nself.opc_client.set_pixel_color(self.channel, self... | <|body_start_0|>
self.log = logging.getLogger('OpenPixelLED')
self.opc_client = opc_client
self.debug = debug
self.channel = int(channel)
self.led = int(led)
self.opc_client.add_pixel(self.channel, self.led)
<|end_body_0|>
<|body_start_1|>
if self.debug:
... | One LED on the openpixel platform. | OpenPixelLED | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenPixelLED:
"""One LED on the openpixel platform."""
def __init__(self, opc_client, channel, led, debug):
"""Initialise Openpixel LED obeject."""
<|body_0|>
def color(self, color):
"""Set color of the led. Args: color: color tuple"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_007599 | 7,154 | permissive | [
{
"docstring": "Initialise Openpixel LED obeject.",
"name": "__init__",
"signature": "def __init__(self, opc_client, channel, led, debug)"
},
{
"docstring": "Set color of the led. Args: color: color tuple",
"name": "color",
"signature": "def color(self, color)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000749 | Implement the Python class `OpenPixelLED` described below.
Class description:
One LED on the openpixel platform.
Method signatures and docstrings:
- def __init__(self, opc_client, channel, led, debug): Initialise Openpixel LED obeject.
- def color(self, color): Set color of the led. Args: color: color tuple | Implement the Python class `OpenPixelLED` described below.
Class description:
One LED on the openpixel platform.
Method signatures and docstrings:
- def __init__(self, opc_client, channel, led, debug): Initialise Openpixel LED obeject.
- def color(self, color): Set color of the led. Args: color: color tuple
<|skelet... | 00937ab2ff51b1dc668bf465282ffa8ff1eebbd8 | <|skeleton|>
class OpenPixelLED:
"""One LED on the openpixel platform."""
def __init__(self, opc_client, channel, led, debug):
"""Initialise Openpixel LED obeject."""
<|body_0|>
def color(self, color):
"""Set color of the led. Args: color: color tuple"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenPixelLED:
"""One LED on the openpixel platform."""
def __init__(self, opc_client, channel, led, debug):
"""Initialise Openpixel LED obeject."""
self.log = logging.getLogger('OpenPixelLED')
self.opc_client = opc_client
self.debug = debug
self.channel = int(chann... | the_stack_v2_python_sparse | mpf/platforms/openpixel.py | vgrillot/mpf | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.