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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cc5aadf6760cb4742b659bd859bd56a14e618ca5 | [
"init_dict = merge_args_kwargs_dict(args, kwargs)\nself._init = {}\nfor key, val in six.iteritems(init_dict):\n self._init.update({to_camel(key): val})\ntry:\n required = self.Meta.required\nexcept AttributeError:\n required = []\nfor field in required:\n if field not in self._init:\n raise Value... | <|body_start_0|>
init_dict = merge_args_kwargs_dict(args, kwargs)
self._init = {}
for key, val in six.iteritems(init_dict):
self._init.update({to_camel(key): val})
try:
required = self.Meta.required
except AttributeError:
required = []
... | Base class for all WoT data types represented as dictionaries in the Scripting API specification. | WotBaseDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WotBaseDict:
"""Base class for all WoT data types represented as dictionaries in the Scripting API specification."""
def __init__(self, *args, **kwargs):
"""Constructor. Will raise ValueError if there is some required field missing."""
<|body_0|>
def __getattr__(self, na... | stack_v2_sparse_classes_75kplus_train_008400 | 2,622 | permissive | [
{
"docstring": "Constructor. Will raise ValueError if there is some required field missing.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Transforms the field name to camelCase and attemps to retrieve it from the internal dict.",
"name": "__getat... | 3 | null | Implement the Python class `WotBaseDict` described below.
Class description:
Base class for all WoT data types represented as dictionaries in the Scripting API specification.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor. Will raise ValueError if there is some required field mis... | Implement the Python class `WotBaseDict` described below.
Class description:
Base class for all WoT data types represented as dictionaries in the Scripting API specification.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor. Will raise ValueError if there is some required field mis... | ab14570927ccb1fcda5e7ffc415fda3c1ef2d00d | <|skeleton|>
class WotBaseDict:
"""Base class for all WoT data types represented as dictionaries in the Scripting API specification."""
def __init__(self, *args, **kwargs):
"""Constructor. Will raise ValueError if there is some required field missing."""
<|body_0|>
def __getattr__(self, na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WotBaseDict:
"""Base class for all WoT data types represented as dictionaries in the Scripting API specification."""
def __init__(self, *args, **kwargs):
"""Constructor. Will raise ValueError if there is some required field missing."""
init_dict = merge_args_kwargs_dict(args, kwargs)
... | the_stack_v2_python_sparse | wotpy/wot/dictionaries/base.py | agmangas/wot-py | train | 34 |
8684ca0578bc54040497a2064a6e4de06ab20292 | [
"loss = sum([0.5 * (y[i] - X[i].dot(w)) ** 2 for i in range(len(y))]) / y.shape[0]\nif self.regularization is not None:\n loss = loss + self.regularization.forward(w)\nreturn loss",
"gradient = -X.T.dot(y - X.dot(w)) / y.shape[0]\nif self.regularization is not None:\n gradient = gradient + self.regularizati... | <|body_start_0|>
loss = sum([0.5 * (y[i] - X[i].dot(w)) ** 2 for i in range(len(y))]) / y.shape[0]
if self.regularization is not None:
loss = loss + self.regularization.forward(w)
return loss
<|end_body_0|>
<|body_start_1|>
gradient = -X.T.dot(y - X.dot(w)) / y.shape[0]
... | The squared loss function. | SquaredLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SquaredLoss:
"""The squared loss function."""
def forward(self, X, w, y):
"""Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the loss. The squared loss for a single example is given as f... | stack_v2_sparse_classes_75kplus_train_008401 | 9,968 | permissive | [
{
"docstring": "Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the loss. The squared loss for a single example is given as follows: L_s(x, y; w) = (1/2) (y - w^T x)^2 The squared loss over a dataset of N points is... | 2 | null | Implement the Python class `SquaredLoss` described below.
Class description:
The squared loss function.
Method signatures and docstrings:
- def forward(self, X, w, y): Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the ... | Implement the Python class `SquaredLoss` described below.
Class description:
The squared loss function.
Method signatures and docstrings:
- def forward(self, X, w, y): Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the ... | aad5ff878a6d7d74d2bb73078e53520317ca3ad3 | <|skeleton|>
class SquaredLoss:
"""The squared loss function."""
def forward(self, X, w, y):
"""Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the loss. The squared loss for a single example is given as f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SquaredLoss:
"""The squared loss function."""
def forward(self, X, w, y):
"""Computes the forward pass through the loss function. If self.regularization is not None, also adds the forward pass of the regularization term to the loss. The squared loss for a single example is given as follows: L_s(x... | the_stack_v2_python_sparse | Gradient_Descent/your_code/loss.py | YaelBenShalom/Machine-Learning | train | 0 |
b9cc3c939efb3892e7fd9018ebecfaeda662dc62 | [
"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... | Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of people of specified demographics that can be reached by an ad in a given market by a campai... | ReachPlanServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReachPlanServiceServicer:
"""Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of people of specified demographics that c... | stack_v2_sparse_classes_75kplus_train_008402 | 6,480 | permissive | [
{
"docstring": "Returns the list of plannable locations (for example, countries & DMAs).",
"name": "ListPlannableLocations",
"signature": "def ListPlannableLocations(self, request, context)"
},
{
"docstring": "Returns the list of per-location plannable YouTube ad formats with allowed targeting."... | 4 | stack_v2_sparse_classes_30k_train_045836 | Implement the Python class `ReachPlanServiceServicer` described below.
Class description:
Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of ... | Implement the Python class `ReachPlanServiceServicer` described below.
Class description:
Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of ... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class ReachPlanServiceServicer:
"""Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of people of specified demographics that c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReachPlanServiceServicer:
"""Proto file describing the reach plan service. Reach Plan Service gives users information about audience size that can be reached through advertisement on YouTube. In particular, GenerateReachForecast provides estimated number of people of specified demographics that can be reached... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/reach_plan_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
e7d8d48120132bdefc07190b034293a5679ccd84 | [
"super(FiniteGroup, self).__init__(baseset, unity, op, inv, op2, properties)\nif 'grouporder' in self.properties:\n self.grouporder = self.properties['grouporder']\nself._orderfactor = None",
"assert hasattr(self, grouporder), 'tell me the group order!'\nif elem not in self:\n raise ValueError('%s is not in... | <|body_start_0|>
super(FiniteGroup, self).__init__(baseset, unity, op, inv, op2, properties)
if 'grouporder' in self.properties:
self.grouporder = self.properties['grouporder']
self._orderfactor = None
<|end_body_0|>
<|body_start_1|>
assert hasattr(self, grouporder), 'tell m... | Declarative finite group class. | FiniteGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FiniteGroup:
"""Declarative finite group class."""
def __init__(self, baseset, unity, op, inv, op2, properties):
"""FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation 'op', the inverse function 'inv' and identity element 'uni... | stack_v2_sparse_classes_75kplus_train_008403 | 5,309 | no_license | [
{
"docstring": "FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation 'op', the inverse function 'inv' and identity element 'unity'. The argument 'op2' is a shorthand of natural action of integers. Another argument 'properties' is a property dictionary. It... | 2 | stack_v2_sparse_classes_30k_train_011093 | Implement the Python class `FiniteGroup` described below.
Class description:
Declarative finite group class.
Method signatures and docstrings:
- def __init__(self, baseset, unity, op, inv, op2, properties): FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation '... | Implement the Python class `FiniteGroup` described below.
Class description:
Declarative finite group class.
Method signatures and docstrings:
- def __init__(self, baseset, unity, op, inv, op2, properties): FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation '... | a48ae9efcf0d9ad1485c2e9863c948a7f1b20311 | <|skeleton|>
class FiniteGroup:
"""Declarative finite group class."""
def __init__(self, baseset, unity, op, inv, op2, properties):
"""FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation 'op', the inverse function 'inv' and identity element 'uni... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FiniteGroup:
"""Declarative finite group class."""
def __init__(self, baseset, unity, op, inv, op2, properties):
"""FiniteGroup(baseset, unity, op, op2, properties) A 'baseset' is declared as a finite group with the operation 'op', the inverse function 'inv' and identity element 'unity'. The argu... | the_stack_v2_python_sparse | sandbox/declarativegroup.py | turkeydonkey/nzmath3 | train | 2 |
2776da0103308f0cb0ce56f8cc63315f85020989 | [
"super(CNN_Text, self).__init__()\nself.args = args\nembed_dim = args.embed_dim\nkernel_num = args.kernel_num\nkernel_sizes = args.kernel_sizes\nembed_num = args.embed_num\nclass_num = args.class_num\nself.embed = nn.Embedding(embed_num, embed_dim)\nself.convs1 = nn.ModuleList([nn.Conv2d(1, kernel_num, (kernel_size... | <|body_start_0|>
super(CNN_Text, self).__init__()
self.args = args
embed_dim = args.embed_dim
kernel_num = args.kernel_num
kernel_sizes = args.kernel_sizes
embed_num = args.embed_num
class_num = args.class_num
self.embed = nn.Embedding(embed_num, embed_dim... | CNN_Text | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
<|body_0|>
def forward(self, x):
"""Your code here. Give the forward pass of the model. With multiple k... | stack_v2_sparse_classes_75kplus_train_008404 | 1,541 | no_license | [
{
"docstring": "Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Your code here. Give the forward pass of the model. With multiple kernel size... | 2 | stack_v2_sparse_classes_30k_train_052159 | Implement the Python class `CNN_Text` described below.
Class description:
Implement the CNN_Text class.
Method signatures and docstrings:
- def __init__(self, args): Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.
- def forward(self, x): Your c... | Implement the Python class `CNN_Text` described below.
Class description:
Implement the CNN_Text class.
Method signatures and docstrings:
- def __init__(self, args): Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.
- def forward(self, x): Your c... | f1af0599ac8c3c8be4852472838dca775a22aa53 | <|skeleton|>
class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
<|body_0|>
def forward(self, x):
"""Your code here. Give the forward pass of the model. With multiple k... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
super(CNN_Text, self).__init__()
self.args = args
embed_dim = args.embed_dim
kernel_num = args.kernel_num
... | the_stack_v2_python_sparse | homework5/Lv_Xinpeng/model.py | Lukeming-tsinghua/pytorch-NLP-guidance | train | 12 | |
4cd4203af612c4f2688395919f70e2a827d9fe76 | [
"if source is None:\n raise ValueError('source cannot be empty')\nself.allowed = load_passwords(source)\nself.algo = algo\nself.auth_header_prefix = 'Basic'",
"if not auth_header:\n raise falcon.HTTPUnauthorized(title='401 Unauthorized', description='Missing Authorization Header')\nparts = auth_header.split... | <|body_start_0|>
if source is None:
raise ValueError('source cannot be empty')
self.allowed = load_passwords(source)
self.algo = algo
self.auth_header_prefix = 'Basic'
<|end_body_0|>
<|body_start_1|>
if not auth_header:
raise falcon.HTTPUnauthorized(title... | Authentification. The name and secret comes from a file. The file must store encrypted password. | AuthMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
... | stack_v2_sparse_classes_75kplus_train_008405 | 3,541 | permissive | [
{
"docstring": "@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords",
"name": "__init__",
"signature": "def __init__(self, source, algo='sha224')"
},
{
"docstring": "Parses and returns Auth token from the request header. Raises `falcon.HTTP... | 4 | stack_v2_sparse_classes_30k_train_000641 | Implement the Python class `AuthMiddleware` described below.
Class description:
Authentification. The name and secret comes from a file. The file must store encrypted password.
Method signatures and docstrings:
- def __init__(self, source, algo='sha224'): @param source filename or dataframe for encrypted password @pa... | Implement the Python class `AuthMiddleware` described below.
Class description:
Authentification. The name and secret comes from a file. The file must store encrypted password.
Method signatures and docstrings:
- def __init__(self, source, algo='sha224'): @param source filename or dataframe for encrypted password @pa... | def172965eb197d8ab7f812c3f5f5ce129593cef | <|skeleton|>
class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
if source is ... | the_stack_v2_python_sparse | src/lightmlrestapi/mlapp/authfiction.py | sdpython/lightmlrestapi | train | 0 |
86c7a1aeeb13f4a3527cb6a2b3ac757a1b9f78dd | [
"n_samples, n_features = X.shape\nself.classes = np.unique(y)\nn_classes = len(self.classes)\nself.phi = np.zeros((n_classes, 1))\nself.means = np.zeros((n_classes, n_features))\nself.sigma = 0\nfor i in range(n_classes):\n indexes = np.flatnonzero(y == self.classes[i])\n self.phi[i] = len(indexes) / n_sample... | <|body_start_0|>
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
self.means = np.zeros((n_classes, n_features))
self.sigma = 0
for i in range(n_classes):
indexes = np.flatnon... | GDA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_75kplus_train_008406 | 1,310 | permissive | [
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels",
"name": "fit",
"signature": "def fit(self, X, y)"
},
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : shape (n_s... | 2 | stack_v2_sparse_classes_30k_train_019867 | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | 7034798a5f0b92c6b8fdfa5948d2ad78a77a1a05 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
... | the_stack_v2_python_sparse | 7. Machine Learning/gaussian_discriminant_analysis.py | Nhiemth1985/Pynaissance | train | 0 | |
20a5a400a07bca00fa139aaa674f9ae90529efe5 | [
"self.logger_id = ''\nself.path_to_files = ''\nself.filenames = []\nself.file_format = ''\nself.first_col_data = ''\nself.delim = ''\nself.datetime_format = ''\nself.header_rows = 0\nself.skip_rows = []\nself.channel_names = []\nself.channel_units = []\nself.set_logger(logger)",
"self.logger_id = logger.logger_id... | <|body_start_0|>
self.logger_id = ''
self.path_to_files = ''
self.filenames = []
self.file_format = ''
self.first_col_data = ''
self.delim = ''
self.datetime_format = ''
self.header_rows = 0
self.skip_rows = []
self.channel_names = []
... | RawDataRead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
<|body_0|>
def set_logger(self, logger):
"""Set the logger filenames and required rea... | stack_v2_sparse_classes_75kplus_train_008407 | 11,699 | no_license | [
{
"docstring": "Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance",
"name": "__init__",
"signature": "def __init__(self, logger=LoggerProperties())"
},
{
"docstring": "Set the logger filenames and required read file properties.",
... | 4 | stack_v2_sparse_classes_30k_train_042834 | Implement the Python class `RawDataRead` described below.
Class description:
Implement the RawDataRead class.
Method signatures and docstrings:
- def __init__(self, logger=LoggerProperties()): Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance
- def set... | Implement the Python class `RawDataRead` described below.
Class description:
Implement the RawDataRead class.
Method signatures and docstrings:
- def __init__(self, logger=LoggerProperties()): Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance
- def set... | 78cae181f85a3cd2b6b6c1f1a57f62bbe5fbbda4 | <|skeleton|>
class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
<|body_0|>
def set_logger(self, logger):
"""Set the logger filenames and required rea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
self.logger_id = ''
self.path_to_files = ''
self.filenames = []
self.file_format = ''
... | the_stack_v2_python_sparse | src/main/python/core/raw_data_plot_properties.py | craigdickinson/DataLab | train | 1 | |
8e73fe7b8dd0aceaaa4c0739085c488d2649a286 | [
"new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))\nnew_category.save()\nreturn new_category",
"instance.name = validated_data.get('name', instance.name)\ninstance.car = validated_data.get('car', instance.car)\ninstance.save()\nreturn instance"
] | <|body_start_0|>
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.name)
instance.car = validated_data.g... | SpecificationCategorySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_75kplus_train_008408 | 6,342 | no_license | [
{
"docstring": "create and return new 'SpecificationCategory' instance",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `SpecificationCategory` instance",
"name": "update",
"signature": "def update(self, instance, valida... | 2 | stack_v2_sparse_classes_30k_train_035748 | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | Implement the Python class `SpecificationCategorySerializer` described below.
Class description:
Implement the SpecificationCategorySerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'SpecificationCategory' instance
- def update(self, instance, validated_data... | dba8d1fdb96889e41328e792816a4968cbeb1ed4 | <|skeleton|>
class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `SpecificationCategory` instance"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecificationCategorySerializer:
def create(self, validated_data):
"""create and return new 'SpecificationCategory' instance"""
new_category = SpecificationCategory(name=validated_data.get('name'), car=validated_data.get('car'))
new_category.save()
return new_category
def ... | the_stack_v2_python_sparse | cars_web/cars_app/serializers.py | Ignisor/cars_scrapper | train | 0 | |
f8b79ee7eaa24fb4f8019d428ddf914a6aed4484 | [
"header_parser = ParserDef(end_marker=lambda line, _ln, nextline: line[0:8] == ' Summary', label=lambda line, _ln: line[1:19], parser_def={'Solution refers to': {'parser': self._parse_time, 'fields': {'year': (26, 30), 'month': (31, 33), 'day': (34, 36), 'hours': (37, 39), 'minutes': (40, 42), 'decimaldate': (47, 5... | <|body_start_0|>
header_parser = ParserDef(end_marker=lambda line, _ln, nextline: line[0:8] == ' Summary', label=lambda line, _ln: line[1:19], parser_def={'Solution refers to': {'parser': self._parse_time, 'fields': {'year': (26, 30), 'month': (31, 33), 'day': (34, 36), 'hours': (37, 39), 'minutes': (40, 42), '... | A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the parser (as needed to call parsers.parse_...). system (String): GNSS identifier. Met... | GamitOrgParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GamitOrgParser:
"""A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the parser (as needed to call parsers.parse_.... | stack_v2_sparse_classes_75kplus_train_008409 | 7,461 | permissive | [
{
"docstring": "Parser defined for reading .org file line by line First the header information are read and afterwards the data block.",
"name": "setup_parser",
"signature": "def setup_parser(self) -> Iterable[ParserDef]"
},
{
"docstring": "Parse a line with station coordinates, and add a dictio... | 4 | stack_v2_sparse_classes_30k_train_042475 | Implement the Python class `GamitOrgParser` described below.
Class description:
A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the pa... | Implement the Python class `GamitOrgParser` described below.
Class description:
A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the pa... | 31939afee943273b23fa0a5ef193cfecfa68d6c0 | <|skeleton|>
class GamitOrgParser:
"""A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the parser (as needed to call parsers.parse_.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GamitOrgParser:
"""A parser for reading gamit org file Attributes: data (Dict): The (observation) data read from file. file_path (Path): Path to the datafile that will be read. meta (Dict): Metainformation read from file. parser_name (String): Name of the parser (as needed to call parsers.parse_...). system (... | the_stack_v2_python_sparse | midgard/parsers/gamit_org.py | kartverket/midgard | train | 18 |
e295d5f0cdad55195150c6f0cff1042453777252 | [
"self.contents = kwargs if kwargs else self.default\ntry:\n self.contents.update(self._get_from_settings(settings=project.settings))\nexcept AttributeError:\n pass\nfor item in self.required:\n if item not in self.contents:\n self.contents[item] = self.default[item]\nif self.runtime:\n self.add_r... | <|body_start_0|>
self.contents = kwargs if kwargs else self.default
try:
self.contents.update(self._get_from_settings(settings=project.settings))
except AttributeError:
pass
for item in self.required:
if item not in self.contents:
self.... | Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with '**', which will turn the 'contents' attribute an ordinary set of kwargs. In... | Parameters | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameters:
"""Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with '**', which will turn the 'contents' a... | stack_v2_sparse_classes_75kplus_train_008410 | 32,679 | permissive | [
{
"docstring": "[summary] Args: name (str): project (sourdough.Project):",
"name": "finalize",
"signature": "def finalize(self, project: sourdough.Project, **kwargs) -> None"
},
{
"docstring": "[summary] Args: project (sourdough.Project):",
"name": "_add_runtime",
"signature": "def _add_... | 3 | stack_v2_sparse_classes_30k_train_046114 | Implement the Python class `Parameters` described below.
Class description:
Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with... | Implement the Python class `Parameters` described below.
Class description:
Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with... | 5302da8bf4944ac518d22cc37c181e5a09baaabe | <|skeleton|>
class Parameters:
"""Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with '**', which will turn the 'contents' a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parameters:
"""Creates and stores parameters for a siMpLify component. Parameters allows parameters to be drawn from several different sources, including those which only become apparent during execution of a siMpLify project. Parameters can be unpacked with '**', which will turn the 'contents' attribute an o... | the_stack_v2_python_sparse | simplify/core/components.py | WithPrecedent/simplify | train | 1 |
a0777a7f04a6eceb6258f7cb8b1c1d4cd078e27e | [
"m = len(nums)\nfor i in range(m - 1, -1, -1):\n for j in range(i):\n if nums[j] > nums[j + 1]:\n nums[j], nums[j + 1] = (nums[j + 1], nums[j])",
"m = len(nums)\nfor i in range(m - 1, -1, -1):\n is_sorted = True\n for j in range(i):\n if nums[j] > nums[j + 1]:\n nums[j... | <|body_start_0|>
m = len(nums)
for i in range(m - 1, -1, -1):
for j in range(i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = (nums[j + 1], nums[j])
<|end_body_0|>
<|body_start_1|>
m = len(nums)
for i in range(m - 1, -1, -1):
... | 冒泡排序 | Bubble_sort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bubble_sort:
"""冒泡排序"""
def sort(self, nums):
"""标准版冒泡排序 :type nums: List[int] 要排序的数组"""
<|body_0|>
def sort_optimize(self, nums):
"""优化版冒泡排序 :type nums: List[int] 要排序的数组"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(nums)
for ... | stack_v2_sparse_classes_75kplus_train_008411 | 815 | no_license | [
{
"docstring": "标准版冒泡排序 :type nums: List[int] 要排序的数组",
"name": "sort",
"signature": "def sort(self, nums)"
},
{
"docstring": "优化版冒泡排序 :type nums: List[int] 要排序的数组",
"name": "sort_optimize",
"signature": "def sort_optimize(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005024 | Implement the Python class `Bubble_sort` described below.
Class description:
冒泡排序
Method signatures and docstrings:
- def sort(self, nums): 标准版冒泡排序 :type nums: List[int] 要排序的数组
- def sort_optimize(self, nums): 优化版冒泡排序 :type nums: List[int] 要排序的数组 | Implement the Python class `Bubble_sort` described below.
Class description:
冒泡排序
Method signatures and docstrings:
- def sort(self, nums): 标准版冒泡排序 :type nums: List[int] 要排序的数组
- def sort_optimize(self, nums): 优化版冒泡排序 :type nums: List[int] 要排序的数组
<|skeleton|>
class Bubble_sort:
"""冒泡排序"""
def sort(self, num... | 0b3bc77cbfe0e45e62c3c8f244e9e3d2421e6121 | <|skeleton|>
class Bubble_sort:
"""冒泡排序"""
def sort(self, nums):
"""标准版冒泡排序 :type nums: List[int] 要排序的数组"""
<|body_0|>
def sort_optimize(self, nums):
"""优化版冒泡排序 :type nums: List[int] 要排序的数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bubble_sort:
"""冒泡排序"""
def sort(self, nums):
"""标准版冒泡排序 :type nums: List[int] 要排序的数组"""
m = len(nums)
for i in range(m - 1, -1, -1):
for j in range(i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = (nums[j + 1], nums[j])
def... | the_stack_v2_python_sparse | sort/bubble_sort.py | lailianqi/LeetCodeByPython | train | 0 |
647531baedec27e1c5d233ee471394458dbe6eeb | [
"points = []\nfor interval in intervals:\n points.append((interval.start, 1))\n points.append((interval.end, -1))\nmeeting_rooms = 0\nongoing_meetings = 0\nfor _, delta in sorted(points):\n ongoing_meetings += delta\n meeting_rooms = max(meeting_rooms, ongoing_meetings)\nreturn meeting_rooms",
"if len... | <|body_start_0|>
points = []
for interval in intervals:
points.append((interval.start, 1))
points.append((interval.end, -1))
meeting_rooms = 0
ongoing_meetings = 0
for _, delta in sorted(points):
ongoing_meetings += delta
meeting_ro... | @param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required"""
def minMeetingRooms(self, intervals):
"""version1,brutal force"""
<|body_0|>
def minMeetingRooms(self, intervals):
"""first sort by the s... | stack_v2_sparse_classes_75kplus_train_008412 | 1,410 | no_license | [
{
"docstring": "version1,brutal force",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals)"
},
{
"docstring": "first sort by the start time then maintain the min_heap of the end time",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals... | 2 | stack_v2_sparse_classes_30k_train_009244 | Implement the Python class `Solution` described below.
Class description:
@param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): version1,brutal force
- def minMeetingRooms(self, intervals)... | Implement the Python class `Solution` described below.
Class description:
@param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): version1,brutal force
- def minMeetingRooms(self, intervals)... | fb4fb493d943d8ab49c63f334623c9717b712fdd | <|skeleton|>
class Solution:
"""@param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required"""
def minMeetingRooms(self, intervals):
"""version1,brutal force"""
<|body_0|>
def minMeetingRooms(self, intervals):
"""first sort by the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""@param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required"""
def minMeetingRooms(self, intervals):
"""version1,brutal force"""
points = []
for interval in intervals:
points.append((interval.start, 1))
... | the_stack_v2_python_sparse | meeting_room2.py | sherlockhoatszx/code_algorithm | train | 0 |
2d384450d5a33a853fe96e92d2d52cffddce7145 | [
"if model._meta.app_label == 'kb':\n return 'kbase'\nreturn None",
"if model._meta.app_label == 'kb':\n return 'kbase'\nreturn None",
"if app_label == 'kb':\n return db == 'kbase'\nreturn None"
] | <|body_start_0|>
if model._meta.app_label == 'kb':
return 'kbase'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'kb':
return 'kbase'
return None
<|end_body_1|>
<|body_start_2|>
if app_label == 'kb':
return db == 'kba... | A router to control all database operations on models in the auth application. | KbRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth mo... | stack_v2_sparse_classes_75kplus_train_008413 | 1,612 | no_license | [
{
"docstring": "Attempts to read auth models go to auth_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
... | 3 | stack_v2_sparse_classes_30k_train_053343 | Implement the Python class `KbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): Atte... | Implement the Python class `KbRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): Atte... | ecdc27ec46ed0f25f20c1bfe95632204c821f738 | <|skeleton|>
class KbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KbRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
if model._meta.app_label == 'kb':
return 'kbase'
return None
def db_for_write(se... | the_stack_v2_python_sparse | homados/homados/contrib/dbrouters.py | cleanmgr112/MetasploitCoop-Backend | train | 0 |
235dced05a1b535cf271e0dceec709df3a2a1c21 | [
"response = self.client.get('/plugin/sample/ho/he/')\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.content, b'Hi there testuser this works')",
"plugin = registry.get_plugin('sample')\nself.assertIsNotNone(plugin)\nself.assertEqual(plugin.check_settings(), (False, ['API_KEY']))\nplugin.se... | <|body_start_0|>
response = self.client.get('/plugin/sample/ho/he/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'Hi there testuser this works')
<|end_body_0|>
<|body_start_1|>
plugin = registry.get_plugin('sample')
self.assertIsNotNone(plugin... | Tests for SampleIntegrationPlugin. | SampleIntegrationPluginTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleIntegrationPluginTests:
"""Tests for SampleIntegrationPlugin."""
def test_view(self):
"""Check the function of the custom sample plugin."""
<|body_0|>
def test_settings(self):
"""Check the SettingsMixin.check_settings function."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_008414 | 889 | permissive | [
{
"docstring": "Check the function of the custom sample plugin.",
"name": "test_view",
"signature": "def test_view(self)"
},
{
"docstring": "Check the SettingsMixin.check_settings function.",
"name": "test_settings",
"signature": "def test_settings(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001672 | Implement the Python class `SampleIntegrationPluginTests` described below.
Class description:
Tests for SampleIntegrationPlugin.
Method signatures and docstrings:
- def test_view(self): Check the function of the custom sample plugin.
- def test_settings(self): Check the SettingsMixin.check_settings function. | Implement the Python class `SampleIntegrationPluginTests` described below.
Class description:
Tests for SampleIntegrationPlugin.
Method signatures and docstrings:
- def test_view(self): Check the function of the custom sample plugin.
- def test_settings(self): Check the SettingsMixin.check_settings function.
<|skele... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class SampleIntegrationPluginTests:
"""Tests for SampleIntegrationPlugin."""
def test_view(self):
"""Check the function of the custom sample plugin."""
<|body_0|>
def test_settings(self):
"""Check the SettingsMixin.check_settings function."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleIntegrationPluginTests:
"""Tests for SampleIntegrationPlugin."""
def test_view(self):
"""Check the function of the custom sample plugin."""
response = self.client.get('/plugin/sample/ho/he/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.conte... | the_stack_v2_python_sparse | InvenTree/plugin/samples/integration/test_sample.py | inventree/InvenTree | train | 3,077 |
f1bebd4caa1c710b473f25faca2215545b05e2f6 | [
"assert isinstance(scheme, str), 'Invalid scheme %s' % scheme\nself._processing = assembly.create(request=RequestHTTP, requestCnt=RequestContentHTTP, response=ResponseHTTP, responseCnt=ResponseContentHTTP)\nself._scheme = scheme",
"assert isinstance(uri, str), 'Invalid URI %s' % uri\nproc = self._processing\nasse... | <|body_start_0|>
assert isinstance(scheme, str), 'Invalid scheme %s' % scheme
self._processing = assembly.create(request=RequestHTTP, requestCnt=RequestContentHTTP, response=ResponseHTTP, responseCnt=ResponseContentHTTP)
self._scheme = scheme
<|end_body_0|>
<|body_start_1|>
assert isins... | Makes OPTIONS headers requests. | RequesterOptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequesterOptions:
"""Makes OPTIONS headers requests."""
def __init__(self, assembly, scheme=HTTP):
"""Create the options request handler. @param assembly: Assembly The assembly used for delivering the request."""
<|body_0|>
def request(self, uri):
"""Request the ... | stack_v2_sparse_classes_75kplus_train_008415 | 7,963 | no_license | [
{
"docstring": "Create the options request handler. @param assembly: Assembly The assembly used for delivering the request.",
"name": "__init__",
"signature": "def __init__(self, assembly, scheme=HTTP)"
},
{
"docstring": "Request the OPTIONS headers for URI. @param uri: string The URI to call, p... | 2 | stack_v2_sparse_classes_30k_train_001603 | Implement the Python class `RequesterOptions` described below.
Class description:
Makes OPTIONS headers requests.
Method signatures and docstrings:
- def __init__(self, assembly, scheme=HTTP): Create the options request handler. @param assembly: Assembly The assembly used for delivering the request.
- def request(sel... | Implement the Python class `RequesterOptions` described below.
Class description:
Makes OPTIONS headers requests.
Method signatures and docstrings:
- def __init__(self, assembly, scheme=HTTP): Create the options request handler. @param assembly: Assembly The assembly used for delivering the request.
- def request(sel... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class RequesterOptions:
"""Makes OPTIONS headers requests."""
def __init__(self, assembly, scheme=HTTP):
"""Create the options request handler. @param assembly: Assembly The assembly used for delivering the request."""
<|body_0|>
def request(self, uri):
"""Request the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequesterOptions:
"""Makes OPTIONS headers requests."""
def __init__(self, assembly, scheme=HTTP):
"""Create the options request handler. @param assembly: Assembly The assembly used for delivering the request."""
assert isinstance(scheme, str), 'Invalid scheme %s' % scheme
self._p... | the_stack_v2_python_sparse | components/ally-http/ally/support/http/request.py | cristidomsa/Ally-Py | train | 0 |
be8a74ec0d93c988a2af0a2a437c1325fa31d111 | [
"self.min_ = min_\nself.max_ = max_\nself.clamp = clamp",
"try:\n val = int(argument)\n if val > self.max_ or val < self.min_:\n if not self.clamp:\n raise commands.UserInputError(f'Argument should be within **{self.min_:,} - {self.max_:,}**')\n val = max(min(val, self.max_), self.m... | <|body_start_0|>
self.min_ = min_
self.max_ = max_
self.clamp = clamp
<|end_body_0|>
<|body_start_1|>
try:
val = int(argument)
if val > self.max_ or val < self.min_:
if not self.clamp:
raise commands.UserInputError(f'Argument s... | Range | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Range:
def __init__(self, min_: int, max_: int, *, clamp: bool=False):
""":param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)"""
<|body_0|>
async def convert(self, ctx: commands.Context, argument: str) -> int:
""":param ctx: ... | stack_v2_sparse_classes_75kplus_train_008416 | 2,395 | permissive | [
{
"docstring": ":param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)",
"name": "__init__",
"signature": "def __init__(self, min_: int, max_: int, *, clamp: bool=False)"
},
{
"docstring": ":param ctx: The context which the command was called from :param ar... | 2 | null | Implement the Python class `Range` described below.
Class description:
Implement the Range class.
Method signatures and docstrings:
- def __init__(self, min_: int, max_: int, *, clamp: bool=False): :param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)
- async def convert(self, ... | Implement the Python class `Range` described below.
Class description:
Implement the Range class.
Method signatures and docstrings:
- def __init__(self, min_: int, max_: int, *, clamp: bool=False): :param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)
- async def convert(self, ... | 373bbd1640078fe2b225200941c8e657c64389c1 | <|skeleton|>
class Range:
def __init__(self, min_: int, max_: int, *, clamp: bool=False):
""":param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)"""
<|body_0|>
async def convert(self, ctx: commands.Context, argument: str) -> int:
""":param ctx: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Range:
def __init__(self, min_: int, max_: int, *, clamp: bool=False):
""":param min_: Minimum value allowed (inclusive) :param max_: Maximum value allowed (inclusive)"""
self.min_ = min_
self.max_ = max_
self.clamp = clamp
async def convert(self, ctx: commands.Context, ar... | the_stack_v2_python_sparse | legacy/common/converters.py | aaryan-sarawgi1/discord-snacc-bot | train | 0 | |
bddf66b06d0e65e8991080e2edc93954d5789cb8 | [
"NUM_COVARS = initial_guess.shape[1]\ncandidates_array = np.random.uniform(low=covar_bounds[0, :].numpy(), high=covar_bounds[1, :].numpy(), size=(n_samp, NUM_COVARS))\ncandidates = torch.from_numpy(candidates_array).double().to(device)\nreturn candidates",
"NUM_COVARS = initial_guess.shape[1]\nbins = np.zeros((n_... | <|body_start_0|>
NUM_COVARS = initial_guess.shape[1]
candidates_array = np.random.uniform(low=covar_bounds[0, :].numpy(), high=covar_bounds[1, :].numpy(), size=(n_samp, NUM_COVARS))
candidates = torch.from_numpy(candidates_array).double().to(device)
return candidates
<|end_body_0|>
<|bo... | class of sample methods (random and structured random) used for initialization and for interdispersed random sampling | DataSamplers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSamplers:
"""class of sample methods (random and structured random) used for initialization and for interdispersed random sampling"""
def random(n_samp, initial_guess, covar_bounds, device):
"""randomly samples each covariate within bounds to provice new candidate datapoint :para... | stack_v2_sparse_classes_75kplus_train_008417 | 10,583 | permissive | [
{
"docstring": "randomly samples each covariate within bounds to provice new candidate datapoint :param n_samp (int): number of samples to be generated. Defines number of subsegments for each covariate, from which each new candidate datapoint are obtained :param initial_guess (tensor, 1 X <num covariates>): con... | 2 | stack_v2_sparse_classes_30k_train_050593 | Implement the Python class `DataSamplers` described below.
Class description:
class of sample methods (random and structured random) used for initialization and for interdispersed random sampling
Method signatures and docstrings:
- def random(n_samp, initial_guess, covar_bounds, device): randomly samples each covaria... | Implement the Python class `DataSamplers` described below.
Class description:
class of sample methods (random and structured random) used for initialization and for interdispersed random sampling
Method signatures and docstrings:
- def random(n_samp, initial_guess, covar_bounds, device): randomly samples each covaria... | e241d0f6a30479b600d85aafabf27058d3fd1072 | <|skeleton|>
class DataSamplers:
"""class of sample methods (random and structured random) used for initialization and for interdispersed random sampling"""
def random(n_samp, initial_guess, covar_bounds, device):
"""randomly samples each covariate within bounds to provice new candidate datapoint :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSamplers:
"""class of sample methods (random and structured random) used for initialization and for interdispersed random sampling"""
def random(n_samp, initial_guess, covar_bounds, device):
"""randomly samples each covariate within bounds to provice new candidate datapoint :param n_samp (int... | the_stack_v2_python_sparse | greattunes/utils.py | minlattnwe/greattunes | train | 0 |
837d50ce6b70c7a658468a4dec770af8c581626b | [
"self.path = path\nself.back = os.path.dirname(path)\nself.dirs = sorted((i for i in image_paths if i.is_dir))\nself.files = sorted((i for i in image_paths if i.is_image))",
"def _split(path, data):\n name = os.path.basename(path)\n if name:\n second = os.path.dirname(path)\n data = _split(sec... | <|body_start_0|>
self.path = path
self.back = os.path.dirname(path)
self.dirs = sorted((i for i in image_paths if i.is_dir))
self.files = sorted((i for i in image_paths if i.is_image))
<|end_body_0|>
<|body_start_1|>
def _split(path, data):
name = os.path.basename(pa... | Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files` | ImageFolder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageFolder:
"""Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files`"""
def __init__(self, path, image_paths):
""":type path: str :type image_paths: list of bviewer.core.files.path.ImagePath"""
<|body_0|>
def split_path(self):
"... | stack_v2_sparse_classes_75kplus_train_008418 | 1,180 | permissive | [
{
"docstring": ":type path: str :type image_paths: list of bviewer.core.files.path.ImagePath",
"name": "__init__",
"signature": "def __init__(self, path, image_paths)"
},
{
"docstring": "Split path for folders name with path fot this name. Example:: /r/p1/p2 -> r:/r, p1:/r/p2, p2:/r/p1/p2 :rtype... | 2 | null | Implement the Python class `ImageFolder` described below.
Class description:
Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files`
Method signatures and docstrings:
- def __init__(self, path, image_paths): :type path: str :type image_paths: list of bviewer.core.files.path.ImagePath
-... | Implement the Python class `ImageFolder` described below.
Class description:
Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files`
Method signatures and docstrings:
- def __init__(self, path, image_paths): :type path: str :type image_paths: list of bviewer.core.files.path.ImagePath
-... | 59d5baeeeffd43d69587228ebc5cce1811dc9f63 | <|skeleton|>
class ImageFolder:
"""Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files`"""
def __init__(self, path, image_paths):
""":type path: str :type image_paths: list of bviewer.core.files.path.ImagePath"""
<|body_0|>
def split_path(self):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageFolder:
"""Simple help class to use in views. Store `path`, `back` path, sorted `dirs` and `files`"""
def __init__(self, path, image_paths):
""":type path: str :type image_paths: list of bviewer.core.files.path.ImagePath"""
self.path = path
self.back = os.path.dirname(path)
... | the_stack_v2_python_sparse | bviewer/core/files/utils.py | b7w/bviewer | train | 0 |
5909417bfa2dc1910f7694d6505b7f24b6215d81 | [
"self.model_config = model_config\nself.data_dir = data_dir\nreturn",
"self.model = Model()\nself.model.initialize(self.model_config, self.data_dir)\nif points == 'groundsurf':\n self.model.write_surfxy()\nelif points == 'blocks':\n self.model.write_blocks()\nelse:\n raise ValueError(\"Unknown value '%s'... | <|body_start_0|>
self.model_config = model_config
self.data_dir = data_dir
return
<|end_body_0|>
<|body_start_1|>
self.model = Model()
self.model.initialize(self.model_config, self.data_dir)
if points == 'groundsurf':
self.model.write_surfxy()
elif po... | Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks. | App | [
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks."""
def __init__(self, model_config, data_dir):
... | stack_v2_sparse_classes_75kplus_train_008419 | 12,090 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, model_config, data_dir)"
},
{
"docstring": "Generate points in the model blocks. :param points: If points == \"groundsurf\", generate points on ground surface. If points == \"blocks\", generate points in each blo... | 2 | stack_v2_sparse_classes_30k_train_037898 | Implement the Python class `App` described below.
Class description:
Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks.
Method signatu... | Implement the Python class `App` described below.
Class description:
Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks.
Method signatu... | 7d0db3c4ca1a83fea69ceb88f6ceec258928251a | <|skeleton|>
class App:
"""Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks."""
def __init__(self, model_config, data_dir):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
"""Create xyz grid files, one file per block with points in physical space. The intent is that external modeling tools provide the values at these points. This step can be skipped if the model is already discretized in a suite of blocks."""
def __init__(self, model_config, data_dir):
"""Cons... | the_stack_v2_python_sparse | geomodelgrids/scripts/generate_points.py | baagaard-usgs/geomodelgrids | train | 5 |
c51d97656d2c65892e5423d0c820b5fe8bb65f82 | [
"super().__init__()\nself.in_features = in_features\nself.groups = groups or ['last', 'avg_droplast', 'max_droplast', 'softmax_droplast']\nself.out_features = in_features * len(self.groups)\ngroups = {}\nfor key in self.groups:\n if isinstance(key, str):\n groups[key] = _get_pooling(key, self.in_features)... | <|body_start_0|>
super().__init__()
self.in_features = in_features
self.groups = groups or ['last', 'avg_droplast', 'max_droplast', 'softmax_droplast']
self.out_features = in_features * len(self.groups)
groups = {}
for key in self.groups:
if isinstance(key, st... | @TODO: Docs. Contribution is welcome. | LamaPooling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LamaPooling:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, in_features, groups=None):
"""@TODO: Docs. Contribution is welcome."""
<|body_0|>
def forward(self, x: torch.Tensor, mask: torch.Tensor=None) -> torch.Tensor:
"""Forward method of the LAM... | stack_v2_sparse_classes_75kplus_train_008420 | 6,469 | permissive | [
{
"docstring": "@TODO: Docs. Contribution is welcome.",
"name": "__init__",
"signature": "def __init__(self, in_features, groups=None)"
},
{
"docstring": "Forward method of the LAMA. Args: x: tensor of size (batch_size, history_len, feature_size) mask: mask to use for attention compute Returns: ... | 2 | stack_v2_sparse_classes_30k_train_019792 | Implement the Python class `LamaPooling` described below.
Class description:
@TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, in_features, groups=None): @TODO: Docs. Contribution is welcome.
- def forward(self, x: torch.Tensor, mask: torch.Tensor=None) -> torch.Tensor: Forw... | Implement the Python class `LamaPooling` described below.
Class description:
@TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, in_features, groups=None): @TODO: Docs. Contribution is welcome.
- def forward(self, x: torch.Tensor, mask: torch.Tensor=None) -> torch.Tensor: Forw... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class LamaPooling:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, in_features, groups=None):
"""@TODO: Docs. Contribution is welcome."""
<|body_0|>
def forward(self, x: torch.Tensor, mask: torch.Tensor=None) -> torch.Tensor:
"""Forward method of the LAM... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LamaPooling:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, in_features, groups=None):
"""@TODO: Docs. Contribution is welcome."""
super().__init__()
self.in_features = in_features
self.groups = groups or ['last', 'avg_droplast', 'max_droplast', 'softmax_dr... | the_stack_v2_python_sparse | catalyst/contrib/layers/lama.py | catalyst-team/catalyst | train | 3,038 |
e7e560c171654e7247a156335b235904983657e1 | [
"checked = None\nman = Globals.manager.command('database show incidents')\nfor i, r in enumerate(man.response[3:-2]):\n match = re_db.search(r)\n if match:\n k, v = match.groups()\n log.debug('Line %d match: %s -> %s' % (i, k, v))\n if v == '1':\n checked = k\n else:\n ... | <|body_start_0|>
checked = None
man = Globals.manager.command('database show incidents')
for i, r in enumerate(man.response[3:-2]):
match = re_db.search(r)
if match:
k, v = match.groups()
log.debug('Line %d match: %s -> %s' % (i, k, v))
... | Incident_ctrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Incident_ctrl:
def index(self, **kw):
"""Display incident form"""
<|body_0|>
def modify(self, checked=[], **kw):
"""Modify Asterisk database (incidents)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
checked = None
man = Globals.manager.com... | stack_v2_sparse_classes_75kplus_train_008421 | 2,441 | no_license | [
{
"docstring": "Display incident form",
"name": "index",
"signature": "def index(self, **kw)"
},
{
"docstring": "Modify Asterisk database (incidents)",
"name": "modify",
"signature": "def modify(self, checked=[], **kw)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038783 | Implement the Python class `Incident_ctrl` described below.
Class description:
Implement the Incident_ctrl class.
Method signatures and docstrings:
- def index(self, **kw): Display incident form
- def modify(self, checked=[], **kw): Modify Asterisk database (incidents) | Implement the Python class `Incident_ctrl` described below.
Class description:
Implement the Incident_ctrl class.
Method signatures and docstrings:
- def index(self, **kw): Display incident form
- def modify(self, checked=[], **kw): Modify Asterisk database (incidents)
<|skeleton|>
class Incident_ctrl:
def inde... | 8a923e59de0f8211e051ef94e160539f1debde95 | <|skeleton|>
class Incident_ctrl:
def index(self, **kw):
"""Display incident form"""
<|body_0|>
def modify(self, checked=[], **kw):
"""Modify Asterisk database (incidents)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Incident_ctrl:
def index(self, **kw):
"""Display incident form"""
checked = None
man = Globals.manager.command('database show incidents')
for i, r in enumerate(man.response[3:-2]):
match = re_db.search(r)
if match:
k, v = match.groups()
... | the_stack_v2_python_sparse | astportal2/controllers/incident.py | sysnux/astportal | train | 0 | |
be8755b05fb0da96905de20a9975a46c3b6c1715 | [
"self.n_bins = n_bins\nself.min_bin = min_bin\nself.max_bin = max_bin\nself.bin_edges_ = None",
"combined_times = np.concatenate([spectrum[:, 0] for spectrum in X], axis=0)\nmin_range = min(self.min_bin, np.min(combined_times))\nmax_range = max(self.max_bin, np.max(combined_times))\n_, self.bin_edges_ = np.histog... | <|body_start_0|>
self.n_bins = n_bins
self.min_bin = min_bin
self.max_bin = max_bin
self.bin_edges_ = None
<|end_body_0|>
<|body_start_1|>
combined_times = np.concatenate([spectrum[:, 0] for spectrum in X], axis=0)
min_range = min(self.min_bin, np.min(combined_times))
... | Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer. | BinningVectorizer | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinningVectorizer:
"""Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer."""
def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf')):
"""Initialize BinningVectorizer. Args: n_bins: Number of b... | stack_v2_sparse_classes_75kplus_train_008422 | 2,224 | permissive | [
{
"docstring": "Initialize BinningVectorizer. Args: n_bins: Number of bins to bin the inputs spectra into. min_bin: Smallest possible bin edge. max_bin: Largest possible bin edge.",
"name": "__init__",
"signature": "def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf'))"
},
{
"d... | 3 | null | Implement the Python class `BinningVectorizer` described below.
Class description:
Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer.
Method signatures and docstrings:
- def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf'))... | Implement the Python class `BinningVectorizer` described below.
Class description:
Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer.
Method signatures and docstrings:
- def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf'))... | 032bfcf1cd9b482ff851d68faaa2cf967aaf62a8 | <|skeleton|>
class BinningVectorizer:
"""Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer."""
def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf')):
"""Initialize BinningVectorizer. Args: n_bins: Number of b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinningVectorizer:
"""Vectorizer based on binning MALDI-TOF spectra. Attributes: bin_edges_: Edges of the bins derived after fitting the transformer."""
def __init__(self, n_bins, min_bin=float('inf'), max_bin=float('-inf')):
"""Initialize BinningVectorizer. Args: n_bins: Number of bins to bin th... | the_stack_v2_python_sparse | maldi-learn/maldi_learn/vectorization/binning.py | dariogodoy2003/maldi_PIKE | train | 0 |
0d20c6f7ff0f58faade08b1e5b77340fd3878fec | [
"self.am_coeffs = None\nself.alt_coeffs = None\nself.reference_transmission = 1.0\nself.poly_am = None\nself.poly_alt = None\nself.configure_options(options)",
"if not isinstance(options, dict):\n raise ValueError(f'Options must be a {dict}. Received {options}.')\nam_coeffs = get_float_list(options.get('amcoe... | <|body_start_0|>
self.am_coeffs = None
self.alt_coeffs = None
self.reference_transmission = 1.0
self.poly_am = None
self.poly_alt = None
self.configure_options(options)
<|end_body_0|>
<|body_start_1|>
if not isinstance(options, dict):
raise ValueError... | AtranModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmos... | stack_v2_sparse_classes_75kplus_train_008423 | 6,143 | permissive | [
{
"docstring": "Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmospheric opacity. Please see :func:`AtranModel.get_rel... | 4 | stack_v2_sparse_classes_30k_train_023068 | Implement the Python class `AtranModel` described below.
Class description:
Implement the AtranModel class.
Method signatures and docstrings:
- def __init__(self, options): Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above th... | Implement the Python class `AtranModel` described below.
Class description:
Implement the AtranModel class.
Method signatures and docstrings:
- def __init__(self, options): Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above th... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmos... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmospheric opacity... | the_stack_v2_python_sparse | sofia_redux/scan/custom/sofia/integration/models/atran.py | SOFIA-USRA/sofia_redux | train | 12 | |
18a03ff8f3c90c9c55a1184a12c33601c3169bb3 | [
"fields = kwargs.pop('fields', None)\nsuper().__init__(*args, **kwargs)\nif fields is not None:\n allowed = set(fields)\n existing = set(self.fields)\n for field_name in existing - allowed:\n self.fields.pop(field_name)",
"ret = super().to_representation(instance)\nif 'groups' in self.fields:\n ... | <|body_start_0|>
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
<|end_body_0|>
<|... | Serializer for a user of the system. | UserSerializer | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""Serializer for a user of the system."""
def __init__(self, *args, **kwargs):
"""Dynamically add or exclude the fields to be serialized."""
<|body_0|>
def to_representation(self, instance):
"""Return fully serialized groups."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_008424 | 1,540 | permissive | [
{
"docstring": "Dynamically add or exclude the fields to be serialized.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Return fully serialized groups.",
"name": "to_representation",
"signature": "def to_representation(self, instance)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042025 | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for a user of the system.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Dynamically add or exclude the fields to be serialized.
- def to_representation(self, instance): Return fully serialized groups. | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for a user of the system.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Dynamically add or exclude the fields to be serialized.
- def to_representation(self, instance): Return fully serialized groups.... | db16f9d01e5579961a7a82af8f11e2dd129516ca | <|skeleton|>
class UserSerializer:
"""Serializer for a user of the system."""
def __init__(self, *args, **kwargs):
"""Dynamically add or exclude the fields to be serialized."""
<|body_0|>
def to_representation(self, instance):
"""Return fully serialized groups."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSerializer:
"""Serializer for a user of the system."""
def __init__(self, *args, **kwargs):
"""Dynamically add or exclude the fields to be serialized."""
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed = ... | the_stack_v2_python_sparse | server/users/serializers.py | jdalton92/trading-bot | train | 0 |
90f663bc6908576487452747db412406e0607c97 | [
"d = datetime(2017, 9, 16, 10, 0, 0, 0)\nself.fail('Write a single line expression')\nself.assertEqual(last_friday, datetime(2017, 9, 15, 10, 0, 0, 0))",
"d = datetime(2017, 9, 16, 10, 0, 0, 0)\nself.fail('Write a single line expression')\nself.assertEqual(next_friday, datetime(2017, 9, 22, 10, 0, 0, 0))"
] | <|body_start_0|>
d = datetime(2017, 9, 16, 10, 0, 0, 0)
self.fail('Write a single line expression')
self.assertEqual(last_friday, datetime(2017, 9, 15, 10, 0, 0, 0))
<|end_body_0|>
<|body_start_1|>
d = datetime(2017, 9, 16, 10, 0, 0, 0)
self.fail('Write a single line expression'... | DeterminingLastFridaysDateTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeterminingLastFridaysDateTest:
def test_find_last_friday(self):
"""Hint: this uses a 3rd party package."""
<|body_0|>
def test_find_next_friday(self):
"""Hint: this uses a 3rd party package."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = datet... | stack_v2_sparse_classes_75kplus_train_008425 | 8,669 | no_license | [
{
"docstring": "Hint: this uses a 3rd party package.",
"name": "test_find_last_friday",
"signature": "def test_find_last_friday(self)"
},
{
"docstring": "Hint: this uses a 3rd party package.",
"name": "test_find_next_friday",
"signature": "def test_find_next_friday(self)"
}
] | 2 | null | Implement the Python class `DeterminingLastFridaysDateTest` described below.
Class description:
Implement the DeterminingLastFridaysDateTest class.
Method signatures and docstrings:
- def test_find_last_friday(self): Hint: this uses a 3rd party package.
- def test_find_next_friday(self): Hint: this uses a 3rd party p... | Implement the Python class `DeterminingLastFridaysDateTest` described below.
Class description:
Implement the DeterminingLastFridaysDateTest class.
Method signatures and docstrings:
- def test_find_last_friday(self): Hint: this uses a 3rd party package.
- def test_find_next_friday(self): Hint: this uses a 3rd party p... | b0b47df00aac7423b91f196ec7e041fac1937aef | <|skeleton|>
class DeterminingLastFridaysDateTest:
def test_find_last_friday(self):
"""Hint: this uses a 3rd party package."""
<|body_0|>
def test_find_next_friday(self):
"""Hint: this uses a 3rd party package."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeterminingLastFridaysDateTest:
def test_find_last_friday(self):
"""Hint: this uses a 3rd party package."""
d = datetime(2017, 9, 16, 10, 0, 0, 0)
self.fail('Write a single line expression')
self.assertEqual(last_friday, datetime(2017, 9, 15, 10, 0, 0, 0))
def test_find_ne... | the_stack_v2_python_sparse | pythoncookbook/chapter3_tests.py | wkeeling/kata | train | 1 | |
200510986ad8ac2d3474f57809abb70cc89c8e28 | [
"self._df = df\nself._default_index = df.index.names == [None]\nself._pandas = __import__('pandas')",
"cls_name = self.__class__.__name__\nhex_id = hex(id(self._df))\nreturn '{0}(<pandas.DataFrame object at {1}>)'.format(cls_name, hex_id)",
"columns = self.columns()\nif self._default_index:\n for row in self... | <|body_start_0|>
self._df = df
self._default_index = df.index.names == [None]
self._pandas = __import__('pandas')
<|end_body_0|>
<|body_start_1|>
cls_name = self.__class__.__name__
hex_id = hex(id(self._df))
return '{0}(<pandas.DataFrame object at {1}>)'.format(cls_name,... | Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optimize. PandasSource is not yet optimized for speed (although it will be in the fu... | PandasSource | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PandasSource:
"""Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optimize. PandasSource is not yet optimized ... | stack_v2_sparse_classes_75kplus_train_008426 | 4,042 | permissive | [
{
"docstring": "Initialize self.",
"name": "__init__",
"signature": "def __init__(self, df)"
},
{
"docstring": "Return a string representation of the data source.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "Return iterable of dictionary rows (like c... | 6 | stack_v2_sparse_classes_30k_train_016957 | Implement the Python class `PandasSource` described below.
Class description:
Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optim... | Implement the Python class `PandasSource` described below.
Class description:
Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optim... | 2e200e2bb7d9a8016bcb6e908d4a8b12db8e2568 | <|skeleton|>
class PandasSource:
"""Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optimize. PandasSource is not yet optimized ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PandasSource:
"""Loads pandas DataFrame as a data source: .. code-block:: python subject = datatest.PandasSource(df) .. note:: This data source is optional---it requires the third-party library `pandas <https://pypi.python.org/pypi/pandas>`_. .. todo:: Optimize. PandasSource is not yet optimized for speed (al... | the_stack_v2_python_sparse | datatest/sources/pandas.py | chansonZ/datatest | train | 0 |
0e831601ce60cbd7e239d58aec965b526a19cb21 | [
"super(MeasureMBDsystem, self).__init__(measure_type, parent=parent)\nif name is None:\n self._name = 'MBD_system_' + measure_type\nelse:\n self._name = name\nif MBD_system is None:\n self.MBD_system = self._parent._parent\nelse:\n self.MBD_system = MBD_system\nself.x = []\nself.y_variables = ['kinetic_... | <|body_start_0|>
super(MeasureMBDsystem, self).__init__(measure_type, parent=parent)
if name is None:
self._name = 'MBD_system_' + measure_type
else:
self._name = name
if MBD_system is None:
self.MBD_system = self._parent._parent
else:
... | classdocs | MeasureMBDsystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasureMBDsystem:
"""classdocs"""
def __init__(self, measure_type, MBD_system=None, name=None, parent=None):
"""Constructor"""
<|body_0|>
def _measure(self, step, h, t, q):
""":param t: :return q: vector of state of MBD system"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_008427 | 1,863 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, measure_type, MBD_system=None, name=None, parent=None)"
},
{
"docstring": ":param t: :return q: vector of state of MBD system",
"name": "_measure",
"signature": "def _measure(self, step, h, t, q)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000590 | Implement the Python class `MeasureMBDsystem` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, measure_type, MBD_system=None, name=None, parent=None): Constructor
- def _measure(self, step, h, t, q): :param t: :return q: vector of state of MBD system | Implement the Python class `MeasureMBDsystem` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, measure_type, MBD_system=None, name=None, parent=None): Constructor
- def _measure(self, step, h, t, q): :param t: :return q: vector of state of MBD system
<|skeleton|>
c... | 5e6a54dee662206664dde022ccca372f966b1789 | <|skeleton|>
class MeasureMBDsystem:
"""classdocs"""
def __init__(self, measure_type, MBD_system=None, name=None, parent=None):
"""Constructor"""
<|body_0|>
def _measure(self, step, h, t, q):
""":param t: :return q: vector of state of MBD system"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeasureMBDsystem:
"""classdocs"""
def __init__(self, measure_type, MBD_system=None, name=None, parent=None):
"""Constructor"""
super(MeasureMBDsystem, self).__init__(measure_type, parent=parent)
if name is None:
self._name = 'MBD_system_' + measure_type
else:
... | the_stack_v2_python_sparse | MBD_system/measure/measure_MBD_system.py | xupeiwust/DyS | train | 0 |
3c377f2d4253f4f70d94bd3d010c48886e8edddf | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 修改和删除地址 | UpdateDestroyAddressView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址 :param request: 请求对象 :param address_id: 删除地址的id :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008428 | 21,636 | permissive | [
{
"docstring": "修改地址",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除地址 :param request: 请求对象 :param address_id: 删除地址的id :return:",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012792 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址 :param request: 请求对象 :param address_id: 删除地址的id :return: | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址 :param request: 请求对象 :param address_id: 删除地址的id :return:
<|skeleton|>
class UpdateDestroyAddress... | b1aa6da9e3d0af3e6aa7ff2587148845469aefad | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址 :param request: 请求对象 :param address_id: 删除地址的id :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/views.py | HuiDBK/meiduo_project | train | 0 |
f977ba1bab53dec232d62c2e52731d2bf6ee8451 | [
"self.path_params = {'ver': self.version[release]}\nself.summary_file = self.get_path('mangagz3dmetadata', path_params=self.path_params)\nself.center_summary_file = self.get_path('mangagz3dcenters', path_params=self.path_params)\nself.stars_summary_file = self.get_path('mangagz3dstars', path_params=self.path_params... | <|body_start_0|>
self.path_params = {'ver': self.version[release]}
self.summary_file = self.get_path('mangagz3dmetadata', path_params=self.path_params)
self.center_summary_file = self.get_path('mangagz3dcenters', path_params=self.path_params)
self.stars_summary_file = self.get_path('mang... | Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating galaxy centers, foreground stars, b... | GZ3DVAC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating ... | stack_v2_sparse_classes_75kplus_train_008429 | 47,753 | permissive | [
{
"docstring": "Sets the path to the GalaxyZoo3D summary file",
"name": "set_summary_file",
"signature": "def set_summary_file(self, release)"
},
{
"docstring": "Find the GZ3D data based on the manga ID",
"name": "get_target",
"signature": "def get_target(self, parent_object)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002086 | Implement the Python class `GZ3DVAC` described below.
Class description:
Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platfor... | Implement the Python class `GZ3DVAC` described below.
Class description:
Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platfor... | db4c536a65fb2f16fee05a4f34996a7fd35f0527 | <|skeleton|>
class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating galaxy center... | the_stack_v2_python_sparse | python/marvin/contrib/vacs/galaxyzoo3d.py | sdss/marvin | train | 56 |
f43e37db49d57b403a976c971ee66b25680e557e | [
"try:\n cluster = Cluster([host], port=port)\n self.session = cluster.connect(keyspace)\nexcept Exception as e:\n print('The connection was unsuccessful.\\n' + str(e))",
"try:\n df = pd.DataFrame(list(self.session.execute(query)))\n return df\nexcept Exception as e:\n print('An error occurred du... | <|body_start_0|>
try:
cluster = Cluster([host], port=port)
self.session = cluster.connect(keyspace)
except Exception as e:
print('The connection was unsuccessful.\n' + str(e))
<|end_body_0|>
<|body_start_1|>
try:
df = pd.DataFrame(list(self.sessio... | CassandraHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CassandraHelper:
def __init__(self, host, port, keyspace):
"""creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of the keyspace"""
<|body_0|>
def execute_query_cassandra(self, query):
"""For executi... | stack_v2_sparse_classes_75kplus_train_008430 | 861 | no_license | [
{
"docstring": "creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of the keyspace",
"name": "__init__",
"signature": "def __init__(self, host, port, keyspace)"
},
{
"docstring": "For executing cassandra query :param query: The ... | 2 | stack_v2_sparse_classes_30k_train_008877 | Implement the Python class `CassandraHelper` described below.
Class description:
Implement the CassandraHelper class.
Method signatures and docstrings:
- def __init__(self, host, port, keyspace): creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of ... | Implement the Python class `CassandraHelper` described below.
Class description:
Implement the CassandraHelper class.
Method signatures and docstrings:
- def __init__(self, host, port, keyspace): creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of ... | 0ee797be88095388c41bc5074df926760a0e3f8f | <|skeleton|>
class CassandraHelper:
def __init__(self, host, port, keyspace):
"""creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of the keyspace"""
<|body_0|>
def execute_query_cassandra(self, query):
"""For executi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CassandraHelper:
def __init__(self, host, port, keyspace):
"""creating connection with cassandra :param host: The host name. :param port: The port in use. :param keyspace: The name of the keyspace"""
try:
cluster = Cluster([host], port=port)
self.session = cluster.conne... | the_stack_v2_python_sparse | helpers/cassandra_helper.py | taimoorpashanbs17/DataLake_Automation | train | 0 | |
99450ced7e4c106cabf7ef9ec30fd8835b4f84a2 | [
"super(LAMBOptimizer, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nif exclude_from_layer_adaptation:\n self.exclude_from_... | <|body_start_0|>
super(LAMBOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight_de... | LAMB (Layer-wise Adaptive Moments optimizer for Batch training). | LAMBOptimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LAMBOptimizer:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_from_layer_adaptation=None, name='LAMBOptimizer'):
"""Constr... | stack_v2_sparse_classes_75kplus_train_008431 | 16,787 | no_license | [
{
"docstring": "Constructs a LAMBOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_from_layer_adaptation=None, name='LAMBOptimizer')"
},
{
"docstring": "See base... | 5 | stack_v2_sparse_classes_30k_train_000428 | Implement the Python class `LAMBOptimizer` described below.
Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_... | Implement the Python class `LAMBOptimizer` described below.
Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_... | 7be89d283b4f0572b47ba0150647080976e5928f | <|skeleton|>
class LAMBOptimizer:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_from_layer_adaptation=None, name='LAMBOptimizer'):
"""Constr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LAMBOptimizer:
"""LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, exclude_from_layer_adaptation=None, name='LAMBOptimizer'):
"""Constructs a LAMBOp... | the_stack_v2_python_sparse | model/utils.py | SangMyeongWoh/mass_raw_tf1 | train | 0 |
a439ce26eda5c9433a914ff863db050b41ad8b56 | [
"self.dt = None\nif data_table is not None:\n self.dt = data_table\nelse:\n self.dt = dt.DataTable(dimensions)\n self.input = dimensions[0]\n self.hidden = dimensions[1]\n self.output = dimensions[2]\nself.input = self.dt.input\nself.hidden = self.dt.hidden\nself.output = self.dt.output\nself.f = squ... | <|body_start_0|>
self.dt = None
if data_table is not None:
self.dt = data_table
else:
self.dt = dt.DataTable(dimensions)
self.input = dimensions[0]
self.hidden = dimensions[1]
self.output = dimensions[2]
self.input = self.dt.inp... | This class implements the training and forward pass algorithms for the neural network. | NeuralNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralNet:
"""This class implements the training and forward pass algorithms for the neural network."""
def __init__(self, dimensions, squash, squash_prime, alpha, data_table=None):
"""Initialize the nodes of the network. Args: dimensions: A tuple, input hidden and output node counts... | stack_v2_sparse_classes_75kplus_train_008432 | 4,601 | no_license | [
{
"docstring": "Initialize the nodes of the network. Args: dimensions: A tuple, input hidden and output node counts. squash: A squashing function squash_prime: First derivative of the squashing func. alpha: The network learning rate.",
"name": "__init__",
"signature": "def __init__(self, dimensions, squ... | 5 | stack_v2_sparse_classes_30k_train_024183 | Implement the Python class `NeuralNet` described below.
Class description:
This class implements the training and forward pass algorithms for the neural network.
Method signatures and docstrings:
- def __init__(self, dimensions, squash, squash_prime, alpha, data_table=None): Initialize the nodes of the network. Args:... | Implement the Python class `NeuralNet` described below.
Class description:
This class implements the training and forward pass algorithms for the neural network.
Method signatures and docstrings:
- def __init__(self, dimensions, squash, squash_prime, alpha, data_table=None): Initialize the nodes of the network. Args:... | 69621f92f2cabd153ecc6803d0182e26bc1d9f88 | <|skeleton|>
class NeuralNet:
"""This class implements the training and forward pass algorithms for the neural network."""
def __init__(self, dimensions, squash, squash_prime, alpha, data_table=None):
"""Initialize the nodes of the network. Args: dimensions: A tuple, input hidden and output node counts... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralNet:
"""This class implements the training and forward pass algorithms for the neural network."""
def __init__(self, dimensions, squash, squash_prime, alpha, data_table=None):
"""Initialize the nodes of the network. Args: dimensions: A tuple, input hidden and output node counts. squash: A s... | the_stack_v2_python_sparse | neural_net.py | nail82/bpnn | train | 0 |
b974f0025d7f1568013cc02a97d1d167c365b19d | [
"super().setUp()\nguild = Guild(12345)\nself.db.session.add(guild)\nself.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc)))\nself.db.session.add(Event(guild, 'Two', datetime(2020, 10, 10, 11, 0, tzinfo=utc), repetition=EventRepetitionFrequency.weekly))\nself.db.session.commit()",
"with... | <|body_start_0|>
super().setUp()
guild = Guild(12345)
self.db.session.add(guild)
self.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc)))
self.db.session.add(Event(guild, 'Two', datetime(2020, 10, 10, 11, 0, tzinfo=utc), repetition=EventRepetitionFreque... | TestEventControllers | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEventControllers:
def setUp(self):
"""Add some stuff in the database."""
<|body_0|>
def test_get_all_events(self):
"""Ensure we return all events in the database."""
<|body_1|>
def test_get_event(self):
"""Ensure we can retrieve a single even... | stack_v2_sparse_classes_75kplus_train_008433 | 3,578 | permissive | [
{
"docstring": "Add some stuff in the database.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Ensure we return all events in the database.",
"name": "test_get_all_events",
"signature": "def test_get_all_events(self)"
},
{
"docstring": "Ensure we can retriev... | 6 | stack_v2_sparse_classes_30k_train_002072 | Implement the Python class `TestEventControllers` described below.
Class description:
Implement the TestEventControllers class.
Method signatures and docstrings:
- def setUp(self): Add some stuff in the database.
- def test_get_all_events(self): Ensure we return all events in the database.
- def test_get_event(self):... | Implement the Python class `TestEventControllers` described below.
Class description:
Implement the TestEventControllers class.
Method signatures and docstrings:
- def setUp(self): Add some stuff in the database.
- def test_get_all_events(self): Ensure we return all events in the database.
- def test_get_event(self):... | 709dd307b046158ddf9e49a559852d486168a94f | <|skeleton|>
class TestEventControllers:
def setUp(self):
"""Add some stuff in the database."""
<|body_0|>
def test_get_all_events(self):
"""Ensure we return all events in the database."""
<|body_1|>
def test_get_event(self):
"""Ensure we can retrieve a single even... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestEventControllers:
def setUp(self):
"""Add some stuff in the database."""
super().setUp()
guild = Guild(12345)
self.db.session.add(guild)
self.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc)))
self.db.session.add(Event(guild, 'Two... | the_stack_v2_python_sparse | api/mod_event/controllers_test.py | FunkySayu/discord-event-manager | train | 6 | |
0744a82928fc5650932020d1d41acd49661e99ca | [
"self.line_numbers_path = line_numbers_path\nself.logger = Logger.from_config_file()\nif os.path.exists(self.line_numbers_path):\n with open(self.line_numbers_path) as fin:\n self.line_numbers = pickle.load(fin)\nelse:\n self.line_numbers = {}",
"b = reader(1024 * 1024)\nwhile b:\n yield b\n b ... | <|body_start_0|>
self.line_numbers_path = line_numbers_path
self.logger = Logger.from_config_file()
if os.path.exists(self.line_numbers_path):
with open(self.line_numbers_path) as fin:
self.line_numbers = pickle.load(fin)
else:
self.line_numbers = ... | Count lines of files and cache the results. | LineCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineCounter:
"""Count lines of files and cache the results."""
def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl'):
"""Specify where to save the cached line counts. :param line_numbers_path: input and output file for cached line counts"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_008434 | 2,692 | no_license | [
{
"docstring": "Specify where to save the cached line counts. :param line_numbers_path: input and output file for cached line counts",
"name": "__init__",
"signature": "def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl')"
},
{
"docstring": "Yield data chunks from a file. ... | 4 | stack_v2_sparse_classes_30k_train_017568 | Implement the Python class `LineCounter` described below.
Class description:
Count lines of files and cache the results.
Method signatures and docstrings:
- def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl'): Specify where to save the cached line counts. :param line_numbers_path: input and ou... | Implement the Python class `LineCounter` described below.
Class description:
Count lines of files and cache the results.
Method signatures and docstrings:
- def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl'): Specify where to save the cached line counts. :param line_numbers_path: input and ou... | 187023f93937985e10f593b032ea7f48c1d61060 | <|skeleton|>
class LineCounter:
"""Count lines of files and cache the results."""
def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl'):
"""Specify where to save the cached line counts. :param line_numbers_path: input and output file for cached line counts"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LineCounter:
"""Count lines of files and cache the results."""
def __init__(self, line_numbers_path=dir_path + '../data/line_numbers.pkl'):
"""Specify where to save the cached line counts. :param line_numbers_path: input and output file for cached line counts"""
self.line_numbers_path = l... | the_stack_v2_python_sparse | helper_functions/line_counting.py | janetzki/fact_extraction | train | 5 |
2611c1bef0d54f8a6fb8d7b001fcf32e415881cd | [
"super(DCDiscrimininator, self).__init__()\nself.img_shape = img_shape\nn_filters = clip_channels(16)\nself.init_conv2d = nn.Conv2d(img_shape[0], n_filters, kernel_size=3, stride=2, padding=1)\nnn.init.kaiming_normal_(self.init_conv2d.weight)\ncur_img_size = self.img_shape[2] // 2\nself.conv2d_layers = nn.ModuleLis... | <|body_start_0|>
super(DCDiscrimininator, self).__init__()
self.img_shape = img_shape
n_filters = clip_channels(16)
self.init_conv2d = nn.Conv2d(img_shape[0], n_filters, kernel_size=3, stride=2, padding=1)
nn.init.kaiming_normal_(self.init_conv2d.weight)
cur_img_size = se... | DCDiscrimininator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCDiscrimininator:
def __init__(self, img_shape: Tuple[int, int, int]):
"""Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies a 3x3 convolutional layer with ReLu activation and a 2x2 stride until the desired embedding size is reache... | stack_v2_sparse_classes_75kplus_train_008435 | 5,032 | no_license | [
{
"docstring": "Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies a 3x3 convolutional layer with ReLu activation and a 2x2 stride until the desired embedding size is reached. The flattened embedding is ran through a Dense layer with sigmoid output to labe... | 2 | stack_v2_sparse_classes_30k_train_042246 | Implement the Python class `DCDiscrimininator` described below.
Class description:
Implement the DCDiscrimininator class.
Method signatures and docstrings:
- def __init__(self, img_shape: Tuple[int, int, int]): Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies ... | Implement the Python class `DCDiscrimininator` described below.
Class description:
Implement the DCDiscrimininator class.
Method signatures and docstrings:
- def __init__(self, img_shape: Tuple[int, int, int]): Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies ... | e7388d5bac4451b0c72ece5c3c2cd399b08048e6 | <|skeleton|>
class DCDiscrimininator:
def __init__(self, img_shape: Tuple[int, int, int]):
"""Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies a 3x3 convolutional layer with ReLu activation and a 2x2 stride until the desired embedding size is reache... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DCDiscrimininator:
def __init__(self, img_shape: Tuple[int, int, int]):
"""Builds the DCGAN discriminator. Builds the very simple discriminator that takes an image input and applies a 3x3 convolutional layer with ReLu activation and a 2x2 stride until the desired embedding size is reached. The flatten... | the_stack_v2_python_sparse | networks/modules/dcgan.py | mcschmitz/duck_and_cover | train | 0 | |
cea5e2f78806bca68114b2d08f120f0d96c6301a | [
"try:\n servicemgr = self.servicemanager\n level = record.levelno\n msg = self.format(record)\n if level >= logging.ERROR:\n servicemgr.LogErrorMsg(msg)\n elif level >= logging.WARNING:\n servicemgr.LogWarningMsg(msg)\n elif level >= logging.INFO:\n servicemgr.LogInfoMsg(msg)\... | <|body_start_0|>
try:
servicemgr = self.servicemanager
level = record.levelno
msg = self.format(record)
if level >= logging.ERROR:
servicemgr.LogErrorMsg(msg)
elif level >= logging.WARNING:
servicemgr.LogWarningMsg(msg)
... | Dispatches logging events to the win32 services event log. Requires pywin32. | ServiceEventLogHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceEventLogHandler:
"""Dispatches logging events to the win32 services event log. Requires pywin32."""
def emit(self, record):
"""Emit a record. If a formatter is specified, it is used to format the record. This record is then written to the win32 services event log, with the typ... | stack_v2_sparse_classes_75kplus_train_008436 | 7,552 | no_license | [
{
"docstring": "Emit a record. If a formatter is specified, it is used to format the record. This record is then written to the win32 services event log, with the type set to the appropriate type based on the level.",
"name": "emit",
"signature": "def emit(self, record)"
},
{
"docstring": "Handl... | 2 | stack_v2_sparse_classes_30k_train_012437 | Implement the Python class `ServiceEventLogHandler` described below.
Class description:
Dispatches logging events to the win32 services event log. Requires pywin32.
Method signatures and docstrings:
- def emit(self, record): Emit a record. If a formatter is specified, it is used to format the record. This record is t... | Implement the Python class `ServiceEventLogHandler` described below.
Class description:
Dispatches logging events to the win32 services event log. Requires pywin32.
Method signatures and docstrings:
- def emit(self, record): Emit a record. If a formatter is specified, it is used to format the record. This record is t... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class ServiceEventLogHandler:
"""Dispatches logging events to the win32 services event log. Requires pywin32."""
def emit(self, record):
"""Emit a record. If a formatter is specified, it is used to format the record. This record is then written to the win32 services event log, with the typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServiceEventLogHandler:
"""Dispatches logging events to the win32 services event log. Requires pywin32."""
def emit(self, record):
"""Emit a record. If a formatter is specified, it is used to format the record. This record is then written to the win32 services event log, with the type set to the ... | the_stack_v2_python_sparse | SpamBayes/rev3250-3267/right-branch-3267/windows/pop3proxy_service.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
e14f5f493f1270683ae216a11c4bef6faf33476c | [
"incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])\nself.assertEqual(incomplete_activities.id, 'user_id0')\nself.assertListEqual(incomplete_activities.exploration_ids, ['exp_id0'])\nself.assertListEqual(incomplete_activities.collection_ids, ['collect_id0'])",
"inco... | <|body_start_0|>
incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])
self.assertEqual(incomplete_activities.id, 'user_id0')
self.assertListEqual(incomplete_activities.exploration_ids, ['exp_id0'])
self.assertListEqual(incomplete_activities.c... | Testing domain object for incomplete activities model. | IncompleteActivitiesTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
<|body_0|>
def test_add_exploration_id(self):
"""Testing add_exploration_id."""
<|body_1|>
def test_remo... | stack_v2_sparse_classes_75kplus_train_008437 | 14,816 | permissive | [
{
"docstring": "Testing init method.",
"name": "test_initialization",
"signature": "def test_initialization(self)"
},
{
"docstring": "Testing add_exploration_id.",
"name": "test_add_exploration_id",
"signature": "def test_add_exploration_id(self)"
},
{
"docstring": "Testing remov... | 5 | stack_v2_sparse_classes_30k_train_010764 | Implement the Python class `IncompleteActivitiesTests` described below.
Class description:
Testing domain object for incomplete activities model.
Method signatures and docstrings:
- def test_initialization(self): Testing init method.
- def test_add_exploration_id(self): Testing add_exploration_id.
- def test_remove_e... | Implement the Python class `IncompleteActivitiesTests` described below.
Class description:
Testing domain object for incomplete activities model.
Method signatures and docstrings:
- def test_initialization(self): Testing init method.
- def test_add_exploration_id(self): Testing add_exploration_id.
- def test_remove_e... | 899b9755a6b795a8991e596055ac24065a8435e0 | <|skeleton|>
class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
<|body_0|>
def test_add_exploration_id(self):
"""Testing add_exploration_id."""
<|body_1|>
def test_remo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])
self.assertEqual(incomplete_activiti... | the_stack_v2_python_sparse | core/domain/user_domain_test.py | import-keshav/oppia | train | 4 |
f7264fd23bb6c45c8bf03f641f86c0351beafea5 | [
"url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2021141353548'\nbody = {'email': '17865517994', 'icode': '', 'origURL': 'http://www.renren.com/home', 'domain': 'renren.com', 'key_id': '1', 'captcha_type': 'web_login', 'password': '6b0f07a2a04f2975752196b1be667cd6a8c426b7be0f030a5f576dc605541cf8', ... | <|body_start_0|>
url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2021141353548'
body = {'email': '17865517994', 'icode': '', 'origURL': 'http://www.renren.com/home', 'domain': 'renren.com', 'key_id': '1', 'captcha_type': 'web_login', 'password': '6b0f07a2a04f2975752196b1be667cd6a8c426b7... | RRapi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RRapi:
def login(self):
"""用户登录"""
<|body_0|>
def edit_hobby(self, music, interest, book, movie, game, comic, sport='足球'):
"""编辑爱好"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=20211... | stack_v2_sparse_classes_75kplus_train_008438 | 2,679 | no_license | [
{
"docstring": "用户登录",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "编辑爱好",
"name": "edit_hobby",
"signature": "def edit_hobby(self, music, interest, book, movie, game, comic, sport='足球')"
}
] | 2 | null | Implement the Python class `RRapi` described below.
Class description:
Implement the RRapi class.
Method signatures and docstrings:
- def login(self): 用户登录
- def edit_hobby(self, music, interest, book, movie, game, comic, sport='足球'): 编辑爱好 | Implement the Python class `RRapi` described below.
Class description:
Implement the RRapi class.
Method signatures and docstrings:
- def login(self): 用户登录
- def edit_hobby(self, music, interest, book, movie, game, comic, sport='足球'): 编辑爱好
<|skeleton|>
class RRapi:
def login(self):
"""用户登录"""
<|... | f6f38b4c8c180d37a52dfaac62063f936f3bad02 | <|skeleton|>
class RRapi:
def login(self):
"""用户登录"""
<|body_0|>
def edit_hobby(self, music, interest, book, movie, game, comic, sport='足球'):
"""编辑爱好"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RRapi:
def login(self):
"""用户登录"""
url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2021141353548'
body = {'email': '17865517994', 'icode': '', 'origURL': 'http://www.renren.com/home', 'domain': 'renren.com', 'key_id': '1', 'captcha_type': 'web_login', 'password': '6b0f... | the_stack_v2_python_sparse | pageobject/api_renren.py | 16602710209/webdriverTest | train | 0 | |
816bae834ff4c9d1743898813a224d9db2a2dcad | [
"sensor = get_api_all_model()['Sensor']\nconstants = sensor.API_CONSTANTS.items()\nresult_map = {v: k for k, v in constants if not k.lower().endswith('sensor')}\nresult_type = self.api_coerce_int(self.type)\nreturn result_map.get(result_type, result_type)",
"values = []\nfor row in self.API_DATA_SET.rows:\n ro... | <|body_start_0|>
sensor = get_api_all_model()['Sensor']
constants = sensor.API_CONSTANTS.items()
result_map = {v: k for k, v in constants if not k.lower().endswith('sensor')}
result_type = self.api_coerce_int(self.type)
return result_map.get(result_type, result_type)
<|end_body_0... | Manually defined API object. | Column | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Column:
"""Manually defined API object."""
def result_type(self):
"""Expose simple attr "rt" as result_type. Notes: Will try to map str from "rt" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`"""
<|body_0|>
def get_values(self, attr='value', j... | stack_v2_sparse_classes_75kplus_train_008439 | 28,308 | permissive | [
{
"docstring": "Expose simple attr \"rt\" as result_type. Notes: Will try to map str from \"rt\" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`",
"name": "result_type",
"signature": "def result_type(self)"
},
{
"docstring": "Get values of this column from all rows. Ar... | 2 | stack_v2_sparse_classes_30k_test_001587 | Implement the Python class `Column` described below.
Class description:
Manually defined API object.
Method signatures and docstrings:
- def result_type(self): Expose simple attr "rt" as result_type. Notes: Will try to map str from "rt" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`
- def ... | Implement the Python class `Column` described below.
Class description:
Manually defined API object.
Method signatures and docstrings:
- def result_type(self): Expose simple attr "rt" as result_type. Notes: Will try to map str from "rt" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`
- def ... | ca8223facb3797261655645fb4ecba6e13856b5e | <|skeleton|>
class Column:
"""Manually defined API object."""
def result_type(self):
"""Expose simple attr "rt" as result_type. Notes: Will try to map str from "rt" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`"""
<|body_0|>
def get_values(self, attr='value', j... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Column:
"""Manually defined API object."""
def result_type(self):
"""Expose simple attr "rt" as result_type. Notes: Will try to map str from "rt" as int to constants from :attr:`Sensor.API_CONSTANTS`. Returns: :obj:`str`"""
sensor = get_api_all_model()['Sensor']
constants = sensor... | the_stack_v2_python_sparse | pytan3/api_objects/build_objects/7_3_314_3641/rest.py | lifehackjim/pytan3 | train | 4 |
c694576bb2839718080118756bc923ec7e44dab4 | [
"if not Path(Properties.BLACKLIST_FILE).is_file():\n raise BlacklistNotFoundError\ntry:\n with open(Properties.BLACKLIST_FILE, 'r') as csv_file:\n read_csv = csv.reader(csv_file, delimiter=',')\n return BlacklistService.__handle_csv(read_csv, url)\nexcept IOError as e:\n print('IOError in Bla... | <|body_start_0|>
if not Path(Properties.BLACKLIST_FILE).is_file():
raise BlacklistNotFoundError
try:
with open(Properties.BLACKLIST_FILE, 'r') as csv_file:
read_csv = csv.reader(csv_file, delimiter=',')
return BlacklistService.__handle_csv(read_csv... | This class can be used to check if URL's are in the blacklist. | BlacklistService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlacklistService:
"""This class can be used to check if URL's are in the blacklist."""
def in_blacklist(url):
"""Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean"""
<|body_0|>
def __handle_csv(read_csv, url):
... | stack_v2_sparse_classes_75kplus_train_008440 | 1,521 | no_license | [
{
"docstring": "Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean",
"name": "in_blacklist",
"signature": "def in_blacklist(url)"
},
{
"docstring": "Loops through all items in the csv file. If that item is found in the url return True else retu... | 2 | stack_v2_sparse_classes_30k_train_031833 | Implement the Python class `BlacklistService` described below.
Class description:
This class can be used to check if URL's are in the blacklist.
Method signatures and docstrings:
- def in_blacklist(url): Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean
- def __han... | Implement the Python class `BlacklistService` described below.
Class description:
This class can be used to check if URL's are in the blacklist.
Method signatures and docstrings:
- def in_blacklist(url): Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean
- def __han... | 6dcbcf4648bb210e1e95fe8638d5c242532ead8e | <|skeleton|>
class BlacklistService:
"""This class can be used to check if URL's are in the blacklist."""
def in_blacklist(url):
"""Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean"""
<|body_0|>
def __handle_csv(read_csv, url):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlacklistService:
"""This class can be used to check if URL's are in the blacklist."""
def in_blacklist(url):
"""Open the blacklist file and call __handle_csv :param url: the url that has been found :return: Boolean"""
if not Path(Properties.BLACKLIST_FILE).is_file():
raise Bl... | the_stack_v2_python_sparse | app/crawler/blacklist_service.py | Yarince/Crawler-Kruipertje | train | 0 |
7757d1f2f8e4fbd7f0d0e20de8162e8a4df86581 | [
"if dob:\n profile_pic = self.default_profile_pic()\n if social_login:\n profile_pic_url = request.get('profile_pic')\n if profile_pic_url:\n profile_pic = self.generate_profile_pic(profile_pic_url, new_user.id)\n newRequest = request.copy()\n newRequest.__setitem__('dob', dob)\... | <|body_start_0|>
if dob:
profile_pic = self.default_profile_pic()
if social_login:
profile_pic_url = request.get('profile_pic')
if profile_pic_url:
profile_pic = self.generate_profile_pic(profile_pic_url, new_user.id)
newReq... | Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing the default user profile picture. gender: '1' for Male or '0' for Female. | NewUserProfileForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewUserProfileForm:
"""Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing the default user profile picture. gender:... | stack_v2_sparse_classes_75kplus_train_008441 | 12,278 | no_license | [
{
"docstring": "Initializes the profile form object after setting a profile picture, date of birth, and the User object it is associated with. Args: request: The HTTP request object, as passed by django. social_login: Boolean of whether or not social login was used. new_user: User object that was just created. ... | 4 | null | Implement the Python class `NewUserProfileForm` described below.
Class description:
Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing th... | Implement the Python class `NewUserProfileForm` described below.
Class description:
Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing th... | b17f058baffd68f33d41ae0be1ec3cb02976aea6 | <|skeleton|>
class NewUserProfileForm:
"""Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing the default user profile picture. gender:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewUserProfileForm:
"""Sub-class of the ModelForm class based on the User Profile object model. Creates and validates the User Profile form object, and initialized the profile picture if provided. Attributes: profile_pic_tmp: A file IO object representing the default user profile picture. gender: '1' for Male... | the_stack_v2_python_sparse | user_account/NewUserForm.py | varunarora/OC | train | 0 |
1bf6bd18cc46283c432f00b574f013eee2bfc33e | [
"if self.hooked is None:\n self.hooked = {}\nif args_gen is None:\n args_gen = make_args_gen(func)\nif not isinstance(hooks, Sequence):\n hooks = [hooks]\nfor hook_cls in hooks:\n self.hooked[hook_cls] = (func, args_gen)",
"try:\n if self.hooked is not None:\n func, args_gen = self.hooked[ty... | <|body_start_0|>
if self.hooked is None:
self.hooked = {}
if args_gen is None:
args_gen = make_args_gen(func)
if not isinstance(hooks, Sequence):
hooks = [hooks]
for hook_cls in hooks:
self.hooked[hook_cls] = (func, args_gen)
<|end_body_0|>... | Baseclass of something that can be attached to a hook | Hookable | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks: Union[Type['Hook'], Sequence[Type['Hook']]], func: Hooked, args_gen: Optional[ArgsGen]=None) -> None:
"""Register func to be run when any of the hooks are run by parent Args: hooks:... | stack_v2_sparse_classes_75kplus_train_008442 | 7,637 | permissive | [
{
"docstring": "Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should be run on that Hook args_gen: Optionally specify the argument names that should be passed to func. If not given then use func.call_types.ke... | 2 | stack_v2_sparse_classes_30k_train_028422 | Implement the Python class `Hookable` described below.
Class description:
Baseclass of something that can be attached to a hook
Method signatures and docstrings:
- def register_hooked(self, hooks: Union[Type['Hook'], Sequence[Type['Hook']]], func: Hooked, args_gen: Optional[ArgsGen]=None) -> None: Register func to be... | Implement the Python class `Hookable` described below.
Class description:
Baseclass of something that can be attached to a hook
Method signatures and docstrings:
- def register_hooked(self, hooks: Union[Type['Hook'], Sequence[Type['Hook']]], func: Hooked, args_gen: Optional[ArgsGen]=None) -> None: Register func to be... | 408ab2b6fa4e2dd9c6cbc1a415d49688dc6a3df8 | <|skeleton|>
class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks: Union[Type['Hook'], Sequence[Type['Hook']]], func: Hooked, args_gen: Optional[ArgsGen]=None) -> None:
"""Register func to be run when any of the hooks are run by parent Args: hooks:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks: Union[Type['Hook'], Sequence[Type['Hook']]], func: Hooked, args_gen: Optional[ArgsGen]=None) -> None:
"""Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class... | the_stack_v2_python_sparse | malcolm/core/hook.py | dls-controls/pymalcolm | train | 11 |
0ad62148204938c5ab7c9f3f836c6f7bc2f50b2e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosUpdateConfiguration()",
"from .day_of_week import DayOfWeek\nfrom .device_configuration import DeviceConfiguration\nfrom .day_of_week import DayOfWeek\nfrom .device_configuration import DeviceConfiguration\nfields: Dict[str, Callabl... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosUpdateConfiguration()
<|end_body_0|>
<|body_start_1|>
from .day_of_week import DayOfWeek
from .device_configuration import DeviceConfiguration
from .day_of_week import DayOfWe... | IOS Update Configuration, allows you to configure time window within week to install iOS updates | IosUpdateConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based... | stack_v2_sparse_classes_75kplus_train_008443 | 3,544 | 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: IosUpdateConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_052232 | Implement the Python class `IosUpdateConfiguration` described below.
Class description:
IOS Update Configuration, allows you to configure time window within week to install iOS updates
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfigurati... | Implement the Python class `IosUpdateConfiguration` described below.
Class description:
IOS Update Configuration, allows you to configure time window within week to install iOS updates
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfigurati... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IosUpdateConfiguration:
"""IOS Update Configuration, allows you to configure time window within week to install iOS updates"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosUpdateConfiguration:
"""Creates a new instance of the appropriate class based on discrimin... | the_stack_v2_python_sparse | msgraph/generated/models/ios_update_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
7c5e0bbd6029a7205a3272073d6fdf22dea8a335 | [
"cm = self.contents_manager\ncheckpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))\ndata = json.dumps(checkpoints, default=date_default)\nself.finish(data)",
"cm = self.contents_manager\ncheckpoint = (yield gen.maybe_future(cm.create_checkpoint(path)))\ndata = json.dumps(checkpoint, default=date_defau... | <|body_start_0|>
cm = self.contents_manager
checkpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))
data = json.dumps(checkpoints, default=date_default)
self.finish(data)
<|end_body_0|>
<|body_start_1|>
cm = self.contents_manager
checkpoint = (yield gen.maybe_f... | CheckpointsHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
<|body_0|>
def post(self, path=''):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cm = self.contents_manager
checkpoints = ... | stack_v2_sparse_classes_75kplus_train_008444 | 11,073 | permissive | [
{
"docstring": "get lists checkpoints for a file",
"name": "get",
"signature": "def get(self, path='')"
},
{
"docstring": "post creates a new checkpoint",
"name": "post",
"signature": "def post(self, path='')"
}
] | 2 | stack_v2_sparse_classes_30k_val_000281 | Implement the Python class `CheckpointsHandler` described below.
Class description:
Implement the CheckpointsHandler class.
Method signatures and docstrings:
- def get(self, path=''): get lists checkpoints for a file
- def post(self, path=''): post creates a new checkpoint | Implement the Python class `CheckpointsHandler` described below.
Class description:
Implement the CheckpointsHandler class.
Method signatures and docstrings:
- def get(self, path=''): get lists checkpoints for a file
- def post(self, path=''): post creates a new checkpoint
<|skeleton|>
class CheckpointsHandler:
... | 1ad7ec05fb1e3676ac879585296c513c3ee50ef9 | <|skeleton|>
class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
<|body_0|>
def post(self, path=''):
"""post creates a new checkpoint"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckpointsHandler:
def get(self, path=''):
"""get lists checkpoints for a file"""
cm = self.contents_manager
checkpoints = (yield gen.maybe_future(cm.list_checkpoints(path)))
data = json.dumps(checkpoints, default=date_default)
self.finish(data)
def post(self, pat... | the_stack_v2_python_sparse | Library/lib/python3.7/site-packages/notebook/services/contents/handlers.py | holzschu/Carnets | train | 541 | |
10b495305589c1b81e6d03cf1545a373582f1cec | [
"self.psi_ = psi\nself.xi_ = xi\nself.gamma_ = gamma\nself.mu_latency_ = 0.0\nself.mu_variance_ = 0.0\nself.mu_control_ = 1.0\nself.model_ = AdaptiveFilter(p, q, alpha)\nself.l_hat_ = self.model_.Predict()",
"self.model_.Update(l, self.l_hat_)\nself.mu_latency_ = (1.0 - self.gamma_) * l + self.gamma_ * self.mu_la... | <|body_start_0|>
self.psi_ = psi
self.xi_ = xi
self.gamma_ = gamma
self.mu_latency_ = 0.0
self.mu_variance_ = 0.0
self.mu_control_ = 1.0
self.model_ = AdaptiveFilter(p, q, alpha)
self.l_hat_ = self.model_.Predict()
<|end_body_0|>
<|body_start_1|>
... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def __init__(self, psi, xi, gamma, p, q, alpha):
"""Constructor."""
<|body_0|>
def Process(self, l, r=None):
"""Process a new latency/control pair. Two steps: (1) updates internal model, and (2) computes optimal control."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_008445 | 2,871 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, psi, xi, gamma, p, q, alpha)"
},
{
"docstring": "Process a new latency/control pair. Two steps: (1) updates internal model, and (2) computes optimal control.",
"name": "Process",
"signature": "def Process... | 2 | null | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self, psi, xi, gamma, p, q, alpha): Constructor.
- def Process(self, l, r=None): Process a new latency/control pair. Two steps: (1) updates internal model, and (... | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self, psi, xi, gamma, p, q, alpha): Constructor.
- def Process(self, l, r=None): Process a new latency/control pair. Two steps: (1) updates internal model, and (... | fea13bb5ea3464945022f2b883f1ccae70b0caa4 | <|skeleton|>
class Controller:
def __init__(self, psi, xi, gamma, p, q, alpha):
"""Constructor."""
<|body_0|>
def Process(self, l, r=None):
"""Process a new latency/control pair. Two steps: (1) updates internal model, and (2) computes optimal control."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def __init__(self, psi, xi, gamma, p, q, alpha):
"""Constructor."""
self.psi_ = psi
self.xi_ = xi
self.gamma_ = gamma
self.mu_latency_ = 0.0
self.mu_variance_ = 0.0
self.mu_control_ = 1.0
self.model_ = AdaptiveFilter(p, q, alpha)
... | the_stack_v2_python_sparse | Revision_Spring2017/python/controller.py | chapmanmp/NetworkControl | train | 0 | |
f1614b9d5702c7f7b8845016dbff547c4e6649cf | [
"url = self.action\nif url is None:\n return {}\nhalves = url.split('?')\nif len(halves) == 1:\n return {}\nkey_value_pairs = halves[1].split('&')\nreturn dict([pair.split('=') for pair in key_value_pairs])",
"url = self.action\nif url is None:\n return None\nprotocol_and_host = url.split('?')[0]\nhost =... | <|body_start_0|>
url = self.action
if url is None:
return {}
halves = url.split('?')
if len(halves) == 1:
return {}
key_value_pairs = halves[1].split('&')
return dict([pair.split('=') for pair in key_value_pairs])
<|end_body_0|>
<|body_start_1|>
... | Custom element class for <a:hlinkClick> elements. | CT_Hyperlink | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Hyperlink:
"""Custom element class for <a:hlinkClick> elements."""
def action_fields(self):
"""A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For example `{'id':'0', 'return':'true'}` in 'ppaction://custom... | stack_v2_sparse_classes_75kplus_train_008446 | 1,603 | permissive | [
{
"docstring": "A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For example `{'id':'0', 'return':'true'}` in 'ppaction://customshow?id=0&return=true'. Returns an empty dictionary if the URL contains no query string or if no action attrib... | 2 | stack_v2_sparse_classes_30k_train_032887 | Implement the Python class `CT_Hyperlink` described below.
Class description:
Custom element class for <a:hlinkClick> elements.
Method signatures and docstrings:
- def action_fields(self): A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For ex... | Implement the Python class `CT_Hyperlink` described below.
Class description:
Custom element class for <a:hlinkClick> elements.
Method signatures and docstrings:
- def action_fields(self): A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For ex... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_Hyperlink:
"""Custom element class for <a:hlinkClick> elements."""
def action_fields(self):
"""A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For example `{'id':'0', 'return':'true'}` in 'ppaction://custom... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CT_Hyperlink:
"""Custom element class for <a:hlinkClick> elements."""
def action_fields(self):
"""A dictionary containing any key-value pairs present in the query portion of the `ppaction://` URL in the action attribute. For example `{'id':'0', 'return':'true'}` in 'ppaction://customshow?id=0&ret... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/action.py | ryfeus/lambda-packs | train | 1,283 |
e1fb48ad6c99e4875eacb656070cdb520fe327f7 | [
"template_values = {}\ntemplate_values['page_title'] = handler.format_title('Local Chapters')\ncontent = safe_dom.NodeList()\ncontent.append(safe_dom.Element('a', id='add_local_chapter', className='gcb-button gcb-pull-right', role='button', href='%s?action=add_local_chapter' % handler.LINK_URL).add_text('Add Local ... | <|body_start_0|>
template_values = {}
template_values['page_title'] = handler.format_title('Local Chapters')
content = safe_dom.NodeList()
content.append(safe_dom.Element('a', id='add_local_chapter', className='gcb-button gcb-pull-right', role='button', href='%s?action=add_local_chapter'... | LocalChapterBaseAdminHandler | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
<|body_0|>
def get_add_local_chapter(self, handler):
"""Handles 'get_add_local_chapter' action and renders new course entry editor.""... | stack_v2_sparse_classes_75kplus_train_008447 | 20,021 | permissive | [
{
"docstring": "Shows a list of all local chapters available on this site.",
"name": "get_local_chapters",
"signature": "def get_local_chapters(self, handler)"
},
{
"docstring": "Handles 'get_add_local_chapter' action and renders new course entry editor.",
"name": "get_add_local_chapter",
... | 4 | stack_v2_sparse_classes_30k_train_006749 | Implement the Python class `LocalChapterBaseAdminHandler` described below.
Class description:
Implement the LocalChapterBaseAdminHandler class.
Method signatures and docstrings:
- def get_local_chapters(self, handler): Shows a list of all local chapters available on this site.
- def get_add_local_chapter(self, handle... | Implement the Python class `LocalChapterBaseAdminHandler` described below.
Class description:
Implement the LocalChapterBaseAdminHandler class.
Method signatures and docstrings:
- def get_local_chapters(self, handler): Shows a list of all local chapters available on this site.
- def get_add_local_chapter(self, handle... | 2bca9d64499e160b2da9bed6e97fcda712feec72 | <|skeleton|>
class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
<|body_0|>
def get_add_local_chapter(self, handler):
"""Handles 'get_add_local_chapter' action and renders new course entry editor.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalChapterBaseAdminHandler:
def get_local_chapters(self, handler):
"""Shows a list of all local chapters available on this site."""
template_values = {}
template_values['page_title'] = handler.format_title('Local Chapters')
content = safe_dom.NodeList()
content.append... | the_stack_v2_python_sparse | coursebuilder/modules/local_chapter/local_chapter.py | RavinderSinghPB/seek | train | 0 | |
debaafab0e69bbf929d414e99998423db3c60d34 | [
"self.__check_figsize()\nallowed_n_ratio_panels = [0, 1, 2, 3]\nif self.n_ratio_panels not in allowed_n_ratio_panels:\n raise ValueError(f'{self.n_ratio_panels} not allwed value for `n_ratio_panels`. Allowed are {allowed_n_ratio_panels}')\nself.__check_yratio(self.ymin_ratio)\nself.ymin_ratio = [None] * self.n_r... | <|body_start_0|>
self.__check_figsize()
allowed_n_ratio_panels = [0, 1, 2, 3]
if self.n_ratio_panels not in allowed_n_ratio_panels:
raise ValueError(f'{self.n_ratio_panels} not allwed value for `n_ratio_panels`. Allowed are {allowed_n_ratio_panels}')
self.__check_yratio(self.... | Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional Minimum value of the x-axis, by default None xmax : float, optional Maximum va... | PlotObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotObject:
"""Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional Minimum value of the x-axis, by default ... | stack_v2_sparse_classes_75kplus_train_008448 | 27,616 | permissive | [
{
"docstring": "Check for allowed values. Raises ------ ValueError If n_ratio_panels not in [0, 1, 2, 3]",
"name": "__post_init__",
"signature": "def __post_init__(self)"
},
{
"docstring": "Check `figsize`. Raises ------ ValueError If shape of `figsize` is not a tuple or list with length 2",
... | 3 | stack_v2_sparse_classes_30k_train_025473 | Implement the Python class `PlotObject` described below.
Class description:
Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional M... | Implement the Python class `PlotObject` described below.
Class description:
Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional M... | 1ea02ba4a10df7c27b639d40c33cd24801b8d72c | <|skeleton|>
class PlotObject:
"""Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional Minimum value of the x-axis, by default ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotObject:
"""Data base class defining properties of a plot object. Parameters ---------- title : str, optional Title of the plot, by default "" draw_errors : bool, optional Draw statistical uncertainty on the lines, by default True xmin : float, optional Minimum value of the x-axis, by default None xmax : f... | the_stack_v2_python_sparse | puma/plot_base.py | umami-hep/puma | train | 3 |
c24a8a62f0be9ef21da40a74873c7cf08a57ecb6 | [
"super().__init__(attacker, defender, enemy=enemy)\nself._move_file_name = join('moves', 'ice_beam.png')\nself._fps = 20\nif enemy:\n self._particle_systems = [MoveLinearParticleSystem(self._move_file_name, 1, (140, 70), 60, dx=-4, dy=2, duration=1), MoveLinearParticleSystem(self._move_file_name, 1, (140, 40), 6... | <|body_start_0|>
super().__init__(attacker, defender, enemy=enemy)
self._move_file_name = join('moves', 'ice_beam.png')
self._fps = 20
if enemy:
self._particle_systems = [MoveLinearParticleSystem(self._move_file_name, 1, (140, 70), 60, dx=-4, dy=2, duration=1), MoveLinearPart... | IceBeam | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IceBeam:
def __init__(self, attacker, defender, enemy=False):
"""Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear path towards the opponent. The player jiggles and is tinted while it is getting hit by the beam. T... | stack_v2_sparse_classes_75kplus_train_008449 | 4,101 | no_license | [
{
"docstring": "Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear path towards the opponent. The player jiggles and is tinted while it is getting hit by the beam. The tint expires at the end of the move. Ice shards are played after the b... | 3 | stack_v2_sparse_classes_30k_train_002992 | Implement the Python class `IceBeam` described below.
Class description:
Implement the IceBeam class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear pa... | Implement the Python class `IceBeam` described below.
Class description:
Implement the IceBeam class.
Method signatures and docstrings:
- def __init__(self, attacker, defender, enemy=False): Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear pa... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class IceBeam:
def __init__(self, attacker, defender, enemy=False):
"""Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear path towards the opponent. The player jiggles and is tinted while it is getting hit by the beam. T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IceBeam:
def __init__(self, attacker, defender, enemy=False):
"""Displays the ice beam animation. This animation consists of two particle systems that generate crystals that follow a linear path towards the opponent. The player jiggles and is tinted while it is getting hit by the beam. The tint expire... | the_stack_v2_python_sparse | pokered/modules/animations/moves/ice_beam.py | surranc20/pokered | train | 44 | |
39ed31710527e4cb6d1e2916edde305b54fb4a2f | [
"if not strs:\n return ''\nret = []\nret.append(str(len(strs)))\nfor v in strs:\n ret.append(str(len(v)))\ns = ''.join(strs)\nret.append(s)\nreturn ','.join(ret)",
"if not s:\n return []\nl = s.split(',')\nlength = int(l[0])\ns = ','.join(l[length + 1:])\nret = []\nj = 0\nfor i in range(1, length + 1):\n... | <|body_start_0|>
if not strs:
return ''
ret = []
ret.append(str(len(strs)))
for v in strs:
ret.append(str(len(v)))
s = ''.join(strs)
ret.append(s)
return ','.join(ret)
<|end_body_0|>
<|body_start_1|>
if not s:
return []... | 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_008450 | 1,579 | 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 | null | 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... | 9eb44afa4233fdedc2e5c72be0fdf54b25d1c45c | <|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"""
if not strs:
return ''
ret = []
ret.append(str(len(strs)))
for v in strs:
ret.append(str(len(v)))
s = ''.join(strs)
... | the_stack_v2_python_sparse | Google/Pro271.Encode and decode Strings.py | YoyinZyc/Leetcode_Python | train | 0 | |
bc3b2a874562d736bd19833bd1697389a7d44ed0 | [
"as_id_int = as_ids.parse(as_id)\nas_ = super().create(isd=isd, as_id=as_id, as_id_int=as_id_int, is_core=is_core, label=label, mtu=mtu or DEFAULT_LINK_MTU, owner=owner, master_as_key=AS._make_master_as_key())\nas_.generate_keys()\nif init_certificates:\n as_.generate_certs()\n if is_core:\n isd.trcs.c... | <|body_start_0|>
as_id_int = as_ids.parse(as_id)
as_ = super().create(isd=isd, as_id=as_id, as_id_int=as_id_int, is_core=is_core, label=label, mtu=mtu or DEFAULT_LINK_MTU, owner=owner, master_as_key=AS._make_master_as_key())
as_.generate_keys()
if init_certificates:
as_.gener... | ASManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASManager:
def create(self, isd, as_id, is_core=False, label=None, mtu=None, owner=None, init_certificates=True):
"""Create the AS and initialise the required keys :param ISD isd: :param str as_id: valid AS-identifier string :param bool is_core: should this AS be created as a core AS? :p... | stack_v2_sparse_classes_75kplus_train_008451 | 44,235 | permissive | [
{
"docstring": "Create the AS and initialise the required keys :param ISD isd: :param str as_id: valid AS-identifier string :param bool is_core: should this AS be created as a core AS? :param str label: optional :param User owner: optional :returns: AS",
"name": "create",
"signature": "def create(self, ... | 3 | stack_v2_sparse_classes_30k_train_045986 | Implement the Python class `ASManager` described below.
Class description:
Implement the ASManager class.
Method signatures and docstrings:
- def create(self, isd, as_id, is_core=False, label=None, mtu=None, owner=None, init_certificates=True): Create the AS and initialise the required keys :param ISD isd: :param str... | Implement the Python class `ASManager` described below.
Class description:
Implement the ASManager class.
Method signatures and docstrings:
- def create(self, isd, as_id, is_core=False, label=None, mtu=None, owner=None, init_certificates=True): Create the AS and initialise the required keys :param ISD isd: :param str... | baa026d2e48217e66a01f567e19caf4fb5db9306 | <|skeleton|>
class ASManager:
def create(self, isd, as_id, is_core=False, label=None, mtu=None, owner=None, init_certificates=True):
"""Create the AS and initialise the required keys :param ISD isd: :param str as_id: valid AS-identifier string :param bool is_core: should this AS be created as a core AS? :p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ASManager:
def create(self, isd, as_id, is_core=False, label=None, mtu=None, owner=None, init_certificates=True):
"""Create the AS and initialise the required keys :param ISD isd: :param str as_id: valid AS-identifier string :param bool is_core: should this AS be created as a core AS? :param str label... | the_stack_v2_python_sparse | scionlab/models/core.py | netsec-ethz/scionlab | train | 10 | |
363d98977eb21870e185d95bc82415560fc99f2e | [
"now = timezone.now()\nperiod = timedelta(days=200)\nreturn pytz.timezone('UTC').localize(datetime.fromordinal(random.randrange((now - period).toordinal(), (now + period).toordinal())))",
"if not self.start:\n return None\nperiod = timedelta(days=90)\nreturn pytz.timezone('UTC').localize(datetime.fromordinal(r... | <|body_start_0|>
now = timezone.now()
period = timedelta(days=200)
return pytz.timezone('UTC').localize(datetime.fromordinal(random.randrange((now - period).toordinal(), (now + period).toordinal())))
<|end_body_0|>
<|body_start_1|>
if not self.start:
return None
peri... | A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end | CourseRunFactory | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseRunFactory:
"""A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end"""
def start(self):
"""A start datet... | stack_v2_sparse_classes_75kplus_train_008452 | 13,829 | permissive | [
{
"docstring": "A start datetime for the course run is chosen randomly in the future (it can of course be forced if we want something else), then the other significant dates for the course run are chosen randomly in periods that make sense with this start date.",
"name": "start",
"signature": "def start... | 4 | null | Implement the Python class `CourseRunFactory` described below.
Class description:
A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end
Method si... | Implement the Python class `CourseRunFactory` described below.
Class description:
A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end
Method si... | b0b04d0ffc0b16f2f1b8a8201418b8f86941e45f | <|skeleton|>
class CourseRunFactory:
"""A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end"""
def start(self):
"""A start datet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CourseRunFactory:
"""A factory to automatically generate random yet meaningful course runs in our tests. Random dates are proposed realistically so that: - now <= start - enrollment_start <= start <= end - enrollment_start <= enrollment_end <= end"""
def start(self):
"""A start datetime for the c... | the_stack_v2_python_sparse | src/richie/apps/courses/factories.py | lunika/richie | train | 0 |
6a0a0783428edc8dca7a1a5f1b7346a6c8d1cfe9 | [
"self.sums = []\nfor weight in w:\n if not self.sums:\n self.sums.append(weight)\n else:\n self.sums.append(weight + self.sums[-1])",
"import bisect\npick = random.uniform(0, self.sums[-1])\nreturn bisect.bisect_left(self.sums, pick)"
] | <|body_start_0|>
self.sums = []
for weight in w:
if not self.sums:
self.sums.append(weight)
else:
self.sums.append(weight + self.sums[-1])
<|end_body_0|>
<|body_start_1|>
import bisect
pick = random.uniform(0, self.sums[-1])
... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def __init__(self, w):
""":type w: List[int] 176ms"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sums = []
for weight in w:
if not self.sums:
se... | stack_v2_sparse_classes_75kplus_train_008453 | 1,901 | no_license | [
{
"docstring": ":type w: List[int] 176ms",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020371 | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int] 176ms
- def pickIndex(self): :rtype: int | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int] 176ms
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution_1:
def __init__(self, w):
""":type w: List[int] 1... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution_1:
def __init__(self, w):
""":type w: List[int] 176ms"""
<|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_1:
def __init__(self, w):
""":type w: List[int] 176ms"""
self.sums = []
for weight in w:
if not self.sums:
self.sums.append(weight)
else:
self.sums.append(weight + self.sums[-1])
def pickIndex(self):
""":rtyp... | the_stack_v2_python_sparse | RandomPickWithWeight_MID_880.py | 953250587/leetcode-python | train | 2 | |
90905294553bbd626b7c32c00ee26f87b434e9e9 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1112')\nurl_one = 'http://datamechanics.io/data/aoconno8_dmak1112/hubway_travel_Jan-Oct.csv'\ndf = pd.read_csv(url_one)\nurl_two = 'http://datamechanics.io/data/aoconno8... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1112')
url_one = 'http://datamechanics.io/data/aoconno8_dmak1112/hubway_travel_Jan-Oct.csv'
df = pd.read_csv(url... | hubwayTravel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hubwayTravel:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_75kplus_train_008454 | 4,261 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `hubwayTravel` described below.
Class description:
Implement the hubwayTravel class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `hubwayTravel` described below.
Class description:
Implement the hubwayTravel class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class hubwayTravel:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class hubwayTravel:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aoconno8_dmak1112', 'aoconno8_dmak1112... | the_stack_v2_python_sparse | aoconno8_dmak1112/hubwayTravel.py | dwang1995/course-2018-spr-proj | train | 1 | |
f10793ecf65eeebba817334559286fe570ff718e | [
"self.deq = deque([])\nself.dic = {}\nself.cap = capacity",
"try:\n val = self.dic[key]\n self.deq.remove(key)\n self.deq.append(key)\n return val\nexcept:\n return -1",
"try:\n self.deq.remove(key)\nexcept:\n None\nself.deq.append(key)\nself.dic[key] = value\nif len(self.dic) > self.cap:\n... | <|body_start_0|>
self.deq = deque([])
self.dic = {}
self.cap = capacity
<|end_body_0|>
<|body_start_1|>
try:
val = self.dic[key]
self.deq.remove(key)
self.deq.append(key)
return val
except:
return -1
<|end_body_1|>
<|b... | LRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_008455 | 2,603 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | ffe317f9a984319fbb3c1811e2a438306fc4eee9 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.deq = deque([])
self.dic = {}
self.cap = capacity
def get(self, key):
""":rtype: int"""
try:
val = self.dic[key]
self.deq.remove(key)
self.deq.append(... | the_stack_v2_python_sparse | LeetCode/02_Medium/lc_146.py | zubie7a/Algorithms | train | 10 | |
8b1159cb29470d867be373ce3a8f792cea81a948 | [
"env = build_environment()\nsuper().__init__(env)\nself._rebuild_environment = build_environment\nself._reset = False",
"if self._reset:\n self._env.close()\n self._env = self._rebuild_environment()\nelse:\n self._reset = True\nreturn super().reset()"
] | <|body_start_0|>
env = build_environment()
super().__init__(env)
self._rebuild_environment = build_environment
self._reset = False
<|end_body_0|>
<|body_start_1|>
if self._reset:
self._env.close()
self._env = self._rebuild_environment()
else:
... | Wrapper that rebuilds the environment on reset. | ResetWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetWrapper:
"""Wrapper that rebuilds the environment on reset."""
def __init__(self, build_environment: Callable[[], dmlab2d.Environment]):
"""Initializes the object. Args: build_environment: Called to build the underlying environment."""
<|body_0|>
def reset(self) -> ... | stack_v2_sparse_classes_75kplus_train_008456 | 1,516 | permissive | [
{
"docstring": "Initializes the object. Args: build_environment: Called to build the underlying environment.",
"name": "__init__",
"signature": "def __init__(self, build_environment: Callable[[], dmlab2d.Environment])"
},
{
"docstring": "Rebuilds the environment and calls reset on it.",
"nam... | 2 | null | Implement the Python class `ResetWrapper` described below.
Class description:
Wrapper that rebuilds the environment on reset.
Method signatures and docstrings:
- def __init__(self, build_environment: Callable[[], dmlab2d.Environment]): Initializes the object. Args: build_environment: Called to build the underlying en... | Implement the Python class `ResetWrapper` described below.
Class description:
Wrapper that rebuilds the environment on reset.
Method signatures and docstrings:
- def __init__(self, build_environment: Callable[[], dmlab2d.Environment]): Initializes the object. Args: build_environment: Called to build the underlying en... | e42b916b32771f7af5ad4eccbdf4ded410735299 | <|skeleton|>
class ResetWrapper:
"""Wrapper that rebuilds the environment on reset."""
def __init__(self, build_environment: Callable[[], dmlab2d.Environment]):
"""Initializes the object. Args: build_environment: Called to build the underlying environment."""
<|body_0|>
def reset(self) -> ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetWrapper:
"""Wrapper that rebuilds the environment on reset."""
def __init__(self, build_environment: Callable[[], dmlab2d.Environment]):
"""Initializes the object. Args: build_environment: Called to build the underlying environment."""
env = build_environment()
super().__init... | the_stack_v2_python_sparse | meltingpot/python/utils/substrates/wrappers/reset_wrapper.py | classicvalues/meltingpot | train | 0 |
a8cf61280870976c63495ff6eec51123d99177ca | [
"self.days_to_keep = days_to_keep\nself.scheduling_policy = scheduling_policy\nself.worm_retention_type = worm_retention_type",
"if dictionary is None:\n return None\ndays_to_keep = dictionary.get('daysToKeep')\nscheduling_policy = cohesity_management_sdk.models.scheduling_policy.SchedulingPolicy.from_dictiona... | <|body_start_0|>
self.days_to_keep = days_to_keep
self.scheduling_policy = scheduling_policy
self.worm_retention_type = worm_retention_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
days_to_keep = dictionary.get('daysToKeep')
scheduli... | Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specifies how many days to retain Snapshots on the Co... | DataMigrationPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specif... | stack_v2_sparse_classes_75kplus_train_008457 | 2,842 | permissive | [
{
"docstring": "Constructor for the DataMigrationPolicy class",
"name": "__init__",
"signature": "def __init__(self, days_to_keep=None, scheduling_policy=None, worm_retention_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti... | 2 | stack_v2_sparse_classes_30k_train_031382 | Implement the Python class `DataMigrationPolicy` described below.
Class description:
Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attr... | Implement the Python class `DataMigrationPolicy` described below.
Class description:
Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attr... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specifies how many ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/data_migration_policy.py | cohesity/management-sdk-python | train | 24 |
303c776052c0b91d7d0ac2e925450e5af5b35673 | [
"ann = None\nbackend = config.get('backend', 'faiss')\nif backend == 'annoy':\n ann = Annoy(config)\nelif backend == 'faiss':\n ann = Faiss(config)\nelif backend == 'hnsw':\n ann = HNSW(config)\nelif backend == 'numpy':\n ann = NumPy(config)\nelif backend == 'torch':\n ann = Torch(config)\nelse:\n ... | <|body_start_0|>
ann = None
backend = config.get('backend', 'faiss')
if backend == 'annoy':
ann = Annoy(config)
elif backend == 'faiss':
ann = Faiss(config)
elif backend == 'hnsw':
ann = HNSW(config)
elif backend == 'numpy':
... | Methods to create ANN indexes. | ANNFactory | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ANNFactory:
"""Methods to create ANN indexes."""
def create(config):
"""Create an ANN. Args: config: index configuration parameters Returns: ANN"""
<|body_0|>
def resolve(backend, config):
"""Attempt to resolve a custom backend. Args: backend: backend class confi... | stack_v2_sparse_classes_75kplus_train_008458 | 1,467 | permissive | [
{
"docstring": "Create an ANN. Args: config: index configuration parameters Returns: ANN",
"name": "create",
"signature": "def create(config)"
},
{
"docstring": "Attempt to resolve a custom backend. Args: backend: backend class config: index configuration parameters Returns: ANN",
"name": "r... | 2 | null | Implement the Python class `ANNFactory` described below.
Class description:
Methods to create ANN indexes.
Method signatures and docstrings:
- def create(config): Create an ANN. Args: config: index configuration parameters Returns: ANN
- def resolve(backend, config): Attempt to resolve a custom backend. Args: backend... | Implement the Python class `ANNFactory` described below.
Class description:
Methods to create ANN indexes.
Method signatures and docstrings:
- def create(config): Create an ANN. Args: config: index configuration parameters Returns: ANN
- def resolve(backend, config): Attempt to resolve a custom backend. Args: backend... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class ANNFactory:
"""Methods to create ANN indexes."""
def create(config):
"""Create an ANN. Args: config: index configuration parameters Returns: ANN"""
<|body_0|>
def resolve(backend, config):
"""Attempt to resolve a custom backend. Args: backend: backend class confi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ANNFactory:
"""Methods to create ANN indexes."""
def create(config):
"""Create an ANN. Args: config: index configuration parameters Returns: ANN"""
ann = None
backend = config.get('backend', 'faiss')
if backend == 'annoy':
ann = Annoy(config)
elif backe... | the_stack_v2_python_sparse | src/python/txtai/ann/factory.py | neuml/txtai | train | 4,804 |
9a03ac5fb50f7ae782072317511b6c0db81910fd | [
"if self == self.HIGH_PRIORITY:\n return 'HighPriority'\nelse:\n return 'OracleResponse'",
"if name == 'HighPriority':\n return cls.HIGH_PRIORITY\nelse:\n return cls.ORACLE_RESPONSE"
] | <|body_start_0|>
if self == self.HIGH_PRIORITY:
return 'HighPriority'
else:
return 'OracleResponse'
<|end_body_0|>
<|body_start_1|>
if name == 'HighPriority':
return cls.HIGH_PRIORITY
else:
return cls.ORACLE_RESPONSE
<|end_body_1|>
| TransactionAttributeType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionAttributeType:
def to_csharp_name(self) -> str:
"""Internal helper to match C# convention"""
<|body_0|>
def from_csharp_name(cls, name: str):
"""Internal helper to parse from C# convention"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_008459 | 18,878 | permissive | [
{
"docstring": "Internal helper to match C# convention",
"name": "to_csharp_name",
"signature": "def to_csharp_name(self) -> str"
},
{
"docstring": "Internal helper to parse from C# convention",
"name": "from_csharp_name",
"signature": "def from_csharp_name(cls, name: str)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002289 | Implement the Python class `TransactionAttributeType` described below.
Class description:
Implement the TransactionAttributeType class.
Method signatures and docstrings:
- def to_csharp_name(self) -> str: Internal helper to match C# convention
- def from_csharp_name(cls, name: str): Internal helper to parse from C# c... | Implement the Python class `TransactionAttributeType` described below.
Class description:
Implement the TransactionAttributeType class.
Method signatures and docstrings:
- def to_csharp_name(self) -> str: Internal helper to match C# convention
- def from_csharp_name(cls, name: str): Internal helper to parse from C# c... | 48eb623318f228ebafe075456a8487abb2ee11f9 | <|skeleton|>
class TransactionAttributeType:
def to_csharp_name(self) -> str:
"""Internal helper to match C# convention"""
<|body_0|>
def from_csharp_name(cls, name: str):
"""Internal helper to parse from C# convention"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionAttributeType:
def to_csharp_name(self) -> str:
"""Internal helper to match C# convention"""
if self == self.HIGH_PRIORITY:
return 'HighPriority'
else:
return 'OracleResponse'
def from_csharp_name(cls, name: str):
"""Internal helper to pa... | the_stack_v2_python_sparse | neo3/network/payloads/transaction.py | baronrustamov/neo-mamba | train | 0 | |
d31369904976a46d33cc6cdafe5ad1d2aaea6826 | [
"assert payoff_matrix.ndim == 3\nassert payoff_matrix.shape[0] == 2\nassert np.allclose(payoff_matrix[0], payoff_matrix[1].T)\nself.payoff_matrix = payoff_matrix[0]\nself.dynamics = dynamics",
"state = np.array(state)\nassert state.ndim == 1\nassert state.shape[0] == self.payoff_matrix.shape[0]\nfitness = np.matm... | <|body_start_0|>
assert payoff_matrix.ndim == 3
assert payoff_matrix.shape[0] == 2
assert np.allclose(payoff_matrix[0], payoff_matrix[1].T)
self.payoff_matrix = payoff_matrix[0]
self.dynamics = dynamics
<|end_body_0|>
<|body_start_1|>
state = np.array(state)
asse... | Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. dynamics: A callback function that returns the time-d... | SinglePopulationDynamics | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePopulationDynamics:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. d... | stack_v2_sparse_classes_75kplus_train_008460 | 6,793 | permissive | [
{
"docstring": "Initializes the single-population dynamics.",
"name": "__init__",
"signature": "def __init__(self, payoff_matrix, dynamics)"
},
{
"docstring": "Time derivative of the population state. Args: state: Probability distribution as list or `numpy.ndarray(shape=num_strategies)`. time: T... | 2 | stack_v2_sparse_classes_30k_train_026737 | Implement the Python class `SinglePopulationDynamics` described below.
Class description:
Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player.... | Implement the Python class `SinglePopulationDynamics` described below.
Class description:
Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player.... | 6f3551fd990053cf2287b380fb9ad0b2a2607c18 | <|skeleton|>
class SinglePopulationDynamics:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SinglePopulationDynamics:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. dynamics: A ca... | the_stack_v2_python_sparse | open_spiel/python/egt/dynamics.py | sarahperrin/open_spiel | train | 3 |
d5afd09b62b77d494b22d363aa55425c7b72fbc7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsMobileMSI()",
"from .mobile_lob_app import MobileLobApp\nfrom .mobile_lob_app import MobileLobApp\nfields: Dict[str, Callable[[Any], None]] = {'commandLine': lambda n: setattr(self, 'command_line', n.get_str_value()), 'ignoreVer... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WindowsMobileMSI()
<|end_body_0|>
<|body_start_1|>
from .mobile_lob_app import MobileLobApp
from .mobile_lob_app import MobileLobApp
fields: Dict[str, Callable[[Any], None]] = {'... | Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps. | WindowsMobileMSI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsMobileMSI:
"""Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMobileMSI:
"""Creates a new instance of the appropriate class based on discriminator ... | stack_v2_sparse_classes_75kplus_train_008461 | 3,140 | 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: WindowsMobileMSI",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `WindowsMobileMSI` described below.
Class description:
Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMobileMSI: Creates a new ... | Implement the Python class `WindowsMobileMSI` described below.
Class description:
Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMobileMSI: Creates a new ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsMobileMSI:
"""Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMobileMSI:
"""Creates a new instance of the appropriate class based on discriminator ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WindowsMobileMSI:
"""Contains properties and inherited properties for Windows Mobile MSI Line Of Business apps."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMobileMSI:
"""Creates a new instance of the appropriate class based on discriminator value Args: p... | the_stack_v2_python_sparse | msgraph/generated/models/windows_mobile_m_s_i.py | microsoftgraph/msgraph-sdk-python | train | 135 |
fb227c39a5d73efa4612140ffb3439ed9edebc46 | [
"def f(*args, **kwargs):\n if_return_trans = module.return_transform\n if_return_label = module.return_label\n module.return_transform = False\n module.return_label = False\n out = module(*args, **kwargs)\n module.return_transform = if_return_trans\n module.return_label = if_return_label\n r... | <|body_start_0|>
def f(*args, **kwargs):
if_return_trans = module.return_transform
if_return_label = module.return_label
module.return_transform = False
module.return_label = False
out = module(*args, **kwargs)
module.return_transform = if_... | Apply and inverse transformations for mask tensors. | MaskApplyInverse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
<|body_0|>
def app... | stack_v2_sparse_classes_75kplus_train_008462 | 14,443 | permissive | [
{
"docstring": "Disable all other additional inputs (e.g. ) for ImageSequential.",
"name": "make_input_only_sequential",
"signature": "def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable"
},
{
"docstring": "Apply a transformation with respect ... | 3 | stack_v2_sparse_classes_30k_test_001418 | Implement the Python class `MaskApplyInverse` described below.
Class description:
Apply and inverse transformations for mask tensors.
Method signatures and docstrings:
- def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable: Disable all other additional inputs (e.g. ... | Implement the Python class `MaskApplyInverse` described below.
Class description:
Apply and inverse transformations for mask tensors.
Method signatures and docstrings:
- def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable: Disable all other additional inputs (e.g. ... | 0aa7a7110872f610f3947eccc4a35f0f0c7d79bd | <|skeleton|>
class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
<|body_0|>
def app... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.container.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
def f(*args, **kwargs):
... | the_stack_v2_python_sparse | kornia/augmentation/container/utils.py | ducha-aiki/kornia | train | 3 |
c3b2635fbaa08ff2f6ec66a10ebc1e781c8ad05d | [
"resNode = ListNode(0)\nmove = resNode\nreslist = []\nwhile head:\n reslist.append(head.val)\n head = head.next\nreslist.reverse()\nfor i in reslist:\n move.next = ListNode(i)\n move = move.next\nreturn resNode.next",
"if not head:\n return head\nstack = []\nwhile head:\n stack.append(head.val)\... | <|body_start_0|>
resNode = ListNode(0)
move = resNode
reslist = []
while head:
reslist.append(head.val)
head = head.next
reslist.reverse()
for i in reslist:
move.next = ListNode(i)
move = move.next
return resNode.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
<|body_0|>
def reverseList(self, hea... | stack_v2_sparse_classes_75kplus_train_008463 | 4,109 | no_license | [
{
"docstring": "最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_051227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
<|body_0|>
def reverseList(self, hea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
resNode = ListNode(0)
move = resNode
re... | the_stack_v2_python_sparse | LeetCode_practice/LinkedList/0206.ReverseLinkedList.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
9810f110f3647afc115629e29615433696d05d52 | [
"code = '{country_alpha2}-{subdivision_code}'.format(country_alpha2=country_alpha2, subdivision_code=subdivision_code)\ntry:\n if subdivisions.get(code=code) is None:\n abort(400, 'Bad request: country_alpha2 and subdivision_code are invalid')\nexcept KeyError:\n abort(400, 'Bad request: country_alpha2... | <|body_start_0|>
code = '{country_alpha2}-{subdivision_code}'.format(country_alpha2=country_alpha2, subdivision_code=subdivision_code)
try:
if subdivisions.get(code=code) is None:
abort(400, 'Bad request: country_alpha2 and subdivision_code are invalid')
except KeyErr... | CityItem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the sub... | stack_v2_sparse_classes_75kplus_train_008464 | 9,552 | permissive | [
{
"docstring": "Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the subdivision record. :type subdivision_code: str :param city_id: The unique identifier of the city... | 3 | stack_v2_sparse_classes_30k_train_047750 | Implement the Python class `CityItem` described below.
Class description:
Implement the CityItem class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str, city_id: int): Returns a city record. :param country_alpha2: The unique two character identifier of the country record. ... | Implement the Python class `CityItem` described below.
Class description:
Implement the CityItem class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str, city_id: int): Returns a city record. :param country_alpha2: The unique two character identifier of the country record. ... | a38097d0f4a2f59c7c4892df6a72c19236df48e9 | <|skeleton|>
class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the sub... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the subdivision recor... | the_stack_v2_python_sparse | api/geolocation_data_flaskapi/endpoints/location_endpoint.py | Fyzel/geolocation-data-flaskapi | train | 3 | |
abe34a11b4db2bc405d9c7957b01f83a911034b7 | [
"se = SequencingCenter.query.get(kf_id)\nif se is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))\nreturn SequencingCenterSchema().jsonify(se)",
"se = SequencingCenter.query.get(kf_id)\nif se is None:\n abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))\n... | <|body_start_0|>
se = SequencingCenter.query.get(kf_id)
if se is None:
abort(404, 'could not find {} `{}`'.format('sequencing_center', kf_id))
return SequencingCenterSchema().jsonify(se)
<|end_body_0|>
<|body_start_1|>
se = SequencingCenter.query.get(kf_id)
if se is ... | SequencingCenter REST API | SequencingCenterAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing sequencing_center. All... | stack_v2_sparse_classes_75kplus_train_008465 | 5,230 | permissive | [
{
"docstring": "Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing sequencing_center. Allows partial update of resource --- template: path: update_by_id.... | 3 | stack_v2_sparse_classes_30k_train_050591 | Implement the Python class `SequencingCenterAPI` described below.
Class description:
SequencingCenter REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter
- def patch(self, kf_id): Update an existing s... | Implement the Python class `SequencingCenterAPI` described below.
Class description:
SequencingCenter REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter
- def patch(self, kf_id): Update an existing s... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing sequencing_center. All... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequencingCenterAPI:
"""SequencingCenter REST API"""
def get(self, kf_id):
"""Get a sequencing_center by id --- template: path: get_by_id.yml properties: resource: SequencingCenter"""
se = SequencingCenter.query.get(kf_id)
if se is None:
abort(404, 'could not find {} `... | the_stack_v2_python_sparse | dataservice/api/sequencing_center/resources.py | kids-first/kf-api-dataservice | train | 9 |
e14f76243cf30a4f08a3be9503d6fbe6c0a921b5 | [
"from collections import defaultdict\nfrom functools import reduce\nTrie = lambda: defaultdict(Trie)\ntrie = Trie()\nEND = True\nfor i, word in enumerate(words):\n reduce(dict.__getitem__, word, trie)[END] = i\nstack = list(trie.values())\nans = ''\nwhile stack:\n cur = stack.pop()\n if END in cur:\n ... | <|body_start_0|>
from collections import defaultdict
from functools import reduce
Trie = lambda: defaultdict(Trie)
trie = Trie()
END = True
for i, word in enumerate(words):
reduce(dict.__getitem__, word, trie)[END] = i
stack = list(trie.values())
... | Dictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dictionary:
def longest_word(self, words: List[str]) -> str:
"""Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:"""
<|body_0|>
def longest_word_(self, words: List[str]) -> str:
"""Approach: Brute Force Time Complexity:O... | stack_v2_sparse_classes_75kplus_train_008466 | 1,753 | no_license | [
{
"docstring": "Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:",
"name": "longest_word",
"signature": "def longest_word(self, words: List[str]) -> str"
},
{
"docstring": "Approach: Brute Force Time Complexity:O(∑w i2) Space Complexity: O(∑w i2) :... | 2 | stack_v2_sparse_classes_30k_train_025129 | Implement the Python class `Dictionary` described below.
Class description:
Implement the Dictionary class.
Method signatures and docstrings:
- def longest_word(self, words: List[str]) -> str: Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:
- def longest_word_(self, wo... | Implement the Python class `Dictionary` described below.
Class description:
Implement the Dictionary class.
Method signatures and docstrings:
- def longest_word(self, words: List[str]) -> str: Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:
- def longest_word_(self, wo... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Dictionary:
def longest_word(self, words: List[str]) -> str:
"""Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:"""
<|body_0|>
def longest_word_(self, words: List[str]) -> str:
"""Approach: Brute Force Time Complexity:O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dictionary:
def longest_word(self, words: List[str]) -> str:
"""Approach: Using Trie DS Time Complexity:O(∑w i) Space Complexity: O(∑w i) :param words: :return:"""
from collections import defaultdict
from functools import reduce
Trie = lambda: defaultdict(Trie)
trie = T... | the_stack_v2_python_sparse | revisited_2021/arrays/longest_word_in_dictionary.py | Shiv2157k/leet_code | train | 1 | |
16feb509d3518e58fb964593bc9bc182f6828f17 | [
"self.params = params\nself.tstep_info = tstep_info\nself.elevation = params['elevation']\nself.start_date = self.params['start_date']\nself.current_datetime = self.params['start_date']\nself.output_divided = False\nself.P_a = hysat(SEA_LEVEL, STD_AIRTMP, STD_LAPSE, self.elevation / 1000.0, GRAVITY, MOL_AIR)\nself.... | <|body_start_0|>
self.params = params
self.tstep_info = tstep_info
self.elevation = params['elevation']
self.start_date = self.params['start_date']
self.current_datetime = self.params['start_date']
self.output_divided = False
self.P_a = hysat(SEA_LEVEL, STD_AIRTMP... | iSnobal | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iSnobal:
def __init__(self, params, tstep_info, inital_conditions, meas_heights):
"""Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() function in snobal Args: params: dictionary of parameters to run the model tstep_info: list of tim... | stack_v2_sparse_classes_75kplus_train_008467 | 4,903 | permissive | [
{
"docstring": "Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() function in snobal Args: params: dictionary of parameters to run the model tstep_info: list of time step information inital_conditions: the initial snow properties meas_height: measurement he... | 3 | stack_v2_sparse_classes_30k_train_025582 | Implement the Python class `iSnobal` described below.
Class description:
Implement the iSnobal class.
Method signatures and docstrings:
- def __init__(self, params, tstep_info, inital_conditions, meas_heights): Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() fu... | Implement the Python class `iSnobal` described below.
Class description:
Implement the iSnobal class.
Method signatures and docstrings:
- def __init__(self, params, tstep_info, inital_conditions, meas_heights): Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() fu... | 9cff1e6cb2f1da4240132af4e1d2f5740092d2ef | <|skeleton|>
class iSnobal:
def __init__(self, params, tstep_info, inital_conditions, meas_heights):
"""Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() function in snobal Args: params: dictionary of parameters to run the model tstep_info: list of tim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iSnobal:
def __init__(self, params, tstep_info, inital_conditions, meas_heights):
"""Initialize the iSnobal() class with the parameters, time step information, This follows the initialize() function in snobal Args: params: dictionary of parameters to run the model tstep_info: list of time step informa... | the_stack_v2_python_sparse | pysnobal/spatial/isnobal.py | aerler/pysnobal | train | 0 | |
e76456089117e3dd6996864aead1855c3d7e5c16 | [
"result_text = cls._get_happy_str()\nlittle_sa.mylove.send(result_text)\nreturn result_text\npass",
"db = pymysql.connect(settings.MYSQL_HOST, settings.MYSQL_USER, settings.MYSQL_PASSWORD, settings.MYSQL_DATABASE)\ncursor = db.cursor()\nsql = '\\n SELECT joke_content FROM joke WHERE id >= ((SELECT MAX(... | <|body_start_0|>
result_text = cls._get_happy_str()
little_sa.mylove.send(result_text)
return result_text
pass
<|end_body_0|>
<|body_start_1|>
db = pymysql.connect(settings.MYSQL_HOST, settings.MYSQL_USER, settings.MYSQL_PASSWORD, settings.MYSQL_DATABASE)
cursor = db.cur... | Happy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Happy:
def send_happy(cls, little_sa):
"""发送每日笑笑 :param little_sa: 小萨引用 :return: None"""
<|body_0|>
def _get_happy_str(cls):
"""得到每日笑笑的发送信息 :return: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result_text = cls._get_happy_str()
littl... | stack_v2_sparse_classes_75kplus_train_008468 | 1,162 | no_license | [
{
"docstring": "发送每日笑笑 :param little_sa: 小萨引用 :return: None",
"name": "send_happy",
"signature": "def send_happy(cls, little_sa)"
},
{
"docstring": "得到每日笑笑的发送信息 :return: str",
"name": "_get_happy_str",
"signature": "def _get_happy_str(cls)"
}
] | 2 | null | Implement the Python class `Happy` described below.
Class description:
Implement the Happy class.
Method signatures and docstrings:
- def send_happy(cls, little_sa): 发送每日笑笑 :param little_sa: 小萨引用 :return: None
- def _get_happy_str(cls): 得到每日笑笑的发送信息 :return: str | Implement the Python class `Happy` described below.
Class description:
Implement the Happy class.
Method signatures and docstrings:
- def send_happy(cls, little_sa): 发送每日笑笑 :param little_sa: 小萨引用 :return: None
- def _get_happy_str(cls): 得到每日笑笑的发送信息 :return: str
<|skeleton|>
class Happy:
def send_happy(cls, litt... | 73184b4e3f45a6ca5e125ad710a5490947f79185 | <|skeleton|>
class Happy:
def send_happy(cls, little_sa):
"""发送每日笑笑 :param little_sa: 小萨引用 :return: None"""
<|body_0|>
def _get_happy_str(cls):
"""得到每日笑笑的发送信息 :return: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Happy:
def send_happy(cls, little_sa):
"""发送每日笑笑 :param little_sa: 小萨引用 :return: None"""
result_text = cls._get_happy_str()
little_sa.mylove.send(result_text)
return result_text
pass
def _get_happy_str(cls):
"""得到每日笑笑的发送信息 :return: str"""
db = pymys... | the_stack_v2_python_sparse | core/happy.py | 2095019320/sms_for_mylove | train | 0 | |
81afd234b7dcb71debd5cf6080a01afe303b46d4 | [
"super().__init__(imageSurf, coord, world_coordinates)\nself.contents = collectable if collectable != None and amount != None else random.choice(list(COLLECTABLES.keys()))\nself.amount = amount if collectable != None and amount != None else random.randint(COLLECTABLES[self.contents][0], COLLECTABLES[self.contents][... | <|body_start_0|>
super().__init__(imageSurf, coord, world_coordinates)
self.contents = collectable if collectable != None and amount != None else random.choice(list(COLLECTABLES.keys()))
self.amount = amount if collectable != None and amount != None else random.randint(COLLECTABLES[self.contents... | PickUp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickUp:
def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None):
"""Interactive chest, random amount of random collectable assigned if no values passed for collectable"""
<|body_0|>
def updateMap(self, map):
"""Adds contents of interact... | stack_v2_sparse_classes_75kplus_train_008469 | 1,324 | no_license | [
{
"docstring": "Interactive chest, random amount of random collectable assigned if no values passed for collectable",
"name": "__init__",
"signature": "def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None)"
},
{
"docstring": "Adds contents of interactive tile to ... | 2 | stack_v2_sparse_classes_30k_train_002033 | Implement the Python class `PickUp` described below.
Class description:
Implement the PickUp class.
Method signatures and docstrings:
- def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None): Interactive chest, random amount of random collectable assigned if no values passed for collec... | Implement the Python class `PickUp` described below.
Class description:
Implement the PickUp class.
Method signatures and docstrings:
- def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None): Interactive chest, random amount of random collectable assigned if no values passed for collec... | 1db75c71912bf054553d50b130eb61f7666d32d8 | <|skeleton|>
class PickUp:
def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None):
"""Interactive chest, random amount of random collectable assigned if no values passed for collectable"""
<|body_0|>
def updateMap(self, map):
"""Adds contents of interact... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickUp:
def __init__(self, imageSurf, coord, world_coordinates, collectable=None, amount=None):
"""Interactive chest, random amount of random collectable assigned if no values passed for collectable"""
super().__init__(imageSurf, coord, world_coordinates)
self.contents = collectable if... | the_stack_v2_python_sparse | PickUps.py | KratzenbergD/Lab_2 | train | 0 | |
e2015e33303f68eca1574a65ac2211337aa86a94 | [
"global all_feats, usage_string, feat_to_order\nfor meta_feat in meta.meta_feats:\n if meta_feat.value == 'integer' or meta_feat.value == 'real':\n all_feats.append(meta_feat.name)\ntp_classes_ok = False\nfor meta_tp in meta.meta_tpclasses:\n if meta_tp.value == '{True,False}':\n tp_classes_ok =... | <|body_start_0|>
global all_feats, usage_string, feat_to_order
for meta_feat in meta.meta_feats:
if meta_feat.value == 'integer' or meta_feat.value == 'real':
all_feats.append(meta_feat.name)
tp_classes_ok = False
for meta_tp in meta.meta_tpclasses:
... | StatsCollectorHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsCollectorHandler:
def handle_meta(self, meta, info={}):
"""Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the meta-features. The list of `all_feats` will be used in order to verify that all key features have a valid meta-... | stack_v2_sparse_classes_75kplus_train_008470 | 11,886 | no_license | [
{
"docstring": "Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the meta-features. The list of `all_feats` will be used in order to verify that all key features have a valid meta-feature. This is important because we need to determine the correct type... | 2 | stack_v2_sparse_classes_30k_train_035065 | Implement the Python class `StatsCollectorHandler` described below.
Class description:
Implement the StatsCollectorHandler class.
Method signatures and docstrings:
- def handle_meta(self, meta, info={}): Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the m... | Implement the Python class `StatsCollectorHandler` described below.
Class description:
Implement the StatsCollectorHandler class.
Method signatures and docstrings:
- def handle_meta(self, meta, info={}): Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the m... | 6e074b9a95ba2efc88e49469a0e90a028681bd12 | <|skeleton|>
class StatsCollectorHandler:
def handle_meta(self, meta, info={}):
"""Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the meta-features. The list of `all_feats` will be used in order to verify that all key features have a valid meta-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StatsCollectorHandler:
def handle_meta(self, meta, info={}):
"""Treats the meta information of the file. Besides of printing the meta header out, it also keeps track of all the meta-features. The list of `all_feats` will be used in order to verify that all key features have a valid meta-feature. This ... | the_stack_v2_python_sparse | LANGAGE_NATUREL/Nazim/TP1/bin/mwetoolkit/bin/avg_precision.py | n4zim/Licence_3_Informatique | train | 0 | |
2fc34223ff7e19ba468a622f26857279da92dbc6 | [
"super().__init__()\nself.D = D\nself.W = W\nself.in_channels_dir = in_channels_dir\nfor i in range(D):\n if i == 0:\n layer = nn.Sequential(nn.Linear(in_channels_dir, W), nn.ReLU())\n else:\n layer = nn.Sequential(nn.Linear(W, W), nn.ReLU())\n setattr(self, f'dir_encoding_{i + 1}', layer)\ns... | <|body_start_0|>
super().__init__()
self.D = D
self.W = W
self.in_channels_dir = in_channels_dir
for i in range(D):
if i == 0:
layer = nn.Sequential(nn.Linear(in_channels_dir, W), nn.ReLU())
else:
layer = nn.Sequential(nn.Li... | BgNeRF | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BgNeRF:
def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n_classes=6):
"""D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer"""
<... | stack_v2_sparse_classes_75kplus_train_008471 | 8,749 | permissive | [
{
"docstring": "D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer",
"name": "__init__",
"signature": "def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n... | 2 | stack_v2_sparse_classes_30k_train_001891 | Implement the Python class `BgNeRF` described below.
Class description:
Implement the BgNeRF class.
Method signatures and docstrings:
- def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n_classes=6): D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels... | Implement the Python class `BgNeRF` described below.
Class description:
Implement the BgNeRF class.
Method signatures and docstrings:
- def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n_classes=6): D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class BgNeRF:
def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n_classes=6):
"""D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BgNeRF:
def __init__(self, D, W, in_channels_dir=27, with_semantics=False, n_classes=6):
"""D: number of layers W: number of hidden units in each layer in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer"""
super().__init_... | the_stack_v2_python_sparse | nerflets/models/nerf.py | Jimmy-INL/google-research | train | 1 | |
186a58c26d9b638085c924b70b35ce458afe2091 | [
"ListNums = len(lists)\nif ListNums == 1:\n return lists[0]\n\ndef mergeList(head1: ListNode, head2: ListNode):\n if head1 == None:\n return head2\n if head2 == None:\n return head1\n if head1.val < head2.val:\n head1.next = mergeList(head1.next, head2)\n return head1\n el... | <|body_start_0|>
ListNums = len(lists)
if ListNums == 1:
return lists[0]
def mergeList(head1: ListNode, head2: ListNode):
if head1 == None:
return head2
if head2 == None:
return head1
if head1.val < head2.val:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists) -> ListNode:
"""每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:"""
<|body_0|>
def mergeKLists2(self, lists) -> ListNode:
"""对上面进行分治,合并 :param list[ListNode] lists: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_008472 | 2,355 | no_license | [
{
"docstring": "每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists) -> ListNode"
},
{
"docstring": "对上面进行分治,合并 :param list[ListNode] lists: :return:",
"name": "mergeKLists2",
"signature": "def mergeKLists2(self, lists) ... | 2 | stack_v2_sparse_classes_30k_train_009907 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists) -> ListNode: 每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:
- def mergeKLists2(self, lists) -> ListNode: 对上面进行分治,合并 :param list[ListNode] lists... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists) -> ListNode: 每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:
- def mergeKLists2(self, lists) -> ListNode: 对上面进行分治,合并 :param list[ListNode] lists... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def mergeKLists(self, lists) -> ListNode:
"""每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:"""
<|body_0|>
def mergeKLists2(self, lists) -> ListNode:
"""对上面进行分治,合并 :param list[ListNode] lists: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeKLists(self, lists) -> ListNode:
"""每次只合并两个链表,超时了。 :param list[ListNode] lists: :return:"""
ListNums = len(lists)
if ListNums == 1:
return lists[0]
def mergeList(head1: ListNode, head2: ListNode):
if head1 == None:
ret... | the_stack_v2_python_sparse | 华为题库/合并K个排序链表.py | 2226171237/Algorithmpractice | train | 0 | |
a3519b6f5ad775a290e0f2d66e5f4b3e1bcced55 | [
"records = Records(Extractor.extract_records(filename))\ngroups = records.group(minsog, maxsog)\nfor key in groups:\n rw = RecordsWriter(groups[key])\n rw.write_to_dir(key + '.fasta', outdir)",
"records = Records(Extractor.extract_records(filename))\nfseqs = records.filtr_organism_by_size(organism, minsize,... | <|body_start_0|>
records = Records(Extractor.extract_records(filename))
groups = records.group(minsog, maxsog)
for key in groups:
rw = RecordsWriter(groups[key])
rw.write_to_dir(key + '.fasta', outdir)
<|end_body_0|>
<|body_start_1|>
records = Records(Extractor.e... | RecordsController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordsController:
def grouping(filename, outdir, minsog, maxsog):
"""Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds' :param filename: filename with sequences in fasta :param outdir: output directory for saving groups :para... | stack_v2_sparse_classes_75kplus_train_008473 | 2,438 | no_license | [
{
"docstring": "Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds' :param filename: filename with sequences in fasta :param outdir: output directory for saving groups :param minsog: int, min size of genome :param maxsog: int, max size of genome",
... | 4 | stack_v2_sparse_classes_30k_train_024582 | Implement the Python class `RecordsController` described below.
Class description:
Implement the RecordsController class.
Method signatures and docstrings:
- def grouping(filename, outdir, minsog, maxsog): Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds'... | Implement the Python class `RecordsController` described below.
Class description:
Implement the RecordsController class.
Method signatures and docstrings:
- def grouping(filename, outdir, minsog, maxsog): Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds'... | 98f8dc52f735bcaa9cc8a2f1c2f1697fcf0f5b4d | <|skeleton|>
class RecordsController:
def grouping(filename, outdir, minsog, maxsog):
"""Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds' :param filename: filename with sequences in fasta :param outdir: output directory for saving groups :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecordsController:
def grouping(filename, outdir, minsog, maxsog):
"""Grouping sequences by names. All big sequences (genomes) with minsog <= size <= maxsog form separate group 'cds' :param filename: filename with sequences in fasta :param outdir: output directory for saving groups :param minsog: int,... | the_stack_v2_python_sparse | Clss/Controller/RecordsController.py | Maximato/fstage | train | 0 | |
7cf3f299b8843e75852a43bf7620ada06c806026 | [
"jwt_auth = JWTAuthentication()\nuser_token = jwt_auth.authenticate(self.request)\nif user_token is not None:\n user = user_token[0]\n return user\nelse:\n return None",
"country = get_country(self.request)\ncontext = super().get_serializer_context()\ncontext['country'] = country\ncontext['user'] = self.... | <|body_start_0|>
jwt_auth = JWTAuthentication()
user_token = jwt_auth.authenticate(self.request)
if user_token is not None:
user = user_token[0]
return user
else:
return None
<|end_body_0|>
<|body_start_1|>
country = get_country(self.request)
... | RetrieveAPIView with modified serializer context that includes User object | URetrieveAPIView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URetrieveAPIView:
"""RetrieveAPIView with modified serializer context that includes User object"""
def get_user(self):
"""Return user object if request contains valid credentials"""
<|body_0|>
def get_serializer_context(self):
"""Add user object and current user'... | stack_v2_sparse_classes_75kplus_train_008474 | 2,712 | permissive | [
{
"docstring": "Return user object if request contains valid credentials",
"name": "get_user",
"signature": "def get_user(self)"
},
{
"docstring": "Add user object and current user's country to serializer context",
"name": "get_serializer_context",
"signature": "def get_serializer_contex... | 2 | stack_v2_sparse_classes_30k_train_036962 | Implement the Python class `URetrieveAPIView` described below.
Class description:
RetrieveAPIView with modified serializer context that includes User object
Method signatures and docstrings:
- def get_user(self): Return user object if request contains valid credentials
- def get_serializer_context(self): Add user obj... | Implement the Python class `URetrieveAPIView` described below.
Class description:
RetrieveAPIView with modified serializer context that includes User object
Method signatures and docstrings:
- def get_user(self): Return user object if request contains valid credentials
- def get_serializer_context(self): Add user obj... | 860d1c1214de125346c0accc4ec4b8953297231b | <|skeleton|>
class URetrieveAPIView:
"""RetrieveAPIView with modified serializer context that includes User object"""
def get_user(self):
"""Return user object if request contains valid credentials"""
<|body_0|>
def get_serializer_context(self):
"""Add user object and current user'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class URetrieveAPIView:
"""RetrieveAPIView with modified serializer context that includes User object"""
def get_user(self):
"""Return user object if request contains valid credentials"""
jwt_auth = JWTAuthentication()
user_token = jwt_auth.authenticate(self.request)
if user_tok... | the_stack_v2_python_sparse | src/catalog/views.py | xgerinx/skillsitev2 | train | 0 |
7f0d30328a2587dfa25eb079dba49795fdf3c61e | [
"params = dict()\nif Utils.is_containing_bracket(synapse_order):\n params = cls._associate_order_params_to_values(user_order, synapse_order)\n logger.debug('Parameters for order: %s' % params)\nreturn params",
"logger.debug('[OrderAnalyser._associate_order_params_to_values] user order: %s, order from synaps... | <|body_start_0|>
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_values(user_order, synapse_order)
logger.debug('Parameters for order: %s' % params)
return params
<|end_body_0|>
<|body_start_1|>
logger.debug(... | NeuronParameterLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_75kplus_train_008475 | 2,737 | permissive | [
{
"docstring": "Class method to get all params coming from a string order. Returns a dict of key/value.",
"name": "get_parameters",
"signature": "def get_parameters(cls, synapse_order, user_order)"
},
{
"docstring": "Associate the variables from the order to the incoming user order :param order_... | 2 | stack_v2_sparse_classes_30k_train_011218 | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | Implement the Python class `NeuronParameterLoader` described below.
Class description:
Implement the NeuronParameterLoader class.
Method signatures and docstrings:
- def get_parameters(cls, synapse_order, user_order): Class method to get all params coming from a string order. Returns a dict of key/value.
- def _assoc... | cea86934e3474b4f944b77001f952285fe2f70bf | <|skeleton|>
class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
<|body_0|>
def _associate_order_params_to_values(cls, order, order_to_check):
"""Associate the var... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuronParameterLoader:
def get_parameters(cls, synapse_order, user_order):
"""Class method to get all params coming from a string order. Returns a dict of key/value."""
params = dict()
if Utils.is_containing_bracket(synapse_order):
params = cls._associate_order_params_to_va... | the_stack_v2_python_sparse | kalliope/core/NeuronParameterLoader.py | metal3d/kalliope | train | 1 | |
71bb7a4f9e2fec3fdc48857dfb5a02173cd53642 | [
"JSON_OPT.__init__(self)\nself.add_features('Figures to operate with', ['figures'], IMAGE_OPT)\npass",
"im_paths = []\noperations = []\nresizes = []\npositions = []\nmasks = []\nmethods = []\nsaves = []\nis_temps = []\ntexts = []\nfont_sizes = []\nfor feature in self.values[0]:\n im_path, operation, resize, po... | <|body_start_0|>
JSON_OPT.__init__(self)
self.add_features('Figures to operate with', ['figures'], IMAGE_OPT)
pass
<|end_body_0|>
<|body_start_1|>
im_paths = []
operations = []
resizes = []
positions = []
masks = []
methods = []
saves = []... | class to hold options for using pillow to operation on images | PILLOW_OPT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PILLOW_OPT:
"""class to hold options for using pillow to operation on images"""
def __init__(self):
"""Initiation"""
<|body_0|>
def to_pillow_run(self):
"""interface to the PillowRun function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
JSON_... | stack_v2_sparse_classes_75kplus_train_008476 | 32,977 | no_license | [
{
"docstring": "Initiation",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "interface to the PillowRun function",
"name": "to_pillow_run",
"signature": "def to_pillow_run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008391 | Implement the Python class `PILLOW_OPT` described below.
Class description:
class to hold options for using pillow to operation on images
Method signatures and docstrings:
- def __init__(self): Initiation
- def to_pillow_run(self): interface to the PillowRun function | Implement the Python class `PILLOW_OPT` described below.
Class description:
class to hold options for using pillow to operation on images
Method signatures and docstrings:
- def __init__(self): Initiation
- def to_pillow_run(self): interface to the PillowRun function
<|skeleton|>
class PILLOW_OPT:
"""class to ho... | d919cadce2b57811351c0615d94da5c6ebfff800 | <|skeleton|>
class PILLOW_OPT:
"""class to hold options for using pillow to operation on images"""
def __init__(self):
"""Initiation"""
<|body_0|>
def to_pillow_run(self):
"""interface to the PillowRun function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PILLOW_OPT:
"""class to hold options for using pillow to operation on images"""
def __init__(self):
"""Initiation"""
JSON_OPT.__init__(self)
self.add_features('Figures to operate with', ['figures'], IMAGE_OPT)
pass
def to_pillow_run(self):
"""interface to the ... | the_stack_v2_python_sparse | jupyter_notebooks/python_scripts/Utilities.py | lhy11009/aspectLib | train | 0 |
fec2d1815ed1138828627d8eba7c3f39a213d3bc | [
"form = ParticipantDataEditForm(self.request.form, config=self.config)\nregistration_form = self.barcamp.registration_form\nif self.request.method == 'POST' and form.validate():\n f = form.data\n f['name'] = unicode(uuid.uuid4())\n new_choices = []\n for c in f['choices'].split('\\n'):\n choice =... | <|body_start_0|>
form = ParticipantDataEditForm(self.request.form, config=self.config)
registration_form = self.barcamp.registration_form
if self.request.method == 'POST' and form.validate():
f = form.data
f['name'] = unicode(uuid.uuid4())
new_choices = []
... | let the user define the participant data form fields | ParticipantsDataEditView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantsDataEditView:
"""let the user define the participant data form fields"""
def get(self, slug=None):
"""render the view"""
<|body_0|>
def delete(self, slug=None):
"""delete a form entry"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f... | stack_v2_sparse_classes_75kplus_train_008477 | 3,339 | permissive | [
{
"docstring": "render the view",
"name": "get",
"signature": "def get(self, slug=None)"
},
{
"docstring": "delete a form entry",
"name": "delete",
"signature": "def delete(self, slug=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049102 | Implement the Python class `ParticipantsDataEditView` described below.
Class description:
let the user define the participant data form fields
Method signatures and docstrings:
- def get(self, slug=None): render the view
- def delete(self, slug=None): delete a form entry | Implement the Python class `ParticipantsDataEditView` described below.
Class description:
let the user define the participant data form fields
Method signatures and docstrings:
- def get(self, slug=None): render the view
- def delete(self, slug=None): delete a form entry
<|skeleton|>
class ParticipantsDataEditView:
... | 9b45664e46c451b2cbe00bb55583b043e769083d | <|skeleton|>
class ParticipantsDataEditView:
"""let the user define the participant data form fields"""
def get(self, slug=None):
"""render the view"""
<|body_0|>
def delete(self, slug=None):
"""delete a form entry"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParticipantsDataEditView:
"""let the user define the participant data form fields"""
def get(self, slug=None):
"""render the view"""
form = ParticipantDataEditForm(self.request.form, config=self.config)
registration_form = self.barcamp.registration_form
if self.request.met... | the_stack_v2_python_sparse | camper/barcamps/customfields.py | comlounge/camper | train | 14 |
fc0d6d958c34b9beeaf7f86695d049be16db6a3f | [
"if not is_all(eids):\n g = g.edge_subgraph(eids.long())\nn_nodes = g.number_of_nodes()\nn_edges = g.number_of_edges()\nscore_context = utils.to_dgl_context(score.device)\nif isinstance(g, DGLGraph):\n gidx = g._graph.get_immutable_gidx(score_context)\nelif isinstance(g, DGLHeteroGraph):\n assert g._graph.... | <|body_start_0|>
if not is_all(eids):
g = g.edge_subgraph(eids.long())
n_nodes = g.number_of_nodes()
n_edges = g.number_of_edges()
score_context = utils.to_dgl_context(score.device)
if isinstance(g, DGLGraph):
gidx = g._graph.get_immutable_gidx(score_conte... | Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context of softmax. :math:`\\mathca... | EdgeSoftmax | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ... | stack_v2_sparse_classes_75kplus_train_008478 | 6,424 | permissive | [
{
"docstring": "Forward function. Pseudo-code: .. code:: python score = dgl.EData(g, score) score_max = score.dst_max() # of type dgl.NData score = score - score_max # edge_sub_dst, ret dgl.EData score_sum = score.dst_sum() # of type dgl.NData out = score / score_sum # edge_div_dst, ret dgl.EData return out.dat... | 2 | stack_v2_sparse_classes_30k_train_043645 | Implement the Python class `EdgeSoftmax` described below.
Class description:
Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j... | Implement the Python class `EdgeSoftmax` described below.
Class description:
Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j... | 170c2ed46fde29271246fe6600948b2864534ca3 | <|skeleton|>
class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EdgeSoftmax:
"""Apply softmax over signals of incoming edges. For a node :math:`i`, edgesoftmax is an operation of computing .. math:: a_{ij} = \\frac{\\exp(z_{ij})}{\\sum_{j\\in\\mathcal{N}(i)}\\exp(z_{ij})} where :math:`z_{ij}` is a signal of edge :math:`j\\rightarrow i`, also called logits in the context o... | the_stack_v2_python_sparse | python/dgl/nn/pytorch/softmax.py | Menooker/dgl | train | 3 |
0efef3711b0468f501bffbcfcd5227185479e891 | [
"h_dim = dim[0]\nz_dim = dim[1]\nsuper(Encoder, self).__init__(**kwargs)\nself.fc1 = tf.keras.layers.Dense(h_dim)\nself.fc2 = tf.keras.layers.Dense(z_dim)",
"h = tf.nn.relu(self.fc1(inputs))\nz = self.fc2(h)\nreturn z"
] | <|body_start_0|>
h_dim = dim[0]
z_dim = dim[1]
super(Encoder, self).__init__(**kwargs)
self.fc1 = tf.keras.layers.Dense(h_dim)
self.fc2 = tf.keras.layers.Dense(z_dim)
<|end_body_0|>
<|body_start_1|>
h = tf.nn.relu(self.fc1(inputs))
z = self.fc2(h)
return ... | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, dim, **kwargs):
"""Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Optional)"""
<|body_0|>
def call(self, inputs, training=None, mask=None):
"""Func... | stack_v2_sparse_classes_75kplus_train_008479 | 823 | permissive | [
{
"docstring": "Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Optional)",
"name": "__init__",
"signature": "def __init__(self, dim, **kwargs)"
},
{
"docstring": "Function that works as __call__ :param in... | 2 | stack_v2_sparse_classes_30k_train_042361 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, dim, **kwargs): Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Option... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, dim, **kwargs): Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Option... | 91dbb0eebba64f1fa2c18562e2c9f35f532ef7c0 | <|skeleton|>
class Encoder:
def __init__(self, dim, **kwargs):
"""Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Optional)"""
<|body_0|>
def call(self, inputs, training=None, mask=None):
"""Func... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
def __init__(self, dim, **kwargs):
"""Encoder model :param dim: hyperparameters of the model [h_dim, z_dim] :param dropout: Noise dropout [0,1] :param kwargs: Keras parameters (Optional)"""
h_dim = dim[0]
z_dim = dim[1]
super(Encoder, self).__init__(**kwargs)
s... | the_stack_v2_python_sparse | src/python_code/Models/PAE_models/Encoder.py | ipmach/Thesis2021 | train | 0 | |
126d341993bc3f850329d2912ae2dc87a6a2e51e | [
"super(GetWordInfo, self).__init__()\nself.text = text\nself.freq = 0.0\nself.left = []\nself.right = []\nself.pmi = 0",
"self.freq += 1\nif left:\n self.left.append(left)\nif right:\n self.right.append(right)",
"self.freq /= length\nself.left = cal_infor_entropy(self.left)\nself.right = cal_infor_entropy... | <|body_start_0|>
super(GetWordInfo, self).__init__()
self.text = text
self.freq = 0.0
self.left = []
self.right = []
self.pmi = 0
<|end_body_0|>
<|body_start_1|>
self.freq += 1
if left:
self.left.append(left)
if right:
self... | Store information of each word, including it's frequency, left neighbors and right neighbors | GetWordInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_008480 | 6,102 | no_license | [
{
"docstring": "init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy.",
"name": "__init__",
"signature": "def __init__(self, text)"
},
{
"docstring": "Increase frequency of this word, then append left/right neighbors. :param left: left ne... | 4 | stack_v2_sparse_classes_30k_test_000312 | Implement the Python class `GetWordInfo` described below.
Class description:
Store information of each word, including it's frequency, left neighbors and right neighbors
Method signatures and docstrings:
- def __init__(self, text): init function,the text is the word. :param text:the string will be compute,include fre... | Implement the Python class `GetWordInfo` described below.
Class description:
Store information of each word, including it's frequency, left neighbors and right neighbors
Method signatures and docstrings:
- def __init__(self, text): init function,the text is the word. :param text:the string will be compute,include fre... | a5ff7ad6c94c1fbb633d7321fd1a27f849ce6fb8 | <|skeleton|>
class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
super(GetWordInfo, self).__init__... | the_stack_v2_python_sparse | word_seg_md/newWordsFind.py | GenjiLuo/the-neologism | train | 0 |
f11f57e04fddb867513872d1c380c1e56f8fa457 | [
"parameters = dict()\nparameters['page'] = GraphQLParam(page, 'PageInput', False)\nparameters['filter'] = GraphQLParam(sc_filter, 'SupportCaseFilter', False)\nparameters['sort'] = GraphQLParam(sort, 'SupportCaseSort', False)\nresponse = self._query(name='getSupportCases', params=parameters, fields=SupportCaseList.f... | <|body_start_0|>
parameters = dict()
parameters['page'] = GraphQLParam(page, 'PageInput', False)
parameters['filter'] = GraphQLParam(sc_filter, 'SupportCaseFilter', False)
parameters['sort'] = GraphQLParam(sort, 'SupportCaseSort', False)
response = self._query(name='getSupportCas... | Mixin to add support case related methods to the GraphQL client | SupportCaseMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportCaseMixin:
"""Mixin to add support case related methods to the GraphQL client"""
def get_support_cases(self, page: PageInput=None, sc_filter: SupportCaseFilter=None, sort: SupportCaseSort=None) -> SupportCaseList:
"""Retrieves a list of support cases :param page: The requested... | stack_v2_sparse_classes_75kplus_train_008481 | 40,618 | permissive | [
{
"docstring": "Retrieves a list of support cases :param page: The requested page from the server. This is an optional argument and if omitted the server will default to returning the first page with a maximum of ``100`` items. :type page: PageInput, optional :param sc_filter: A filter object to filter support ... | 6 | stack_v2_sparse_classes_30k_train_023319 | Implement the Python class `SupportCaseMixin` described below.
Class description:
Mixin to add support case related methods to the GraphQL client
Method signatures and docstrings:
- def get_support_cases(self, page: PageInput=None, sc_filter: SupportCaseFilter=None, sort: SupportCaseSort=None) -> SupportCaseList: Ret... | Implement the Python class `SupportCaseMixin` described below.
Class description:
Mixin to add support case related methods to the GraphQL client
Method signatures and docstrings:
- def get_support_cases(self, page: PageInput=None, sc_filter: SupportCaseFilter=None, sort: SupportCaseSort=None) -> SupportCaseList: Ret... | 8ea044096bd18aaccbfb81eca4e26ec29895a18c | <|skeleton|>
class SupportCaseMixin:
"""Mixin to add support case related methods to the GraphQL client"""
def get_support_cases(self, page: PageInput=None, sc_filter: SupportCaseFilter=None, sort: SupportCaseSort=None) -> SupportCaseList:
"""Retrieves a list of support cases :param page: The requested... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupportCaseMixin:
"""Mixin to add support case related methods to the GraphQL client"""
def get_support_cases(self, page: PageInput=None, sc_filter: SupportCaseFilter=None, sort: SupportCaseSort=None) -> SupportCaseList:
"""Retrieves a list of support cases :param page: The requested page from th... | the_stack_v2_python_sparse | nebpyclient/api/etickets.py | firefly707/nebpyclient | train | 0 |
0d2305cd39b47e2c0c04713de03dec7a2d38176d | [
"args = self._base_args_copy()\nargs += ['-p', project.filename]\nargs += ['-c', config.name]\nargs += ['--verbose']\nreturn args",
"super(UbuildBuilder, self)._run_builder(project, config)\nargs = self._construct_ubuild_args(project, config)\nif not ubuild(args):\n raise BuildError('Failed to build {}'.format... | <|body_start_0|>
args = self._base_args_copy()
args += ['-p', project.filename]
args += ['-c', config.name]
args += ['--verbose']
return args
<|end_body_0|>
<|body_start_1|>
super(UbuildBuilder, self)._run_builder(project, config)
args = self._construct_ubuild_ar... | UbuildBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UbuildBuilder:
def _construct_ubuild_args(self, project, config):
"""Build the arguments list for passing to ubuild"""
<|body_0|>
def _run_builder(self, project, config):
"""Call the ubuild module to perform the actual build."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_008482 | 762 | no_license | [
{
"docstring": "Build the arguments list for passing to ubuild",
"name": "_construct_ubuild_args",
"signature": "def _construct_ubuild_args(self, project, config)"
},
{
"docstring": "Call the ubuild module to perform the actual build.",
"name": "_run_builder",
"signature": "def _run_buil... | 2 | stack_v2_sparse_classes_30k_train_027695 | Implement the Python class `UbuildBuilder` described below.
Class description:
Implement the UbuildBuilder class.
Method signatures and docstrings:
- def _construct_ubuild_args(self, project, config): Build the arguments list for passing to ubuild
- def _run_builder(self, project, config): Call the ubuild module to p... | Implement the Python class `UbuildBuilder` described below.
Class description:
Implement the UbuildBuilder class.
Method signatures and docstrings:
- def _construct_ubuild_args(self, project, config): Build the arguments list for passing to ubuild
- def _run_builder(self, project, config): Call the ubuild module to p... | bff2d8c9e5e1ead4018f63098c1adea0e0c28184 | <|skeleton|>
class UbuildBuilder:
def _construct_ubuild_args(self, project, config):
"""Build the arguments list for passing to ubuild"""
<|body_0|>
def _run_builder(self, project, config):
"""Call the ubuild module to perform the actual build."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UbuildBuilder:
def _construct_ubuild_args(self, project, config):
"""Build the arguments list for passing to ubuild"""
args = self._base_args_copy()
args += ['-p', project.filename]
args += ['-c', config.name]
args += ['--verbose']
return args
def _run_buil... | the_stack_v2_python_sparse | adk/tools/packages/workspace_builders/ubuild_builder.py | litterstar7/Qualcomm_BT_Audio | train | 4 | |
70f33b4ce9e669293dfb6c0a599db2a964ee4677 | [
"idx = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\nidy = cuda.blockIdx.y * cuda.blockDim.y + cuda.threadIdx.y\nindex = idx * size + idy\nif idx < size and idy < size:\n if idx > i:\n mul = A[idx * size + i] / A[i * size + i]\n if idy >= i:\n A[index] -= A[i * size + idy] * mul\... | <|body_start_0|>
idx = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x
idy = cuda.blockIdx.y * cuda.blockDim.y + cuda.threadIdx.y
index = idx * size + idy
if idx < size and idy < size:
if idx > i:
mul = A[idx * size + i] / A[i * size + i]
... | GuassianLUDecomposition | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuassianLUDecomposition:
def gaussian_lu_decomposition(A, L, size, i):
"""Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the multipliers. @param size Size of coefficiente matrix. @param i Integer representing the current column in which... | stack_v2_sparse_classes_75kplus_train_008483 | 4,828 | no_license | [
{
"docstring": "Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the multipliers. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads are performing row operations. @return None",
"name": "gaussian_l... | 6 | stack_v2_sparse_classes_30k_train_040288 | Implement the Python class `GuassianLUDecomposition` described below.
Class description:
Implement the GuassianLUDecomposition class.
Method signatures and docstrings:
- def gaussian_lu_decomposition(A, L, size, i): Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the... | Implement the Python class `GuassianLUDecomposition` described below.
Class description:
Implement the GuassianLUDecomposition class.
Method signatures and docstrings:
- def gaussian_lu_decomposition(A, L, size, i): Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the... | b2b89a18260c25134d50c37a4fbb48981de79218 | <|skeleton|>
class GuassianLUDecomposition:
def gaussian_lu_decomposition(A, L, size, i):
"""Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the multipliers. @param size Size of coefficiente matrix. @param i Integer representing the current column in which... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GuassianLUDecomposition:
def gaussian_lu_decomposition(A, L, size, i):
"""Performs Gaussian LU elimination. @param A Coefficient matrix A. @param L Matrix in which to store the multipliers. @param size Size of coefficiente matrix. @param i Integer representing the current column in which all threads a... | the_stack_v2_python_sparse | project/lu_decomposition/gaussian_lu_decomposition.py | tllano11/Numerical-Methods | train | 3 | |
ecc797040122638ad29a04879f33ba3d8f03e3fc | [
"super(PointerAfterLogits, self).__init__(hidden_size, output_size, causal=causal, logits_per_slot=logits_per_slot, **kwargs)\nself.logits_embedding = tf.keras.layers.Embedding(logits_size, output_size, **kwargs)\nself.logits_size = logits_size",
"features = self.block(inputs.queries, **kwargs)\nb = self.logits_e... | <|body_start_0|>
super(PointerAfterLogits, self).__init__(hidden_size, output_size, causal=causal, logits_per_slot=logits_per_slot, **kwargs)
self.logits_embedding = tf.keras.layers.Embedding(logits_size, output_size, **kwargs)
self.logits_size = logits_size
<|end_body_0|>
<|body_start_1|>
... | PointerAfterLogits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointerAfterLogits:
def __init__(self, hidden_size, output_size, logits_size, causal=True, logits_per_slot=1, **kwargs):
"""Creates a pointer network using the first operation in the self attention mechanism Arguments: hidden_size: int the number of hidden units in the network blocks use... | stack_v2_sparse_classes_75kplus_train_008484 | 4,385 | no_license | [
{
"docstring": "Creates a pointer network using the first operation in the self attention mechanism Arguments: hidden_size: int the number of hidden units in the network blocks used by this layer output_size: int the number of output units used by the network blocks used by this layer logits_size: int the numbe... | 3 | null | Implement the Python class `PointerAfterLogits` described below.
Class description:
Implement the PointerAfterLogits class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, logits_size, causal=True, logits_per_slot=1, **kwargs): Creates a pointer network using the first operation in th... | Implement the Python class `PointerAfterLogits` described below.
Class description:
Implement the PointerAfterLogits class.
Method signatures and docstrings:
- def __init__(self, hidden_size, output_size, logits_size, causal=True, logits_per_slot=1, **kwargs): Creates a pointer network using the first operation in th... | c155b16265f13d87be0108fcf815517491b93a74 | <|skeleton|>
class PointerAfterLogits:
def __init__(self, hidden_size, output_size, logits_size, causal=True, logits_per_slot=1, **kwargs):
"""Creates a pointer network using the first operation in the self attention mechanism Arguments: hidden_size: int the number of hidden units in the network blocks use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointerAfterLogits:
def __init__(self, hidden_size, output_size, logits_size, causal=True, logits_per_slot=1, **kwargs):
"""Creates a pointer network using the first operation in the self attention mechanism Arguments: hidden_size: int the number of hidden units in the network blocks used by this laye... | the_stack_v2_python_sparse | indigo/nn/variables/pointer_after_logits.py | mlberkeley/indigo | train | 4 | |
9ee3951d484d64a80b375ea232066c783ef16238 | [
"tmp_sum = (x + self.eta).as_array()\nind = tmp_sum >= 0\ntmp = scipy.special.kl_div(self.b.as_array()[ind], tmp_sum[ind])\nreturn numpy.sum(tmp)",
"should_return = False\nif out is None:\n out = x.add(self.eta)\n should_return = True\nelse:\n x.add(self.eta, out=out)\narr = out.as_array()\narr[arr > 0] ... | <|body_start_0|>
tmp_sum = (x + self.eta).as_array()
ind = tmp_sum >= 0
tmp = scipy.special.kl_div(self.b.as_array()[ind], tmp_sum[ind])
return numpy.sum(tmp)
<|end_body_0|>
<|body_start_1|>
should_return = False
if out is None:
out = x.add(self.eta)
... | KullbackLeibler_numpy | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KullbackLeibler_numpy:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
<|body_0|>
def gradient(self, x, out=None):
... | stack_v2_sparse_classes_75kplus_train_008485 | 18,813 | permissive | [
{
"docstring": "Returns the value of the KullbackLeibler function at :math:`(b, x + \\\\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\\\eta\\\\geq0`.",
"name": "__call__",
"signature": "def __call__(self, x)"
},
{
"docstring": "Returns the value of the ... | 5 | stack_v2_sparse_classes_30k_train_028111 | Implement the Python class `KullbackLeibler_numpy` described below.
Class description:
Implement the KullbackLeibler_numpy class.
Method signatures and docstrings:
- def __call__(self, x): Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only... | Implement the Python class `KullbackLeibler_numpy` described below.
Class description:
Implement the KullbackLeibler_numpy class.
Method signatures and docstrings:
- def __call__(self, x): Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only... | b0503d1b24cc71d937bbb780602d8778b36b0e77 | <|skeleton|>
class KullbackLeibler_numpy:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
<|body_0|>
def gradient(self, x, out=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KullbackLeibler_numpy:
def __call__(self, x):
"""Returns the value of the KullbackLeibler function at :math:`(b, x + \\eta)`. Note ---- To avoid infinity values, we consider only pixels/voxels for :math:`x+\\eta\\geq0`."""
tmp_sum = (x + self.eta).as_array()
ind = tmp_sum >= 0
... | the_stack_v2_python_sparse | Wrappers/Python/cil/optimisation/functions/KullbackLeibler.py | TomographicImaging/CIL | train | 72 | |
14935c8951193de3b8718182b8456168e31f57b4 | [
"self.smaller, self.bigger = ([], [])\nheapify(self.smaller)\nheapify(self.bigger)",
"heappush(self.bigger, num)\nheappush(self.smaller, -heappop(self.bigger))\nwhile len(self.smaller) > len(self.bigger):\n heappush(self.bigger, -heappop(self.smaller))",
"if len(self.smaller) == len(self.bigger):\n return... | <|body_start_0|>
self.smaller, self.bigger = ([], [])
heapify(self.smaller)
heapify(self.bigger)
<|end_body_0|>
<|body_start_1|>
heappush(self.bigger, num)
heappush(self.smaller, -heappop(self.bigger))
while len(self.smaller) > len(self.bigger):
heappush(self... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_008486 | 1,169 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_052967 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | 76d767ec001649b2df07aac211ac4b43b415ebdd | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.smaller, self.bigger = ([], [])
heapify(self.smaller)
heapify(self.bigger)
def addNum(self, num):
""":type num: int :rtype: None"""
heappush(self.bigger, num)
heappush... | the_stack_v2_python_sparse | leetcode295 Find Median from Data Stream.py | whglamrock/leetcode_series | train | 2 | |
aa1c580a44b5b6c4f26230be569d9ebcc5cebfc8 | [
"self.api_url_base = str(api_url_base)\nself.auth_params = auth_params\nself.auth_type = 'Bearer Token' if auth_type is None else auth_type\nself.api_version_prefix = '/apis/apps/v1' if api_version_prefix is None else str(api_version_prefix)\nself.headers = {}\nself.request_verify = None\nself.certs = None\nif self... | <|body_start_0|>
self.api_url_base = str(api_url_base)
self.auth_params = auth_params
self.auth_type = 'Bearer Token' if auth_type is None else auth_type
self.api_version_prefix = '/apis/apps/v1' if api_version_prefix is None else str(api_version_prefix)
self.headers = {}
... | 仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。 | K8SClientBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class K8SClientBase:
"""仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。"""
def __init__(self, api_url_base, auth_params, auth_type=None, api_version_prefix=None, ignore_https_verify=False, *args, **kwargs):
"""确定认证用的headers,以及与k8s-apiserver接口版本相关的基础url。 参数: api_url_base 字符串。如:'http://<i... | stack_v2_sparse_classes_75kplus_train_008487 | 4,117 | no_license | [
{
"docstring": "确定认证用的headers,以及与k8s-apiserver接口版本相关的基础url。 参数: api_url_base 字符串。如:'http://<ip>:<port>', 'https://<domain_name>' auth_type 可选范围:'Bearer Token', 'CA Certs'; 默认为'Bearer Token'。 auth_params 一个字典。记录的参数,用于传k8s接口认证。字典字段要求,随`auth_type`,有不同要求。 'Bearer Token',要求:{'bearer_token': '<a bearer token string>'... | 2 | stack_v2_sparse_classes_30k_val_000450 | Implement the Python class `K8SClientBase` described below.
Class description:
仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。
Method signatures and docstrings:
- def __init__(self, api_url_base, auth_params, auth_type=None, api_version_prefix=None, ignore_https_verify=False, *args, **kwargs): 确定认证用的headers,以及与k8s... | Implement the Python class `K8SClientBase` described below.
Class description:
仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。
Method signatures and docstrings:
- def __init__(self, api_url_base, auth_params, auth_type=None, api_version_prefix=None, ignore_https_verify=False, *args, **kwargs): 确定认证用的headers,以及与k8s... | 83b6a0d7662abf19d7b596a795b501baa77934d3 | <|skeleton|>
class K8SClientBase:
"""仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。"""
def __init__(self, api_url_base, auth_params, auth_type=None, api_version_prefix=None, ignore_https_verify=False, *args, **kwargs):
"""确定认证用的headers,以及与k8s-apiserver接口版本相关的基础url。 参数: api_url_base 字符串。如:'http://<i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class K8SClientBase:
"""仅适用于k8s-apiserver的直接认证调用。 对于各大云厂商的接口网关复杂认证方式,并不适用。"""
def __init__(self, api_url_base, auth_params, auth_type=None, api_version_prefix=None, ignore_https_verify=False, *args, **kwargs):
"""确定认证用的headers,以及与k8s-apiserver接口版本相关的基础url。 参数: api_url_base 字符串。如:'http://<ip>:<port>', '... | the_stack_v2_python_sparse | corelib/tools/k8s_clients/client_base.py | alan011/django-action-api | train | 16 |
ce8c87dfe67e6271d4a168734e1586244509fe97 | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units=units)\nself.U = tf.keras.layers.Dense(units=units)\nself.V = tf.keras.layers.Dense(units=1)",
"s_expanded = tf.expand_dims(input=s_prev, axis=1)\nfirst = self.W(s_expanded)\nsecond = self.U(hidden_states)\nscore = self.V(tf.nn.tanh(first + second))\natten... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
self.V = tf.keras.layers.Dense(units=1)
<|end_body_0|>
<|body_start_1|>
s_expanded = tf.expand_dims(input=s_prev, axis=1)
first = self.W(s_expanded... | SelfAttention | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""SelfAttention"""
def __init__(self, units):
"""V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Returns: context, weights"""
<|body_1|>... | stack_v2_sparse_classes_75kplus_train_008488 | 1,116 | no_license | [
{
"docstring": "V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "Returns: context, weights",
"name": "call",
"signature": "def call(self, s_prev, hidden_states)... | 2 | stack_v2_sparse_classes_30k_train_038748 | Implement the Python class `SelfAttention` described below.
Class description:
SelfAttention
Method signatures and docstrings:
- def __init__(self, units): V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U
- def call(self, s_prev, hidden_states): Returns: context, weights | Implement the Python class `SelfAttention` described below.
Class description:
SelfAttention
Method signatures and docstrings:
- def __init__(self, units): V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U
- def call(self, s_prev, hidden_states): Returns: context, weights
... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class SelfAttention:
"""SelfAttention"""
def __init__(self, units):
"""V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Returns: context, weights"""
<|body_1|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""SelfAttention"""
def __init__(self, units):
"""V - a Dense layer with 1 units, to be applied to the tanh of the sum of the outputs of W and U"""
super().__init__()
self.W = tf.keras.layers.Dense(units=units)
self.U = tf.keras.layers.Dense(units=units)
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | Nzparra/holbertonschool-machine_learning | train | 0 |
bb081255958b594a77b7f51a63e7a8da201f90bd | [
"time.sleep(0.2)\noriginal_count = threading.active_count()\nwith VirtualPump():\n self.assertEqual(threading.active_count(), original_count + 2)\ntime.sleep(0.2)\nself.assertEqual(threading.active_count(), original_count)",
"time.sleep(0.2)\noriginal_count = threading.active_count()\nvp = VirtualPump()\nself.... | <|body_start_0|>
time.sleep(0.2)
original_count = threading.active_count()
with VirtualPump():
self.assertEqual(threading.active_count(), original_count + 2)
time.sleep(0.2)
self.assertEqual(threading.active_count(), original_count)
<|end_body_0|>
<|body_start_1|>
... | Make sure VirtualPump shuts down all parallel threads properly. | TestStop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStop:
"""Make sure VirtualPump shuts down all parallel threads properly."""
def test_with_block(self):
"""Test the __enter__ and __exit__ methods."""
<|body_0|>
def test_stop(self):
"""Test manually stopping VirtualPump."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_008489 | 5,580 | no_license | [
{
"docstring": "Test the __enter__ and __exit__ methods.",
"name": "test_with_block",
"signature": "def test_with_block(self)"
},
{
"docstring": "Test manually stopping VirtualPump.",
"name": "test_stop",
"signature": "def test_stop(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023947 | Implement the Python class `TestStop` described below.
Class description:
Make sure VirtualPump shuts down all parallel threads properly.
Method signatures and docstrings:
- def test_with_block(self): Test the __enter__ and __exit__ methods.
- def test_stop(self): Test manually stopping VirtualPump. | Implement the Python class `TestStop` described below.
Class description:
Make sure VirtualPump shuts down all parallel threads properly.
Method signatures and docstrings:
- def test_with_block(self): Test the __enter__ and __exit__ methods.
- def test_stop(self): Test manually stopping VirtualPump.
<|skeleton|>
cla... | a29f2c92cac65b2d2b8d89c69944277ae3eb8753 | <|skeleton|>
class TestStop:
"""Make sure VirtualPump shuts down all parallel threads properly."""
def test_with_block(self):
"""Test the __enter__ and __exit__ methods."""
<|body_0|>
def test_stop(self):
"""Test manually stopping VirtualPump."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStop:
"""Make sure VirtualPump shuts down all parallel threads properly."""
def test_with_block(self):
"""Test the __enter__ and __exit__ methods."""
time.sleep(0.2)
original_count = threading.active_count()
with VirtualPump():
self.assertEqual(threading.ac... | the_stack_v2_python_sparse | test_turboctl/virtualpump/test_virtualpump.py | fkivela/TurboCtl | train | 2 |
e381f18b984fef06e950748af9385892348bb0b3 | [
"Category = CategoryModel.find_by_id(id)\nif Category:\n return Category.json()\nreturn ({'message': 'Category not found'}, 404)",
"if CategoryModel.find_by_id(id):\n return ({'message': \"A Category with id '{}' already exists.\".format(id)}, 400)\nCategory = CategoryModel(id)\ntry:\n Category.save_to_d... | <|body_start_0|>
Category = CategoryModel.find_by_id(id)
if Category:
return Category.json()
return ({'message': 'Category not found'}, 404)
<|end_body_0|>
<|body_start_1|>
if CategoryModel.find_by_id(id):
return ({'message': "A Category with id '{}' already exis... | Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:id> | Category | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Category:
"""Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:id>"""
def get(self, id):
... | stack_v2_sparse_classes_75kplus_train_008490 | 8,266 | permissive | [
{
"docstring": "GET request that deals with requests that look for a category by id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "POST request that deals with creation of a category provided an id",
"name": "post",
"signature": "def post(self, id)"
},
{
"do... | 4 | null | Implement the Python class `Category` described below.
Class description:
Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:... | Implement the Python class `Category` described below.
Class description:
Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:... | 42456ced804a2c9570227b393de662847283c76f | <|skeleton|>
class Category:
"""Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:id>"""
def get(self, id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Category:
"""Category. Resource that helps with dealing with Http request for a category by providing its id. HTTP GET call : /categories/<int:id> HTTP POST call : /categories/<int:id> HTTP PUT call : /categories/<int:id> HTTP DELETE call : /categories/<int:id>"""
def get(self, id):
"""GET reques... | the_stack_v2_python_sparse | resources/category.py | basgir/bibliotek | train | 0 |
5716b5f02e9f550df441f371313598e695e5933e | [
"if request.user.is_authenticated:\n routes = UserRoute.objects.filter(route_user=request.user)\n routes = list(routes)\n routes_list = [{'route_start': route.route_start, 'route_end': route.route_end} for route in routes]\n json_file = {'user_routes_list': routes_list, 'res': 1}\n return JsonRespons... | <|body_start_0|>
if request.user.is_authenticated:
routes = UserRoute.objects.filter(route_user=request.user)
routes = list(routes)
routes_list = [{'route_start': route.route_start, 'route_end': route.route_end} for route in routes]
json_file = {'user_routes_list'... | store the favorite routes of user | FavoriteRouteView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteRouteView:
"""store the favorite routes of user"""
def get(self, request):
"""return the user's favortie route list"""
<|body_0|>
def post(self, request):
"""add new route information"""
<|body_1|>
def delete(self, request):
"""remove... | stack_v2_sparse_classes_75kplus_train_008491 | 28,206 | no_license | [
{
"docstring": "return the user's favortie route list",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "add new route information",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "remove the route from the favorite list",
"nam... | 3 | stack_v2_sparse_classes_30k_train_002639 | Implement the Python class `FavoriteRouteView` described below.
Class description:
store the favorite routes of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie route list
- def post(self, request): add new route information
- def delete(self, request): remove the route from... | Implement the Python class `FavoriteRouteView` described below.
Class description:
store the favorite routes of user
Method signatures and docstrings:
- def get(self, request): return the user's favortie route list
- def post(self, request): add new route information
- def delete(self, request): remove the route from... | 5efeebedd4695ef9d904beb707a1538ba049b187 | <|skeleton|>
class FavoriteRouteView:
"""store the favorite routes of user"""
def get(self, request):
"""return the user's favortie route list"""
<|body_0|>
def post(self, request):
"""add new route information"""
<|body_1|>
def delete(self, request):
"""remove... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteRouteView:
"""store the favorite routes of user"""
def get(self, request):
"""return the user's favortie route list"""
if request.user.is_authenticated:
routes = UserRoute.objects.filter(route_user=request.user)
routes = list(routes)
routes_list... | the_stack_v2_python_sparse | dbbus/apps/user/views.py | mofiebiger/DublinBus | train | 1 |
86eb73238503a9b1b4eecc65776c8dc0a9c9a2b7 | [
"self.active_opens = active_opens\nself.client_ip = client_ip\nself.domain = domain\nself.server_ip = server_ip\nself.session_id = session_id\nself.username = username",
"if dictionary is None:\n return None\nactive_opens = None\nif dictionary.get('activeOpens') != None:\n active_opens = list()\n for str... | <|body_start_0|>
self.active_opens = active_opens
self.client_ip = client_ip
self.domain = domain
self.server_ip = server_ip
self.session_id = session_id
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is still open. domain (string): Specifies the doma... | SmbActiveSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is sti... | stack_v2_sparse_classes_75kplus_train_008492 | 2,939 | permissive | [
{
"docstring": "Constructor for the SmbActiveSession class",
"name": "__init__",
"signature": "def __init__(self, active_opens=None, client_ip=None, domain=None, server_ip=None, session_id=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictiona... | 2 | stack_v2_sparse_classes_30k_train_014071 | Implement the Python class `SmbActiveSession` described below.
Class description:
Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies th... | Implement the Python class `SmbActiveSession` described below.
Class description:
Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is sti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is still open. doma... | the_stack_v2_python_sparse | cohesity_management_sdk/models/smb_active_session.py | cohesity/management-sdk-python | train | 24 |
6624fd84c6b1f5e0132a61e1bef7c09ccec13819 | [
"now = utils.utcnow()\nkey = ndb.Key(models.Instance, 'fake-key')\nmetadata.associate_metadata_operation(key, 'checksum', 'url', now)\nself.failIf(key.get())",
"now = utils.utcnow()\nkey = models.Instance(key=instances.get_instance_key('base-name', 'revision', 'zone', 'instance-name')).put()\nmetadata.associate_m... | <|body_start_0|>
now = utils.utcnow()
key = ndb.Key(models.Instance, 'fake-key')
metadata.associate_metadata_operation(key, 'checksum', 'url', now)
self.failIf(key.get())
<|end_body_0|>
<|body_start_1|>
now = utils.utcnow()
key = models.Instance(key=instances.get_instanc... | Tests for metadata.associate_metadata_operation. | AssociateMetadataOperationTest | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssociateMetadataOperationTest:
"""Tests for metadata.associate_metadata_operation."""
def test_not_found(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_no_active_metadata_update(self):
"""Ensures nothing happens when acti... | stack_v2_sparse_classes_75kplus_train_008493 | 29,404 | permissive | [
{
"docstring": "Ensures nothing happens when the entity doesn't exist.",
"name": "test_not_found",
"signature": "def test_not_found(self)"
},
{
"docstring": "Ensures nothing happens when active metadata update is unspecified.",
"name": "test_no_active_metadata_update",
"signature": "def ... | 6 | null | Implement the Python class `AssociateMetadataOperationTest` described below.
Class description:
Tests for metadata.associate_metadata_operation.
Method signatures and docstrings:
- def test_not_found(self): Ensures nothing happens when the entity doesn't exist.
- def test_no_active_metadata_update(self): Ensures noth... | Implement the Python class `AssociateMetadataOperationTest` described below.
Class description:
Tests for metadata.associate_metadata_operation.
Method signatures and docstrings:
- def test_not_found(self): Ensures nothing happens when the entity doesn't exist.
- def test_no_active_metadata_update(self): Ensures noth... | 3fa4c520dddd82ed190152709e0a54b35faa3bae | <|skeleton|>
class AssociateMetadataOperationTest:
"""Tests for metadata.associate_metadata_operation."""
def test_not_found(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_no_active_metadata_update(self):
"""Ensures nothing happens when acti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssociateMetadataOperationTest:
"""Tests for metadata.associate_metadata_operation."""
def test_not_found(self):
"""Ensures nothing happens when the entity doesn't exist."""
now = utils.utcnow()
key = ndb.Key(models.Instance, 'fake-key')
metadata.associate_metadata_operati... | the_stack_v2_python_sparse | appengine/gce-backend/metadata_test.py | Slayo2008/New2 | train | 1 |
eb351043dafa2dcc0442927f55d68529403ea56e | [
"super(RaDNet, self).__init__()\nin_nc = opt['network_D']['in_nc']\nnf = opt['network_D']['nf']\nleak = opt['network_G']['activation_leak']\nbeta = opt['network_G']['residual_scaling']\nself.conv0_0 = Conv2D(nf, kernel_size=3, strides=1, padding='same', use_bias=True, name='conv0_0')\nself.conv0_1 = Conv2D(nf, kern... | <|body_start_0|>
super(RaDNet, self).__init__()
in_nc = opt['network_D']['in_nc']
nf = opt['network_D']['nf']
leak = opt['network_G']['activation_leak']
beta = opt['network_G']['residual_scaling']
self.conv0_0 = Conv2D(nf, kernel_size=3, strides=1, padding='same', use_bia... | Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class. | RaDNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RaDNet:
"""Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class."""
def __init__(self, opt):
"""Initializes the discriminator architecture. Attributes: opt: th... | stack_v2_sparse_classes_75kplus_train_008494 | 3,627 | no_license | [
{
"docstring": "Initializes the discriminator architecture. Attributes: opt: the config file",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Forward pass through the network. Args: x: input of the network Returns: The output of the network",
"name": "call",
... | 2 | stack_v2_sparse_classes_30k_train_038913 | Implement the Python class `RaDNet` described below.
Class description:
Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class.
Method signatures and docstrings:
- def __init__(self, opt): Initia... | Implement the Python class `RaDNet` described below.
Class description:
Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class.
Method signatures and docstrings:
- def __init__(self, opt): Initia... | 4809e454512fefe168bebc31cfc8f78e138b7790 | <|skeleton|>
class RaDNet:
"""Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class."""
def __init__(self, opt):
"""Initializes the discriminator architecture. Attributes: opt: th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RaDNet:
"""Represents a discriminator network in the ERSGAN architecture. This network follows the one described in the paper, implemented as a VGG128 network Extends the keras Model class."""
def __init__(self, opt):
"""Initializes the discriminator architecture. Attributes: opt: the config file... | the_stack_v2_python_sparse | models/RaDNet.py | mchatton/w2s-tensorflow | train | 16 |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nservice = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_FOUND')\nres = cm.api.get_import(cluster, service)\nreturn Response(res)",
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nservice = check_obj(Clu... | <|body_start_0|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
service = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_FOUND')
res = cm.api.get_import(cluster, service)
return Response(res)
<|end_body_0|>
<|body_start_1|>
cluster =... | ClusterServiceImport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
<|body_0|>
def post(self, request, cluster_id, service_id):
"""Update bind for service in cluster"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_008495 | 32,530 | permissive | [
{
"docstring": "List all imports avaliable for specified service in cluster",
"name": "get",
"signature": "def get(self, request, cluster_id, service_id)"
},
{
"docstring": "Update bind for service in cluster",
"name": "post",
"signature": "def post(self, request, cluster_id, service_id)... | 2 | stack_v2_sparse_classes_30k_train_009911 | Implement the Python class `ClusterServiceImport` described below.
Class description:
Implement the ClusterServiceImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id, service_id): List all imports avaliable for specified service in cluster
- def post(self, request, cluster_id, service_... | Implement the Python class `ClusterServiceImport` described below.
Class description:
Implement the ClusterServiceImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id, service_id): List all imports avaliable for specified service in cluster
- def post(self, request, cluster_id, service_... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
<|body_0|>
def post(self, request, cluster_id, service_id):
"""Update bind for service in cluster"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterServiceImport:
def get(self, request, cluster_id, service_id):
"""List all imports avaliable for specified service in cluster"""
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
service = check_obj(ClusterObject, {'cluster': cluster, 'id': service_id}, 'SERVICE_NOT_... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 | |
85c11dac699aa07192c414452476308a76347796 | [
"if head is None:\n return None\nnew_head = self.reverseList(head.next)\nif new_head:\n tmp = new_head\n while tmp.next:\n tmp = tmp.next\n tmp.next = head\n head.next = None\nelse:\n new_head = head\nreturn new_head",
"if head is None or head.next is None:\n return head\np = self.reve... | <|body_start_0|>
if head is None:
return None
new_head = self.reverseList(head.next)
if new_head:
tmp = new_head
while tmp.next:
tmp = tmp.next
tmp.next = head
head.next = None
else:
new_head = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseListV2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseListV3(self, head):
""":type head: ListNode :rtype: Lis... | stack_v2_sparse_classes_75kplus_train_008496 | 1,364 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseListV2",
"signature": "def reverseListV2(self, head)"
},
{
"docstring": ":type head... | 3 | stack_v2_sparse_classes_30k_test_001109 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV2(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV3(self, head): :type h... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV2(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV3(self, head): :type h... | 266def94df8245f90ea5b6885fc472470b189e51 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseListV2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseListV3(self, head):
""":type head: ListNode :rtype: Lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if head is None:
return None
new_head = self.reverseList(head.next)
if new_head:
tmp = new_head
while tmp.next:
tmp = tmp.next
tmp.... | the_stack_v2_python_sparse | 206_Reverse_Linked_List.py | GuangyuZheng/leet_code_python | train | 2 | |
50594984c84de39d3c69350b562d05eb95bb26da | [
"super().__init__()\nself.embedder = embedder\nself.output_layer = output_layer\nself.drop = nn.Dropout(dropout)\nself.pad_index = pad_index\nself.tie_weights = tie_weights\nif tie_weights:\n module = self.embedder\n for attr in tie_weight_attr.split('.'):\n module = getattr(module, attr)\n self.out... | <|body_start_0|>
super().__init__()
self.embedder = embedder
self.output_layer = output_layer
self.drop = nn.Dropout(dropout)
self.pad_index = pad_index
self.tie_weights = tie_weights
if tie_weights:
module = self.embedder
for attr in tie_w... | Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multiplied by the sequence length. | LanguageModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multip... | stack_v2_sparse_classes_75kplus_train_008497 | 3,321 | permissive | [
{
"docstring": "Initialize the LanguageModel model. Parameters ---------- embedder: Embedder The embedder layer output_layer : Decoder Output layer to use dropout : float, optional Amount of droput between the encoder and decoder, defaults to 0. pad_index: int, optional Index used for padding, defaults to 0 tie... | 2 | stack_v2_sparse_classes_30k_train_042019 | Implement the Python class `LanguageModel` described below.
Class description:
Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the n... | Implement the Python class `LanguageModel` described below.
Class description:
Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the n... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LanguageModel:
"""Implement an LanguageModel model for sequential classification. This model can be used to language modeling, as well as other sequential classification tasks. The full sequence predictions are produced by the model, effectively making the number of examples the batch size multiplied by the s... | the_stack_v2_python_sparse | flambe/nlp/language_modeling/model.py | cle-ros/flambe | train | 1 |
408972fb5304df4cced7a7bdb64926f5001a0fa0 | [
"timer = RepeatingTimer(monitor.CYCLE, monitor.safe_run_monitor, test)\ntimer.start()\ncls.MONITORS[monitor] = timer",
"if monitor not in cls.MONITORS:\n return\nthread = cls.MONITORS[monitor]\nthread.cancel()\nthread.join()\ncls.MONITORS.pop(monitor)"
] | <|body_start_0|>
timer = RepeatingTimer(monitor.CYCLE, monitor.safe_run_monitor, test)
timer.start()
cls.MONITORS[monitor] = timer
<|end_body_0|>
<|body_start_1|>
if monitor not in cls.MONITORS:
return
thread = cls.MONITORS[monitor]
thread.cancel()
th... | Monitors manager class, for activating and deactivating monitors. | MonitorServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitorServer:
"""Monitors manager class, for activating and deactivating monitors."""
def register_monitor(cls, monitor, test):
"""Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item instance."""
<|body_0|>
def unregister_monitor(c... | stack_v2_sparse_classes_75kplus_train_008498 | 1,586 | permissive | [
{
"docstring": "Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item instance.",
"name": "register_monitor",
"signature": "def register_monitor(cls, monitor, test)"
},
{
"docstring": "Stop monitor. Args: monitor (AbstractMonitor): monitor instance.",
"na... | 2 | stack_v2_sparse_classes_30k_train_048218 | Implement the Python class `MonitorServer` described below.
Class description:
Monitors manager class, for activating and deactivating monitors.
Method signatures and docstrings:
- def register_monitor(cls, monitor, test): Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item inst... | Implement the Python class `MonitorServer` described below.
Class description:
Monitors manager class, for activating and deactivating monitors.
Method signatures and docstrings:
- def register_monitor(cls, monitor, test): Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item inst... | c443bc1b99e02f047adfcab9943966f0023f652c | <|skeleton|>
class MonitorServer:
"""Monitors manager class, for activating and deactivating monitors."""
def register_monitor(cls, monitor, test):
"""Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item instance."""
<|body_0|>
def unregister_monitor(c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonitorServer:
"""Monitors manager class, for activating and deactivating monitors."""
def register_monitor(cls, monitor, test):
"""Start monitor. Args: monitor (AbstractMonitor): monitor instance. test (object): test item instance."""
timer = RepeatingTimer(monitor.CYCLE, monitor.safe_ru... | the_stack_v2_python_sparse | src/rotest/core/result/monitor/server.py | gregoil/rotest | train | 26 |
da870b8b761d45d90f2b88d06d0fd53082368f15 | [
"assert alpha >= 0\nsuper(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma)\nself.max_priority, self.tree_ptr = (1.0, 0)\nself.alpha = alpha\ntree_capacity = 1\nwhile tree_capacity < self.max_size:\n tree_capacity *= 2\nself.sum_tree = SumSegmentTree(tree_capacity)\nself.min_tree = MinSegm... | <|body_start_0|>
assert alpha >= 0
super(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma)
self.max_priority, self.tree_ptr = (1.0, 0)
self.alpha = alpha
tree_capacity = 1
while tree_capacity < self.max_size:
tree_capacity *= 2
s... | Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight | PrioritizedReplayBuffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ... | stack_v2_sparse_classes_75kplus_train_008499 | 26,535 | no_license | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99)"
},
{
"docstring": "Store experience and priority.",
"name": "store",
"signature": "def store(self, obs: OdinsynthEnvS... | 6 | stack_v2_sparse_classes_30k_train_037747 | Implement the Python class `PrioritizedReplayBuffer` described below.
Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS... | Implement the Python class `PrioritizedReplayBuffer` described below.
Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS... | 60e0c3389724460b5b32ba35c89d8838da4d51c9 | <|skeleton|>
class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weigh... | the_stack_v2_python_sparse | lrec2022-odinsynth/python/rl_rainbow_implementation.py | clulab/releases | train | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.