blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dda4d6fdf84bc343cdbe94d0be98fc87c12a55ef | [
"assert verifiers, 'At least one verifier is required'\nif __debug__:\n for verifier in verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier\nself.verifiers = verifiers",
"for verifier in self.verifiers:\n assert isinstance(verifier, IVerifier), 'Invalid verifier %s' ... | <|body_start_0|>
assert verifiers, 'At least one verifier is required'
if __debug__:
for verifier in verifiers:
assert isinstance(verifier, IVerifier), 'Invalid verifier %s' % verifier
self.verifiers = verifiers
<|end_body_0|>
<|body_start_1|>
for verifier in... | Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers. | VerifierOr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
<|body_0|>
def prepare(se... | stack_v2_sparse_classes_36k_train_032800 | 15,633 | no_license | [
{
"docstring": "Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for.",
"name": "__init__",
"signature": "def __init__(self, *verifiers)"
},
{
"docstring": "@see: IVerifier.prepare",
"name": "prepare",
"signature": "def prepare(self, res... | 3 | null | Implement the Python class `VerifierOr` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to appl... | Implement the Python class `VerifierOr` described below.
Class description:
Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers.
Method signatures and docstrings:
- def __init__(self, *verifiers): Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to appl... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
<|body_0|>
def prepare(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerifierOr:
"""Implementation for a @see: IVerifier that aplies an 'or' operator between verifiers."""
def __init__(self, *verifiers):
"""Construct the 'or' verifier. @param verifiers: arguments[IVerifier] The verifiers to apply the 'or' for."""
assert verifiers, 'At least one verifier is... | the_stack_v2_python_sparse | components/ally-core/ally/core/impl/definition.py | cristidomsa/Ally-Py | train | 0 |
fc04a3afb6a058d44814c8bffe404af229a97fce | [
"self.a = a\nself.b = b\nself.cx = cx\nself.cy = cy\nself.theta = theta",
"x = self.a * np.cos(alpha) * np.cos(self.theta) - self.b * np.sin(alpha) * np.sin(self.theta) + self.cx\ny = self.a * np.cos(alpha) * np.sin(self.theta) + self.b * np.sin(alpha) * np.cos(self.theta) + self.cy\nreturn (x, y)"
] | <|body_start_0|>
self.a = a
self.b = b
self.cx = cx
self.cy = cy
self.theta = theta
<|end_body_0|>
<|body_start_1|>
x = self.a * np.cos(alpha) * np.cos(self.theta) - self.b * np.sin(alpha) * np.sin(self.theta) + self.cx
y = self.a * np.cos(alpha) * np.sin(self.th... | Ellipse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ellipse:
def __init__(self, a=1, b=1, cx=0, cy=0, theta=0):
"""Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated"""
<|body_0|>
def get_el... | stack_v2_sparse_classes_36k_train_032801 | 12,432 | no_license | [
{
"docstring": "Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated",
"name": "__init__",
"signature": "def __init__(self, a=1, b=1, cx=0, cy=0, theta=0)"
},
{
... | 2 | null | Implement the Python class `Ellipse` described below.
Class description:
Implement the Ellipse class.
Method signatures and docstrings:
- def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ell... | Implement the Python class `Ellipse` described below.
Class description:
Implement the Ellipse class.
Method signatures and docstrings:
- def __init__(self, a=1, b=1, cx=0, cy=0, theta=0): Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ell... | 3be1c0d1a96b7d220c2aba1515af6095712c65bc | <|skeleton|>
class Ellipse:
def __init__(self, a=1, b=1, cx=0, cy=0, theta=0):
"""Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated"""
<|body_0|>
def get_el... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ellipse:
def __init__(self, a=1, b=1, cx=0, cy=0, theta=0):
"""Create an ellipse object Args: a -- major radius b -- minor radius cx -- x coordinate of ellipse center cy -- y coordinate of ellipse center theta -- angle by which the ellipse is rotated"""
self.a = a
self.b = b
se... | the_stack_v2_python_sparse | riseq_perception/scripts/ellipse_detector.py | juanmed/riseq_uav | train | 3 | |
8a0df03cb743d8d5818818c61fc699fa86c1505e | [
"self.d_model = d_model\nself.d_k = d_k\nself.d_v = d_v\nself.sequence_length = sequence_length\nself.h = h\nself.num_layer = num_layer\nself.batch_size = batch_size\nself.decoder_sent_length = decoder_sent_length",
"with tf.variable_scope('sub_layer_postion_wise_feed_forward' + str(layer_index)):\n postion_wi... | <|body_start_0|>
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.sequence_length = sequence_length
self.h = h
self.num_layer = num_layer
self.batch_size = batch_size
self.decoder_sent_length = decoder_sent_length
<|end_body_0|>
<|body_start_1|>
... | base class has some common fields and functions. | BaseClass | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embed... | stack_v2_sparse_classes_36k_train_032802 | 4,426 | permissive | [
{
"docstring": ":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: shape:[batch_size,sequence_length,embed_size]",
"name": "__init__",
"signature": "def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder... | 4 | stack_v2_sparse_classes_30k_train_019094 | Implement the Python class `BaseClass` described below.
Class description:
base class has some common fields and functions.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param s... | Implement the Python class `BaseClass` described below.
Class description:
base class has some common fields and functions.
Method signatures and docstrings:
- def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None): :param d_model: :param d_k: :param d_v: :param s... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embed... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseClass:
"""base class has some common fields and functions."""
def __init__(self, d_model, d_k, d_v, sequence_length, h, batch_size, num_layer=6, decoder_sent_length=None):
""":param d_model: :param d_k: :param d_v: :param sequence_length: :param h: :param batch_size: :param embedded_words: sh... | the_stack_v2_python_sparse | bert_language_understanding-master/bert_language_understanding-master/model/base_model.py | yyht/BERT | train | 37 |
cfcea6e812f6ca96691730b7ce3c9e5bb034f6bb | [
"self.ip_address = ip_address\nself.port = port\nself.application_name = application_name",
"try:\n connection_url = 'tcp://' + self.ip_address + ':' + str(self.port)\n app = qi.Application([self.application_name, '--qi-url=' + connection_url])\nexcept RuntimeError:\n print('Can\\'t connect to Naoqi at i... | <|body_start_0|>
self.ip_address = ip_address
self.port = port
self.application_name = application_name
<|end_body_0|>
<|body_start_1|>
try:
connection_url = 'tcp://' + self.ip_address + ':' + str(self.port)
app = qi.Application([self.application_name, '--qi-url=... | QiApplication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
<|body_0|>
def connect(self):
"""Establish a Qi-application and connect to robot"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ip... | stack_v2_sparse_classes_36k_train_032803 | 947 | no_license | [
{
"docstring": "Initialise variables for connection",
"name": "__init__",
"signature": "def __init__(self, application_name, ip_address, port)"
},
{
"docstring": "Establish a Qi-application and connect to robot",
"name": "connect",
"signature": "def connect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020766 | Implement the Python class `QiApplication` described below.
Class description:
Implement the QiApplication class.
Method signatures and docstrings:
- def __init__(self, application_name, ip_address, port): Initialise variables for connection
- def connect(self): Establish a Qi-application and connect to robot | Implement the Python class `QiApplication` described below.
Class description:
Implement the QiApplication class.
Method signatures and docstrings:
- def __init__(self, application_name, ip_address, port): Initialise variables for connection
- def connect(self): Establish a Qi-application and connect to robot
<|skel... | ed3008d4ac864ec9c5b9384144c6a80c98c8c871 | <|skeleton|>
class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
<|body_0|>
def connect(self):
"""Establish a Qi-application and connect to robot"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
self.ip_address = ip_address
self.port = port
self.application_name = application_name
def connect(self):
"""Establish a Qi-application and connect to r... | the_stack_v2_python_sparse | mgribb3n-pepper-5bababb73a86/RobotServices/qiApplication.py | GustavSB/pepper-code | train | 0 | |
31e5f727d55c324bd3931ceb70519d5533cd67e7 | [
"post = get_post(post_id)\npost_dto = post_to_dto(post, href=req.uri, links=get_post_links(req, post))\npost_comments = get_post_comments(post_id)\npost_dto.comments = [comment_to_dto(comment, href=comments.CommentResource.url_to(req.netloc, comment_id=str(comment.id), links=comments.get_comment_links(req, comment)... | <|body_start_0|>
post = get_post(post_id)
post_dto = post_to_dto(post, href=req.uri, links=get_post_links(req, post))
post_comments = get_post_comments(post_id)
post_dto.comments = [comment_to_dto(comment, href=comments.CommentResource.url_to(req.netloc, comment_id=str(comment.id), links... | PostResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostResource:
def on_get(self, req, resp, post_id):
"""Fetch single post resource."""
<|body_0|>
def on_put(self, req, resp, post_id):
"""Update single post resource."""
<|body_1|>
def on_delete(self, req, resp, post_id):
"""Delete single post re... | stack_v2_sparse_classes_36k_train_032804 | 7,743 | permissive | [
{
"docstring": "Fetch single post resource.",
"name": "on_get",
"signature": "def on_get(self, req, resp, post_id)"
},
{
"docstring": "Update single post resource.",
"name": "on_put",
"signature": "def on_put(self, req, resp, post_id)"
},
{
"docstring": "Delete single post resour... | 3 | stack_v2_sparse_classes_30k_train_020544 | Implement the Python class `PostResource` described below.
Class description:
Implement the PostResource class.
Method signatures and docstrings:
- def on_get(self, req, resp, post_id): Fetch single post resource.
- def on_put(self, req, resp, post_id): Update single post resource.
- def on_delete(self, req, resp, po... | Implement the Python class `PostResource` described below.
Class description:
Implement the PostResource class.
Method signatures and docstrings:
- def on_get(self, req, resp, post_id): Fetch single post resource.
- def on_put(self, req, resp, post_id): Update single post resource.
- def on_delete(self, req, resp, po... | e507fe0307d1a7ea29d6c3e20be62fa82a8f109f | <|skeleton|>
class PostResource:
def on_get(self, req, resp, post_id):
"""Fetch single post resource."""
<|body_0|>
def on_put(self, req, resp, post_id):
"""Update single post resource."""
<|body_1|>
def on_delete(self, req, resp, post_id):
"""Delete single post re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostResource:
def on_get(self, req, resp, post_id):
"""Fetch single post resource."""
post = get_post(post_id)
post_dto = post_to_dto(post, href=req.uri, links=get_post_links(req, post))
post_comments = get_post_comments(post_id)
post_dto.comments = [comment_to_dto(comm... | the_stack_v2_python_sparse | blog/resources/posts.py | neetjn/py-blog | train | 0 | |
ae81d19eaae8338e999c2d9c9e55641a57ee292e | [
"self.Wz = np.random.normal(size=(i + h, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"x_concat0 = np.concaten... | <|body_start_0|>
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.bz = np.zeros((1, h))
self.br = np.zeros((1... | Represents a gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""x_t is a numpy... | stack_v2_sparse_classes_36k_train_032805 | 1,724 | no_license | [
{
"docstring": "i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "x_t is a numpy.ndarray of shape (m, i) that contains the data input for the c... | 2 | stack_v2_sparse_classes_30k_train_014956 | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward(self, h_prev,... | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward(self, h_prev,... | d3802fc2e552447cd5b17d1ed593aee46a8ae929 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""x_t is a numpy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | RodrigoSierraV/holbertonschool-machine_learning | train | 0 |
8e7e5d3ffb120c138c55f240ae4f3b09793009ed | [
"import rasterio\nself.fn = fn\nself.sub_domains = sub_domains\nself._parse_alf_fn()\nself.rst = rasterio.open(self.fn)\nself._band_reader()\nself.sub_domains = sub_domains",
"import os\ndirname, basename = os.path.split(self.fn)\nvariable, replicate, year_ext = basename.split('_')\nyear, ext = year_ext.split('.'... | <|body_start_0|>
import rasterio
self.fn = fn
self.sub_domains = sub_domains
self._parse_alf_fn()
self.rst = rasterio.open(self.fn)
self._band_reader()
self.sub_domains = sub_domains
<|end_body_0|>
<|body_start_1|>
import os
dirname, basename = os... | class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations. | AlfrescoDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlfrescoDataset:
"""class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations."""
def __init__(self, fn, sub_domains=None, *args, **kwargs):
"""parse elemets of the f... | stack_v2_sparse_classes_36k_train_032806 | 7,782 | no_license | [
{
"docstring": "parse elemets of the filename passed arguments: ---------- fn = [str] path to the input alfresco generated file of type FireScar, Age, or Veg nodata = [scalar] value to use as a background so final counts do not include it. sub_domains = [alfresco_postprocessing.SubDomains] alfresco_postprocessi... | 3 | stack_v2_sparse_classes_30k_val_000830 | Implement the Python class `AlfrescoDataset` described below.
Class description:
class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations.
Method signatures and docstrings:
- def __init__(self, fn, s... | Implement the Python class `AlfrescoDataset` described below.
Class description:
class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations.
Method signatures and docstrings:
- def __init__(self, fn, s... | c16ccc2b3d335cc5bb1df16b79aebc8510210a77 | <|skeleton|>
class AlfrescoDataset:
"""class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations."""
def __init__(self, fn, sub_domains=None, *args, **kwargs):
"""parse elemets of the f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlfrescoDataset:
"""class to take an output ALFRESCO generated output dataset of the flavor Veg, Age, or FireScar and break its filename (fn) to elements needed in summary statistics calculations."""
def __init__(self, fn, sub_domains=None, *args, **kwargs):
"""parse elemets of the filename passe... | the_stack_v2_python_sparse | alfresco_postprocessing/_working_test.py | ua-snap/alfresco_postprocessing | train | 0 |
45d00b828df76ac8c1559ad7f65ac87d0cf76950 | [
"self.defaults = deepcopy(DEFAULTS)\nself.defaults.update(extend_defaults)\nself.allowed_keys_with_dtype = deepcopy(ALLOWED_KEYS_WITH_DTYPE)\nself.allowed_keys_with_dtype.update(extend_allowed_keys_with_dtype)",
"parsed_kwargs = {}\nerr_list = []\nquery_param = kwargs.get('query_param')\nstatement = '{container}.... | <|body_start_0|>
self.defaults = deepcopy(DEFAULTS)
self.defaults.update(extend_defaults)
self.allowed_keys_with_dtype = deepcopy(ALLOWED_KEYS_WITH_DTYPE)
self.allowed_keys_with_dtype.update(extend_allowed_keys_with_dtype)
<|end_body_0|>
<|body_start_1|>
parsed_kwargs = {}
... | Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers. | QueryParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryParser:
"""Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers."""
def __init__(self, extend_defaults: dict={}, extend_allowed_keys_with_dtype: dict={}):
"""Query parse co... | stack_v2_sparse_classes_36k_train_032807 | 3,063 | no_license | [
{
"docstring": "Query parse constructor, which can be used to extend allowed query parameters for the specific data manager. Default values can also be updated and extended.",
"name": "__init__",
"signature": "def __init__(self, extend_defaults: dict={}, extend_allowed_keys_with_dtype: dict={})"
},
... | 2 | stack_v2_sparse_classes_30k_train_010616 | Implement the Python class `QueryParser` described below.
Class description:
Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers.
Method signatures and docstrings:
- def __init__(self, extend_defaults: dict={},... | Implement the Python class `QueryParser` described below.
Class description:
Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers.
Method signatures and docstrings:
- def __init__(self, extend_defaults: dict={},... | 7bca15c619e1fca5d3b756661cc336fadbad669a | <|skeleton|>
class QueryParser:
"""Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers."""
def __init__(self, extend_defaults: dict={}, extend_allowed_keys_with_dtype: dict={}):
"""Query parse co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryParser:
"""Parser utility to help parsing query parameters. It comes with some default query parameters, which can easily be extended as per the need of the data managers."""
def __init__(self, extend_defaults: dict={}, extend_allowed_keys_with_dtype: dict={}):
"""Query parse constructor, wh... | the_stack_v2_python_sparse | demo/services/api/src/app/shared/utils/query_parser.py | dipangshu15/flask_boilerplate | train | 0 |
31d527a544437cb4deac06a44ce603773282d238 | [
"hrd = pcs.Field('hrd', 16, default=1)\npro = pcs.Field('pro', 16, default=2048)\nhln = pcs.Field('hln', 8, default=6)\npln = pcs.Field('pln', 8, default=4)\nop = pcs.Field('op', 16)\nsha = pcs.StringField('sha', 48)\nspa = pcs.Field('spa', 32)\ntha = pcs.StringField('tha', 48)\ntpa = pcs.Field('tpa', 32)\npcs.Pack... | <|body_start_0|>
hrd = pcs.Field('hrd', 16, default=1)
pro = pcs.Field('pro', 16, default=2048)
hln = pcs.Field('hln', 8, default=6)
pln = pcs.Field('pln', 8, default=4)
op = pcs.Field('op', 16)
sha = pcs.StringField('sha', 48)
spa = pcs.Field('spa', 32)
t... | arp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class arp:
def __init__(self, bytes=None):
"""initialize an ARP packet"""
<|body_0|>
def __str__(self):
"""return a human readable version of an ARP packet"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hrd = pcs.Field('hrd', 16, default=1)
pro =... | stack_v2_sparse_classes_36k_train_032808 | 4,350 | no_license | [
{
"docstring": "initialize an ARP packet",
"name": "__init__",
"signature": "def __init__(self, bytes=None)"
},
{
"docstring": "return a human readable version of an ARP packet",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005184 | Implement the Python class `arp` described below.
Class description:
Implement the arp class.
Method signatures and docstrings:
- def __init__(self, bytes=None): initialize an ARP packet
- def __str__(self): return a human readable version of an ARP packet | Implement the Python class `arp` described below.
Class description:
Implement the arp class.
Method signatures and docstrings:
- def __init__(self, bytes=None): initialize an ARP packet
- def __str__(self): return a human readable version of an ARP packet
<|skeleton|>
class arp:
def __init__(self, bytes=None):... | a070a39586b582fbeea72abf12bbfd812955ad81 | <|skeleton|>
class arp:
def __init__(self, bytes=None):
"""initialize an ARP packet"""
<|body_0|>
def __str__(self):
"""return a human readable version of an ARP packet"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class arp:
def __init__(self, bytes=None):
"""initialize an ARP packet"""
hrd = pcs.Field('hrd', 16, default=1)
pro = pcs.Field('pro', 16, default=2048)
hln = pcs.Field('hln', 8, default=6)
pln = pcs.Field('pln', 8, default=4)
op = pcs.Field('op', 16)
sha = pc... | the_stack_v2_python_sparse | src/pcs/packets/arp.py | bilouro/tcptest | train | 0 | |
c5e0dad4cc0eed51beef649c18f3b2d6113f20b9 | [
"self.n_kernels = n_kernels\nself.n_strides = n_strides\nself.dropout = dropout\nself.norm_type = normalization\nself.activation_type = activation\nself.init_kernel = tf.random_normal_initializer(0.0, 0.02)",
"activation = Conv2DTranspose(n_filters, kernel_size=self.n_kernels, strides=self.n_strides, padding='sam... | <|body_start_0|>
self.n_kernels = n_kernels
self.n_strides = n_strides
self.dropout = dropout
self.norm_type = normalization
self.activation_type = activation
self.init_kernel = tf.random_normal_initializer(0.0, 0.02)
<|end_body_0|>
<|body_start_1|>
activation = ... | Class for the Up Convolution block for Unet. | UpConvBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpConvBlock:
"""Class for the Up Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): In... | stack_v2_sparse_classes_36k_train_032809 | 11,636 | no_license | [
{
"docstring": "Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Include dropout for intermediate layers. activation (str): Type of activation layer to use. normalization (str): Type of normalization layer to use.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_004675 | Implement the Python class `UpConvBlock` described below.
Class description:
Class for the Up Convolution block for Unet.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, dropout, activation, normalization): Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for ... | Implement the Python class `UpConvBlock` described below.
Class description:
Class for the Up Convolution block for Unet.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, dropout, activation, normalization): Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for ... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class UpConvBlock:
"""Class for the Up Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): In... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpConvBlock:
"""Class for the Up Convolution block for Unet."""
def __init__(self, n_kernels, n_strides, dropout, activation, normalization):
"""Initialize the Up Convolution Block. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. dropout (float): Include dropout... | the_stack_v2_python_sparse | fmlwright/trainer/neural_networks/blocks.py | rgresia-umd/fml-wright | train | 0 |
32c8f6dd8b34ad9ea5fc4649fdeb100c05f76f1a | [
"m, n = (len(word1), len(word2))\ndp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\nfor i in range(m + 1):\n dp[i][0] = i\nfor j in range(n + 1):\n dp[0][j] = j\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n ... | <|body_start_0|>
m, n = (len(word1), len(word2))
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""自底向上"""
<|body_0|>
def minDistance_1(self, word1: str, word2: str) -> int:
"""自顶向下的递归 需要增加备忘录才不会超时"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(word1), len(word2))
... | stack_v2_sparse_classes_36k_train_032810 | 1,700 | no_license | [
{
"docstring": "自底向上",
"name": "minDistance",
"signature": "def minDistance(self, word1: str, word2: str) -> int"
},
{
"docstring": "自顶向下的递归 需要增加备忘录才不会超时",
"name": "minDistance_1",
"signature": "def minDistance_1(self, word1: str, word2: str) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: 自底向上
- def minDistance_1(self, word1: str, word2: str) -> int: 自顶向下的递归 需要增加备忘录才不会超时 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: 自底向上
- def minDistance_1(self, word1: str, word2: str) -> int: 自顶向下的递归 需要增加备忘录才不会超时
<|skeleton|>
class Solution:
def m... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""自底向上"""
<|body_0|>
def minDistance_1(self, word1: str, word2: str) -> int:
"""自顶向下的递归 需要增加备忘录才不会超时"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""自底向上"""
m, n = (len(word1), len(word2))
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for ... | the_stack_v2_python_sparse | algorithm/leetcode/dp/22-编辑距离.py | lxconfig/UbuntuCode_bak | train | 0 | |
a60c63ef49d4a0466f8bafcc5dccb43d59b4618e | [
"ret = []\nn = len(nums)\nnums.sort()\nfor i in range(n):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n if nums[i] > 0:\n break\n L = i + 1\n R = n - 1\n while L < R:\n if nums[i] + nums[L] + nums[R] == 0:\n ret.append([nums[i], nums[L], nums[R]])\n wh... | <|body_start_0|>
ret = []
n = len(nums)
nums.sort()
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] > 0:
break
L = i + 1
R = n - 1
while L < R:
if nums[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)"""
<|body_0|>
def threeSum2(self, nums: List[int]) -> List[List[int]]:
"""使用哈希表完成。类似于两数之和 时间复杂度: O(n^2) 空间复杂度: On(n) Args: nums: Returns:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_032811 | 3,035 | no_license | [
{
"docstring": "排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)",
"name": "threeSum",
"signature": "def threeSum(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "使用哈希表完成。类似于两数之和 时间复杂度: O(n^2) 空间复杂度: On(n) Args: nums: Returns:",
"name": "threeSum2",
"signature": "def threeSum2(self, nums: L... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: 排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)
- def threeSum2(self, nums: List[int]) -> List[List[int]]: 使用哈希表完成。类似于两数之和 时间复杂度: O(n^2) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums: List[int]) -> List[List[int]]: 排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)
- def threeSum2(self, nums: List[int]) -> List[List[int]]: 使用哈希表完成。类似于两数之和 时间复杂度: O(n^2) ... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)"""
<|body_0|>
def threeSum2(self, nums: List[int]) -> List[List[int]]:
"""使用哈希表完成。类似于两数之和 时间复杂度: O(n^2) 空间复杂度: On(n) Args: nums: Returns:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""排序 + 双指针 时间复杂度:O(n^2) 空间复杂度:O(1)"""
ret = []
n = len(nums)
nums.sort()
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] > 0:
... | the_stack_v2_python_sparse | leetcode/015_三数之和.py | tenqaz/crazy_arithmetic | train | 0 | |
3093455e886f371492c9bb274c3b6e0f534eb14b | [
"prefix_sum_count = {}\nprefix_sum_count[0] = 1\nreturn self.helper(root, prefix_sum_count, sum, 0)",
"if not node:\n return 0\nres = 0\ncur_sum += node.val\nres += prefix_sum_count.get(cur_sum - target, 0)\nprefix_sum_count[cur_sum] = prefix_sum_count.get(cur_sum, 0) + 1\nres += self.helper(node.left, prefix_... | <|body_start_0|>
prefix_sum_count = {}
prefix_sum_count[0] = 1
return self.helper(root, prefix_sum_count, sum, 0)
<|end_body_0|>
<|body_start_1|>
if not node:
return 0
res = 0
cur_sum += node.val
res += prefix_sum_count.get(cur_sum - target, 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
<|body_0|>
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int"""
<|bo... | stack_v2_sparse_classes_36k_train_032812 | 1,878 | no_license | [
{
"docstring": "Args: root: TreeNode sum: int Return: int",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": "Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int",
"name": "helper",
"signature": "def helper(self, node... | 2 | stack_v2_sparse_classes_30k_val_000422 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: int
- def helper(self, node, prefix_sum_count, target, cur_sum): Args: node: TreeNode prefix_sum_count: dict{i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: int
- def helper(self, node, prefix_sum_count, target, cur_sum): Args: node: TreeNode prefix_sum_count: dict{i... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
<|body_0|>
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
prefix_sum_count = {}
prefix_sum_count[0] = 1
return self.helper(root, prefix_sum_count, sum, 0)
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNo... | the_stack_v2_python_sparse | code/437. 路径总和 III.py | AiZhanghan/Leetcode | train | 0 | |
4f92cdfd4116ffdcaeecc90d895aec03a98f8cab | [
"self.serial_com = []\nself.is_active = False\nself.port_number = port_number",
"if self.is_active:\n self.serial_com.close()\n self.is_active = False\nelse:\n print('port was not open')",
"if not self.is_active:\n port = 'COM' + str(self.port_number)\n baud = 9600\n self.serial_com = serial.S... | <|body_start_0|>
self.serial_com = []
self.is_active = False
self.port_number = port_number
<|end_body_0|>
<|body_start_1|>
if self.is_active:
self.serial_com.close()
self.is_active = False
else:
print('port was not open')
<|end_body_1|>
<|bo... | Class to communicate with arduino or custrom serial class | Serial_communication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serial_communication:
"""Class to communicate with arduino or custrom serial class"""
def __init__(self, port_number):
"""init"""
<|body_0|>
def close(self):
"""close com port when open"""
<|body_1|>
def open(self):
"""open com port when clos... | stack_v2_sparse_classes_36k_train_032813 | 1,339 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, port_number)"
},
{
"docstring": "close com port when open",
"name": "close",
"signature": "def close(self)"
},
{
"docstring": "open com port when closed",
"name": "open",
"signature": "def open(se... | 4 | stack_v2_sparse_classes_30k_train_010982 | Implement the Python class `Serial_communication` described below.
Class description:
Class to communicate with arduino or custrom serial class
Method signatures and docstrings:
- def __init__(self, port_number): init
- def close(self): close com port when open
- def open(self): open com port when closed
- def send_c... | Implement the Python class `Serial_communication` described below.
Class description:
Class to communicate with arduino or custrom serial class
Method signatures and docstrings:
- def __init__(self, port_number): init
- def close(self): close com port when open
- def open(self): open com port when closed
- def send_c... | 69eae94c8c9d7eee993adb7fbf02ec44febff8e9 | <|skeleton|>
class Serial_communication:
"""Class to communicate with arduino or custrom serial class"""
def __init__(self, port_number):
"""init"""
<|body_0|>
def close(self):
"""close com port when open"""
<|body_1|>
def open(self):
"""open com port when clos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Serial_communication:
"""Class to communicate with arduino or custrom serial class"""
def __init__(self, port_number):
"""init"""
self.serial_com = []
self.is_active = False
self.port_number = port_number
def close(self):
"""close com port when open"""
... | the_stack_v2_python_sparse | src/serial_communication.py | MarkVerbeek91/AR2 | train | 0 |
a4957e869e3ce074b3e14fc167c0652f5637f5dd | [
"def dfs(node):\n nonlocal ans\n if not node:\n ans += 'None,'\n return\n ans += str(node.val) + ','\n dfs(node.left)\n dfs(node.right)\nans = ''\ndfs(root)\nreturn ans",
"def dfs(queue):\n if queue[0] == 'None':\n queue.popleft()\n return None\n node = TreeNode(qu... | <|body_start_0|>
def dfs(node):
nonlocal ans
if not node:
ans += 'None,'
return
ans += str(node.val) + ','
dfs(node.left)
dfs(node.right)
ans = ''
dfs(root)
return ans
<|end_body_0|>
<|body_start... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node):
nonlocal ans
... | stack_v2_sparse_classes_36k_train_032814 | 949 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009492 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string.
- def deserialize(self, data): Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string.
- def deserialize(self, data): Decodes your encoded data to tree.
<|skeleton|>
class Codec:
def serialize(self, root... | 03afae2bf1407b8cf81e5e642f6d62ad4238dfe3 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
def dfs(node):
nonlocal ans
if not node:
ans += 'None,'
return
ans += str(node.val) + ','
dfs(node.left)
dfs(node.right)
... | the_stack_v2_python_sparse | data_structures/trees/04_serialize_deserialize.py | juanjones5/cs-concepts | train | 0 | |
4861b32c63d30304caf70c5a229585cf8a1c9458 | [
"self.dataset = None\nself.supersedes = True\nself.root_batch_id = None\nself.forced_nodes = None\nself.estimated_recipes = 0\nself.prev_batch_diff = None",
"if self.root_batch_id:\n if batch.recipe_type_id != batch.superseded_batch.recipe_type_id:\n raise InvalidDefinition('MISMATCHED_RECIPE_TYPE', 'Ne... | <|body_start_0|>
self.dataset = None
self.supersedes = True
self.root_batch_id = None
self.forced_nodes = None
self.estimated_recipes = 0
self.prev_batch_diff = None
<|end_body_0|>
<|body_start_1|>
if self.root_batch_id:
if batch.recipe_type_id != bat... | Represents a batch definition | BatchDefinition | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchDefinition:
"""Represents a batch definition"""
def __init__(self):
"""Constructor"""
<|body_0|>
def validate(self, batch):
"""Validates the given batch to make sure it is valid with respect to this batch definition. The given batch must have all of its rela... | stack_v2_sparse_classes_36k_train_032815 | 4,231 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Validates the given batch to make sure it is valid with respect to this batch definition. The given batch must have all of its related fields populated, though id and root_batch_id may be None.... | 3 | null | Implement the Python class `BatchDefinition` described below.
Class description:
Represents a batch definition
Method signatures and docstrings:
- def __init__(self): Constructor
- def validate(self, batch): Validates the given batch to make sure it is valid with respect to this batch definition. The given batch must... | Implement the Python class `BatchDefinition` described below.
Class description:
Represents a batch definition
Method signatures and docstrings:
- def __init__(self): Constructor
- def validate(self, batch): Validates the given batch to make sure it is valid with respect to this batch definition. The given batch must... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class BatchDefinition:
"""Represents a batch definition"""
def __init__(self):
"""Constructor"""
<|body_0|>
def validate(self, batch):
"""Validates the given batch to make sure it is valid with respect to this batch definition. The given batch must have all of its rela... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchDefinition:
"""Represents a batch definition"""
def __init__(self):
"""Constructor"""
self.dataset = None
self.supersedes = True
self.root_batch_id = None
self.forced_nodes = None
self.estimated_recipes = 0
self.prev_batch_diff = None
def ... | the_stack_v2_python_sparse | scale/batch/definition/definition.py | kfconsultant/scale | train | 0 |
bee63bbef15f47b410ece4b67a8a6687ebc4d282 | [
"domain_file = get_data_file('domain_lookup')\nwith open(domain_file, 'r') as df:\n reader = csv.reader(df, delimiter='\\t')\n for row in reader:\n gene_id = row[0].lower()\n domain_data = {'interpro_id': f'interpro:{row[2]}', 'domain_name': row[3], 'start': int(row[4]), 'end': int(row[5]), 'ref... | <|body_start_0|>
domain_file = get_data_file('domain_lookup')
with open(domain_file, 'r') as df:
reader = csv.reader(df, delimiter='\t')
for row in reader:
gene_id = row[0].lower()
domain_data = {'interpro_id': f'interpro:{row[2]}', 'domain_name': ... | Handler class providing requisite services for functional domain lookup. | DomainService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainService:
"""Handler class providing requisite services for functional domain lookup."""
def load_mapping(self) -> None:
"""Load mapping file. Domain map file should be tab separated with a column for each: * UniProt accession * Normalized gene ID * Normalized gene symbol * Inte... | stack_v2_sparse_classes_36k_train_032816 | 2,056 | permissive | [
{
"docstring": "Load mapping file. Domain map file should be tab separated with a column for each: * UniProt accession * Normalized gene ID * Normalized gene symbol * InterPro ID * InterPro domain name * Start coordinate * Stop coordinate * RefSeq protein accession",
"name": "load_mapping",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_018777 | Implement the Python class `DomainService` described below.
Class description:
Handler class providing requisite services for functional domain lookup.
Method signatures and docstrings:
- def load_mapping(self) -> None: Load mapping file. Domain map file should be tab separated with a column for each: * UniProt acces... | Implement the Python class `DomainService` described below.
Class description:
Handler class providing requisite services for functional domain lookup.
Method signatures and docstrings:
- def load_mapping(self) -> None: Load mapping file. Domain map file should be tab separated with a column for each: * UniProt acces... | 0b941fee146a98ac8811c5c111c27e58c565f511 | <|skeleton|>
class DomainService:
"""Handler class providing requisite services for functional domain lookup."""
def load_mapping(self) -> None:
"""Load mapping file. Domain map file should be tab separated with a column for each: * UniProt accession * Normalized gene ID * Normalized gene symbol * Inte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DomainService:
"""Handler class providing requisite services for functional domain lookup."""
def load_mapping(self) -> None:
"""Load mapping file. Domain map file should be tab separated with a column for each: * UniProt accession * Normalized gene ID * Normalized gene symbol * InterPro ID * Int... | the_stack_v2_python_sparse | server/curfu/domain_services.py | cancervariants/fusion-curation | train | 1 |
225bea0445d99f13ba7205cc78e25c57df4d9056 | [
"args = {'client_label': client_label, 'report_type': graph_series.report_type.SerializeToWireFormat(), 'timestamp': mysql_utils.RDFDatetimeToTimestamp(timestamp), 'graph_series': graph_series.SerializeToBytes()}\nquery = '\\n INSERT INTO client_report_graphs (client_label, report_type, timestamp,\\n ... | <|body_start_0|>
args = {'client_label': client_label, 'report_type': graph_series.report_type.SerializeToWireFormat(), 'timestamp': mysql_utils.RDFDatetimeToTimestamp(timestamp), 'graph_series': graph_series.SerializeToBytes()}
query = '\n INSERT INTO client_report_graphs (client_label, report_typ... | Mixin providing an F1 implementation of client-reports DB logic. | MySQLDBClientReportsMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLDBClientReportsMixin:
"""Mixin providing an F1 implementation of client-reports DB logic."""
def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetime, cursor=None):
"""Writes the provided graphs to the DB wit... | stack_v2_sparse_classes_36k_train_032817 | 3,662 | permissive | [
{
"docstring": "Writes the provided graphs to the DB with the given client label.",
"name": "WriteClientGraphSeries",
"signature": "def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetime, cursor=None)"
},
{
"docstring": "Re... | 3 | null | Implement the Python class `MySQLDBClientReportsMixin` described below.
Class description:
Mixin providing an F1 implementation of client-reports DB logic.
Method signatures and docstrings:
- def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetim... | Implement the Python class `MySQLDBClientReportsMixin` described below.
Class description:
Mixin providing an F1 implementation of client-reports DB logic.
Method signatures and docstrings:
- def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetim... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class MySQLDBClientReportsMixin:
"""Mixin providing an F1 implementation of client-reports DB logic."""
def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetime, cursor=None):
"""Writes the provided graphs to the DB wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySQLDBClientReportsMixin:
"""Mixin providing an F1 implementation of client-reports DB logic."""
def WriteClientGraphSeries(self, graph_series: rdf_stats.ClientGraphSeries, client_label: Text, timestamp: rdfvalue.RDFDatetime, cursor=None):
"""Writes the provided graphs to the DB with the given c... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/mysql_client_reports.py | google/grr | train | 4,683 |
00f91c62fd9a5410eb6cb531a9f5c199871001f4 | [
"super(Stance, self).__init__()\nself.src_encoder = encoder\nif tgt_encoder is None:\n self.tgt_encoder = encoder\nelse:\n self.tgt_encoder = tgt_encoder\nself.CNN = CNN(cnn_increasing, cnn_num_layers, cnn_filter_counts)\nself.loss = BCEWithLogitsLoss()",
"pos_score = self.score_pair(query, pos, query_mask,... | <|body_start_0|>
super(Stance, self).__init__()
self.src_encoder = encoder
if tgt_encoder is None:
self.tgt_encoder = encoder
else:
self.tgt_encoder = tgt_encoder
self.CNN = CNN(cnn_increasing, cnn_num_layers, cnn_filter_counts)
self.loss = BCEWith... | "STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. Finally, CNN detects features in al... | Stance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stance:
""""STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. F... | stack_v2_sparse_classes_36k_train_032818 | 8,806 | permissive | [
{
"docstring": "param config: config object param vocab: vocab object param max_len_token: max number of tokens",
"name": "__init__",
"signature": "def __init__(self, encoder, cnn_increasing, cnn_num_layers, cnn_filter_counts, tgt_encoder=None)"
},
{
"docstring": "Compute loss for batch of query... | 3 | stack_v2_sparse_classes_30k_train_005138 | Implement the Python class `Stance` described below.
Class description:
"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over th... | Implement the Python class `Stance` described below.
Class description:
"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over th... | 5dca6fa477c6fdb93b042deb1b0212bb91ce7f00 | <|skeleton|>
class Stance:
""""STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. F... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stance:
""""STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. Finally, CNN d... | the_stack_v2_python_sparse | stance.py | jlibovicky/neural-string-edit-distance | train | 2 |
84e3038c52e222951e6e456e233c0bb33aeffecb | [
"self._run = builder_run\nself._prebuilt_type = self._run.config.build_type\nself._chrome_rev = self._run.options.chrome_rev or self._run.config.chrome_rev\nself._build_root = os.path.abspath(self._run.buildroot)",
"generated_args = []\nif self._run.options.debug:\n generated_args.extend(['--debug', '--dry-run... | <|body_start_0|>
self._run = builder_run
self._prebuilt_type = self._run.config.build_type
self._chrome_rev = self._run.options.chrome_rev or self._run.config.chrome_rev
self._build_root = os.path.abspath(self._run.buildroot)
<|end_body_0|>
<|body_start_1|>
generated_args = []
... | Writes *BINHOST.conf commits on master, on behalf of slaves. | BinhostConfWriter | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinhostConfWriter:
"""Writes *BINHOST.conf commits on master, on behalf of slaves."""
def __init__(self, builder_run):
"""BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build."""
<|body_0|>
def _GenerateCommonArgs(self):
... | stack_v2_sparse_classes_36k_train_032819 | 13,213 | permissive | [
{
"docstring": "BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build.",
"name": "__init__",
"signature": "def __init__(self, builder_run)"
},
{
"docstring": "Generate common prebuilt arguments.",
"name": "_GenerateCommonArgs",
"signature": ... | 4 | null | Implement the Python class `BinhostConfWriter` described below.
Class description:
Writes *BINHOST.conf commits on master, on behalf of slaves.
Method signatures and docstrings:
- def __init__(self, builder_run): BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build.
- d... | Implement the Python class `BinhostConfWriter` described below.
Class description:
Writes *BINHOST.conf commits on master, on behalf of slaves.
Method signatures and docstrings:
- def __init__(self, builder_run): BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build.
- d... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class BinhostConfWriter:
"""Writes *BINHOST.conf commits on master, on behalf of slaves."""
def __init__(self, builder_run):
"""BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build."""
<|body_0|>
def _GenerateCommonArgs(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinhostConfWriter:
"""Writes *BINHOST.conf commits on master, on behalf of slaves."""
def __init__(self, builder_run):
"""BinhostConfWriter constructor. Args: builder_run: BuilderRun instance of the currently running build."""
self._run = builder_run
self._prebuilt_type = self._ru... | the_stack_v2_python_sparse | third_party/chromite/cbuildbot/prebuilts.py | metux/chromium-suckless | train | 5 |
51aaef20c51f6aa83658104741be77a01aed9532 | [
"self.anchor = anchor\nself.sentence = sentence\nself.label_string = label_string\nself.label = pair_labels[label_string]\nself.word_text = word_text\nself.constraint_text = constraint_text\nself._allocate_arrays(params.get_int('max_sent_length'), params.get_int('cnn.neighbor_dist'), params.get_int('embedding.none_... | <|body_start_0|>
self.anchor = anchor
self.sentence = sentence
self.label_string = label_string
self.label = pair_labels[label_string]
self.word_text = word_text
self.constraint_text = constraint_text
self._allocate_arrays(params.get_int('max_sent_length'), params... | WordPairExample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordPairExample:
def __init__(self, anchor, sentence, params, label_string, word_text, constraint_text):
"""We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span.Sentence :t... | stack_v2_sparse_classes_36k_train_032820 | 23,847 | permissive | [
{
"docstring": "We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span.Sentence :type params: nlplingo.common.parameters.Parameters :type label_string: str # 'SAME' or 'DIFFERENT'",
"name": "__i... | 2 | null | Implement the Python class `WordPairExample` described below.
Class description:
Implement the WordPairExample class.
Method signatures and docstrings:
- def __init__(self, anchor, sentence, params, label_string, word_text, constraint_text): We are given a token, sentence as context, and event_type (present during tr... | Implement the Python class `WordPairExample` described below.
Class description:
Implement the WordPairExample class.
Method signatures and docstrings:
- def __init__(self, anchor, sentence, params, label_string, word_text, constraint_text): We are given a token, sentence as context, and event_type (present during tr... | 32ff17b1320937faa3d3ebe727032f4b3e7a353d | <|skeleton|>
class WordPairExample:
def __init__(self, anchor, sentence, params, label_string, word_text, constraint_text):
"""We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span.Sentence :t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordPairExample:
def __init__(self, anchor, sentence, params, label_string, word_text, constraint_text):
"""We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span.Sentence :type params: nl... | the_stack_v2_python_sparse | nlplingo/sandbox/misc/wordpair.use_embedding_layer.py | BBN-E/nlplingo | train | 3 | |
9b8a76fa2994e40efcaa25c23252bc031671143f | [
"if not os.path.exists(f):\n raise OSError('File does not exist')\nwith lock(f, 'r') as fp:\n self.fields = dict(self.fields.items() + from_json(fp.read()).items())\nreturn True",
"if not type(self.fields) is dict:\n raise TypeError('self.fields must be a dict')\nwith lock(f, 'w') as fp:\n fp.write(to... | <|body_start_0|>
if not os.path.exists(f):
raise OSError('File does not exist')
with lock(f, 'r') as fp:
self.fields = dict(self.fields.items() + from_json(fp.read()).items())
return True
<|end_body_0|>
<|body_start_1|>
if not type(self.fields) is dict:
... | JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file. | JSONFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONFile:
"""JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file."""
def from_file(self, f):
"""Read self.fields from file."""
<|body_0|>
def to_file(self, f):
"""Save self.fields to file."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_032821 | 9,795 | no_license | [
{
"docstring": "Read self.fields from file.",
"name": "from_file",
"signature": "def from_file(self, f)"
},
{
"docstring": "Save self.fields to file.",
"name": "to_file",
"signature": "def to_file(self, f)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021305 | Implement the Python class `JSONFile` described below.
Class description:
JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file.
Method signatures and docstrings:
- def from_file(self, f): Read self.fields from file.
- def to_file(self, f): Save self.fields to file. | Implement the Python class `JSONFile` described below.
Class description:
JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file.
Method signatures and docstrings:
- def from_file(self, f): Read self.fields from file.
- def to_file(self, f): Save self.fields to file.
<|skeleto... | 17ff4118b4a49bf4a61c5b763f2f91fbc18d34cd | <|skeleton|>
class JSONFile:
"""JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file."""
def from_file(self, f):
"""Read self.fields from file."""
<|body_0|>
def to_file(self, f):
"""Save self.fields to file."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSONFile:
"""JSONFile subclasses the BaseFile class to provide methods for reading and writing JSON to file."""
def from_file(self, f):
"""Read self.fields from file."""
if not os.path.exists(f):
raise OSError('File does not exist')
with lock(f, 'r') as fp:
... | the_stack_v2_python_sparse | hopper/files.py | ndreynolds/hopper | train | 3 |
bc450b5f45ef84b2239f94ca17e7c7f369f9514b | [
"if len(center_fractions) != len(accelerations):\n raise ValueError('Number of center fractions should match number of accelerations')\nself.center_fractions = center_fractions\nself.accelerations = accelerations\nself.rng = np.random.RandomState()",
"if len(shape) < 3:\n raise ValueError('Shape should have... | <|body_start_0|>
if len(center_fractions) != len(accelerations):
raise ValueError('Number of center fractions should match number of accelerations')
self.center_fractions = center_fractions
self.accelerations = accelerations
self.rng = np.random.RandomState()
<|end_body_0|>
... | MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center corresponding to low-frequencies 2. The other columns are selected uniformly at ran... | MaskFunc | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskFunc:
"""MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center corresponding to low-frequencies 2. The other c... | stack_v2_sparse_classes_36k_train_032822 | 3,589 | permissive | [
{
"docstring": "Args: center_fractions (List[float]): Fraction of low-frequency columns to be retained. If multiple values are provided, then one of these numbers is chosen uniformly each time. accelerations (List[int]): Amount of under-sampling. This should have the same length as center_fractions. If multiple... | 2 | stack_v2_sparse_classes_30k_test_000378 | Implement the Python class `MaskFunc` described below.
Class description:
MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center correspo... | Implement the Python class `MaskFunc` described below.
Class description:
MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center correspo... | 210025d9cb8f92583f5f983be15af06b57cfea36 | <|skeleton|>
class MaskFunc:
"""MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center corresponding to low-frequencies 2. The other c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskFunc:
"""MaskFunc creates a sub-sampling mask of a given shape. The mask selects a subset of columns from the input k-space data. If the k-space data has N columns, the mask picks out: 1. N_low_freqs = (N * center_fraction) columns in the center corresponding to low-frequencies 2. The other columns are se... | the_stack_v2_python_sparse | subtle_data_crimes/crime_1_zero_padding/Fig5_statistics_knee_data/DL/utils/subsample_fastmri.py | mikgroup/data_crimes | train | 3 |
fb03b8f9596d80fc944313d6d5bd695032b4dfa2 | [
"self.file_type = file_type\nself.full_path = full_path\nself.size_bytes = size_bytes",
"if dictionary is None:\n return None\nfile_type = dictionary.get('fileType')\nfull_path = dictionary.get('fullPath')\nsize_bytes = dictionary.get('sizeBytes')\nreturn cls(file_type, full_path, size_bytes)"
] | <|body_start_0|>
self.file_type = file_type
self.full_path = full_path
self.size_bytes = size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
file_type = dictionary.get('fileType')
full_path = dictionary.get('fullPath')
size_b... | Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' refers to a data file 'kLog' refers to a ... | DbFileInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' ref... | stack_v2_sparse_classes_36k_train_032823 | 2,285 | permissive | [
{
"docstring": "Constructor for the DbFileInfo class",
"name": "__init__",
"signature": "def __init__(self, file_type=None, full_path=None, size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the o... | 2 | stack_v2_sparse_classes_30k_train_018652 | Implement the Python class `DbFileInfo` described below.
Class description:
Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQ... | Implement the Python class `DbFileInfo` described below.
Class description:
Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' ref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbFileInfo:
"""Implementation of the 'DbFileInfo' model. Specifies information about a database file. Attributes: file_type (FileTypeEnum): Specifies the format type of the file that SQL database stores the data. Specifies the format type of the file that SQL database stores the data. 'kRows' refers to a data... | the_stack_v2_python_sparse | cohesity_management_sdk/models/db_file_info.py | cohesity/management-sdk-python | train | 24 |
2c94c31d930daf34defb7103a80bf03161d02c61 | [
"def check(s):\n s1 = set(s)\n return set(s) & change\n\ndef DFS(s, i, bound):\n if i == L:\n return 1 if check(s) else 0\n n = 0\n for ch in valid:\n if bound and ch > NS[i]:\n continue\n if bound and ch == NS[i]:\n n += DFS(s + ch, i + 1, True)\n el... | <|body_start_0|>
def check(s):
s1 = set(s)
return set(s) & change
def DFS(s, i, bound):
if i == L:
return 1 if check(s) else 0
n = 0
for ch in valid:
if bound and ch > NS[i]:
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotatedDigits(self, N):
""":type N: int :rtype: int"""
<|body_0|>
def rotatedDigits2(self, N):
""":type N: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def check(s):
s1 = set(s)
return set(s) ... | stack_v2_sparse_classes_36k_train_032824 | 2,385 | no_license | [
{
"docstring": ":type N: int :rtype: int",
"name": "rotatedDigits",
"signature": "def rotatedDigits(self, N)"
},
{
"docstring": ":type N: int :rtype: int",
"name": "rotatedDigits2",
"signature": "def rotatedDigits2(self, N)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011438 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotatedDigits(self, N): :type N: int :rtype: int
- def rotatedDigits2(self, N): :type N: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotatedDigits(self, N): :type N: int :rtype: int
- def rotatedDigits2(self, N): :type N: int :rtype: int
<|skeleton|>
class Solution:
def rotatedDigits(self, N):
... | c4f1cfaff642647f5bd8bd76cd17f2bcc4b28d71 | <|skeleton|>
class Solution:
def rotatedDigits(self, N):
""":type N: int :rtype: int"""
<|body_0|>
def rotatedDigits2(self, N):
""":type N: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotatedDigits(self, N):
""":type N: int :rtype: int"""
def check(s):
s1 = set(s)
return set(s) & change
def DFS(s, i, bound):
if i == L:
return 1 if check(s) else 0
n = 0
for ch in valid:
... | the_stack_v2_python_sparse | LeetCode/788_Rotated_Digits.py | KaiboLiu/Algorithm_Online_Judge | train | 0 | |
16b5322f01b66e0d2562e0823d31192f4534cddb | [
"body = premarshal(result)\nif isinstance(body, xmlrpclib.Fault):\n body = xmlrpclib.dumps(body, methodresponse=True)\nelse:\n try:\n body = xmlrpclib.dumps((body,), methodresponse=True, allow_none=True)\n except:\n self.handleException(sys.exc_info())\n return\nsuper(XMLRPCResponse, s... | <|body_start_0|>
body = premarshal(result)
if isinstance(body, xmlrpclib.Fault):
body = xmlrpclib.dumps(body, methodresponse=True)
else:
try:
body = xmlrpclib.dumps((body,), methodresponse=True, allow_none=True)
except:
self.han... | XMLRPC response. This object is responsible for converting all output to valid XML-RPC. | XMLRPCResponse | [
"ZPL-2.1",
"Python-2.0",
"ICU",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLRPCResponse:
"""XMLRPC response. This object is responsible for converting all output to valid XML-RPC."""
def setResult(self, result):
"""Sets the result of the response Sets the return body equal to the (string) argument "body". Also updates the "content-length" return header. I... | stack_v2_sparse_classes_36k_train_032825 | 7,960 | permissive | [
{
"docstring": "Sets the result of the response Sets the return body equal to the (string) argument \"body\". Also updates the \"content-length\" return header. If the body is a 2-element tuple, then it will be treated as (title,body) If is_error is true then the HTML will be formatted as a Zope error message i... | 2 | stack_v2_sparse_classes_30k_train_013038 | Implement the Python class `XMLRPCResponse` described below.
Class description:
XMLRPC response. This object is responsible for converting all output to valid XML-RPC.
Method signatures and docstrings:
- def setResult(self, result): Sets the result of the response Sets the return body equal to the (string) argument "... | Implement the Python class `XMLRPCResponse` described below.
Class description:
XMLRPC response. This object is responsible for converting all output to valid XML-RPC.
Method signatures and docstrings:
- def setResult(self, result): Sets the result of the response Sets the return body equal to the (string) argument "... | 4c538584703754c956ca66392fdcecf0a0ca2314 | <|skeleton|>
class XMLRPCResponse:
"""XMLRPC response. This object is responsible for converting all output to valid XML-RPC."""
def setResult(self, result):
"""Sets the result of the response Sets the return body equal to the (string) argument "body". Also updates the "content-length" return header. I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XMLRPCResponse:
"""XMLRPC response. This object is responsible for converting all output to valid XML-RPC."""
def setResult(self, result):
"""Sets the result of the response Sets the return body equal to the (string) argument "body". Also updates the "content-length" return header. If the body is... | the_stack_v2_python_sparse | CMS/Zope-3.2.1/Dependencies/zope.publisher-Zope-3.2.1/zope.publisher/xmlrpc.py | germanfriday/code-examples-sandbox | train | 0 |
d16ab2116ed9f91f888cd3e1b21e02cf072575dc | [
"if user is not None:\n return user\nreturn user_or_404(user_id)",
"if user is None:\n user = user_or_404(user_id)\nargs = USER_EDIT_PARSER.parse_args(strict=True)\nargs = clean_attrs(args)\ntry:\n new_password = args.pop('password')\nexcept KeyError:\n pass\nelse:\n change_user_password(user, new_... | <|body_start_0|>
if user is not None:
return user
return user_or_404(user_id)
<|end_body_0|>
<|body_start_1|>
if user is None:
user = user_or_404(user_id)
args = USER_EDIT_PARSER.parse_args(strict=True)
args = clean_attrs(args)
try:
ne... | API resource that handles getting user details, and updating users | UserDetail | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetail:
"""API resource that handles getting user details, and updating users"""
def get(self, user_id=None, user=None):
"""Get a user's details"""
<|body_0|>
def post(self, user_id=None, user=None):
"""Update a user"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_032826 | 7,739 | permissive | [
{
"docstring": "Get a user's details",
"name": "get",
"signature": "def get(self, user_id=None, user=None)"
},
{
"docstring": "Update a user",
"name": "post",
"signature": "def post(self, user_id=None, user=None)"
}
] | 2 | null | Implement the Python class `UserDetail` described below.
Class description:
API resource that handles getting user details, and updating users
Method signatures and docstrings:
- def get(self, user_id=None, user=None): Get a user's details
- def post(self, user_id=None, user=None): Update a user | Implement the Python class `UserDetail` described below.
Class description:
API resource that handles getting user details, and updating users
Method signatures and docstrings:
- def get(self, user_id=None, user=None): Get a user's details
- def post(self, user_id=None, user=None): Update a user
<|skeleton|>
class U... | a4cae55de15a829a3e1b72006f3baa1276e95f30 | <|skeleton|>
class UserDetail:
"""API resource that handles getting user details, and updating users"""
def get(self, user_id=None, user=None):
"""Get a user's details"""
<|body_0|>
def post(self, user_id=None, user=None):
"""Update a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetail:
"""API resource that handles getting user details, and updating users"""
def get(self, user_id=None, user=None):
"""Get a user's details"""
if user is not None:
return user
return user_or_404(user_id)
def post(self, user_id=None, user=None):
""... | the_stack_v2_python_sparse | dockci/api/user.py | sprucedev/DockCI | train | 1 |
8ce06f1f43fae96cdac34c93dcda12e5917e8ad0 | [
"serializer = UserLoginSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nuser, token = serializer.save()\ndata = {'user': UserModelSerializer(user).data, 'access_token': token}\nreturn Response(data, status=status.HTTP_201_CREATED)",
"serializer = UserSignUpSerializer(data=request.data)\ns... | <|body_start_0|>
serializer = UserLoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user, token = serializer.save()
data = {'user': UserModelSerializer(user).data, 'access_token': token}
return Response(data, status=status.HTTP_201_CREATED)
<|end_body_0... | UserViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
def login(self, request):
"""User sign in."""
<|body_0|>
def signup(self, request):
"""User sign up."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
serializer = UserLoginSerializer(data=request.data)
serializer.is_valid(raise_e... | stack_v2_sparse_classes_36k_train_032827 | 1,326 | no_license | [
{
"docstring": "User sign in.",
"name": "login",
"signature": "def login(self, request)"
},
{
"docstring": "User sign up.",
"name": "signup",
"signature": "def signup(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007945 | Implement the Python class `UserViewSet` described below.
Class description:
Implement the UserViewSet class.
Method signatures and docstrings:
- def login(self, request): User sign in.
- def signup(self, request): User sign up. | Implement the Python class `UserViewSet` described below.
Class description:
Implement the UserViewSet class.
Method signatures and docstrings:
- def login(self, request): User sign in.
- def signup(self, request): User sign up.
<|skeleton|>
class UserViewSet:
def login(self, request):
"""User sign in."... | f46be6003e69dc1524d1eae230ba109e3dfeb50f | <|skeleton|>
class UserViewSet:
def login(self, request):
"""User sign in."""
<|body_0|>
def signup(self, request):
"""User sign up."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserViewSet:
def login(self, request):
"""User sign in."""
serializer = UserLoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user, token = serializer.save()
data = {'user': UserModelSerializer(user).data, 'access_token': token}
return... | the_stack_v2_python_sparse | mercados_unac/apps/users/views.py | Chaoslecion123/backendMercado | train | 0 | |
3daeceba3b9e45d979841aafc7bd6d9c3076f0e1 | [
"last_date = datetime.datetime.utcnow().date() - datetime.timedelta(days=settings.OSWL_COLLECT_PERIOD)\ninstance = db().query(models.OpenStackWorkloadStats).filter_by(is_sent=False).filter(models.OpenStackWorkloadStats.created_date <= last_date)\nreturn instance",
"last_date = datetime.datetime.utcnow().date() - ... | <|body_start_0|>
last_date = datetime.datetime.utcnow().date() - datetime.timedelta(days=settings.OSWL_COLLECT_PERIOD)
instance = db().query(models.OpenStackWorkloadStats).filter_by(is_sent=False).filter(models.OpenStackWorkloadStats.created_date <= last_date)
return instance
<|end_body_0|>
<|b... | OpenStackWorkloadStatsCollection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenStackWorkloadStatsCollection:
def get_ready_to_send(cls):
"""Get entries which are ready to send but were not sent yet."""
<|body_0|>
def clean_expired_entries(cls):
"""Delete expired oswl entries from db"""
<|body_1|>
def get_last_by_resource_type(c... | stack_v2_sparse_classes_36k_train_032828 | 3,314 | permissive | [
{
"docstring": "Get entries which are ready to send but were not sent yet.",
"name": "get_ready_to_send",
"signature": "def get_ready_to_send(cls)"
},
{
"docstring": "Delete expired oswl entries from db",
"name": "clean_expired_entries",
"signature": "def clean_expired_entries(cls)"
},... | 3 | null | Implement the Python class `OpenStackWorkloadStatsCollection` described below.
Class description:
Implement the OpenStackWorkloadStatsCollection class.
Method signatures and docstrings:
- def get_ready_to_send(cls): Get entries which are ready to send but were not sent yet.
- def clean_expired_entries(cls): Delete ex... | Implement the Python class `OpenStackWorkloadStatsCollection` described below.
Class description:
Implement the OpenStackWorkloadStatsCollection class.
Method signatures and docstrings:
- def get_ready_to_send(cls): Get entries which are ready to send but were not sent yet.
- def clean_expired_entries(cls): Delete ex... | 0e09dce510927f2cc490b898e5fe3f813bd791be | <|skeleton|>
class OpenStackWorkloadStatsCollection:
def get_ready_to_send(cls):
"""Get entries which are ready to send but were not sent yet."""
<|body_0|>
def clean_expired_entries(cls):
"""Delete expired oswl entries from db"""
<|body_1|>
def get_last_by_resource_type(c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenStackWorkloadStatsCollection:
def get_ready_to_send(cls):
"""Get entries which are ready to send but were not sent yet."""
last_date = datetime.datetime.utcnow().date() - datetime.timedelta(days=settings.OSWL_COLLECT_PERIOD)
instance = db().query(models.OpenStackWorkloadStats).filt... | the_stack_v2_python_sparse | nailgun/nailgun/objects/oswl.py | mba811/fuel-web | train | 1 | |
4d2c13ce9edfbd58290537f5ad1350f09b773d4a | [
"self.tokenizer = tokenizer\nself.classifier = classifier\nself.seq_repo_access = seqrepo_access\nself.transcript_mappings = transcript_mappings\nself.gene_symbol = gene_symbol\nself.amino_acid_cache = amino_acid_cache\nself.uta = uta\nself.mane_transcript_mappings = mane_transcript_mappings\nself.mane_transcript =... | <|body_start_0|>
self.tokenizer = tokenizer
self.classifier = classifier
self.seq_repo_access = seqrepo_access
self.transcript_mappings = transcript_mappings
self.gene_symbol = gene_symbol
self.amino_acid_cache = amino_acid_cache
self.uta = uta
self.mane_t... | The class for translating variation strings to VRS representations. | ToVRS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToVRS:
"""The class for translating variation strings to VRS representations."""
def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symbol: GeneSymbol, amino_acid_cache: AminoAcidCache, uta: UTA, mane_tra... | stack_v2_sparse_classes_36k_train_032829 | 3,426 | permissive | [
{
"docstring": "Initialize the ToVRS class.",
"name": "__init__",
"signature": "def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symbol: GeneSymbol, amino_acid_cache: AminoAcidCache, uta: UTA, mane_transcript_mappi... | 3 | stack_v2_sparse_classes_30k_train_001299 | Implement the Python class `ToVRS` described below.
Class description:
The class for translating variation strings to VRS representations.
Method signatures and docstrings:
- def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symb... | Implement the Python class `ToVRS` described below.
Class description:
The class for translating variation strings to VRS representations.
Method signatures and docstrings:
- def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symb... | d41e9ee786b14f47d17ea8e458eed08ec00ba339 | <|skeleton|>
class ToVRS:
"""The class for translating variation strings to VRS representations."""
def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symbol: GeneSymbol, amino_acid_cache: AminoAcidCache, uta: UTA, mane_tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToVRS:
"""The class for translating variation strings to VRS representations."""
def __init__(self, tokenizer: Tokenize, classifier: Classify, seqrepo_access: SeqRepoAccess, transcript_mappings: TranscriptMappings, gene_symbol: GeneSymbol, amino_acid_cache: AminoAcidCache, uta: UTA, mane_transcript_mappi... | the_stack_v2_python_sparse | variation/to_vrs.py | richardhj/vicc-variation-normalization | train | 0 |
f84b655e11c4d76f1bce91b27536b5baaf3d4c37 | [
"obj = hashlib.md5(user.encode('utf-8'))\nobj.update(pwd.encode('utf-8'))\nreturn obj.hexdigest()",
"code = ''\nfor i in range(n):\n big_letter = chr(random.randint(65, 90))\n letter = chr(random.randint(97, 122))\n number = str(random.randint(0, 9))\n code += random.choice([big_letter, letter, number... | <|body_start_0|>
obj = hashlib.md5(user.encode('utf-8'))
obj.update(pwd.encode('utf-8'))
return obj.hexdigest()
<|end_body_0|>
<|body_start_1|>
code = ''
for i in range(n):
big_letter = chr(random.randint(65, 90))
letter = chr(random.randint(97, 122))
... | Public | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Public:
def md5(user, pwd):
"""md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码"""
<|body_0|>
def code(n):
"""随机验证码 :param n: 验证码长度 :return: 返回验证码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = hashlib.md5(user.encode('utf-8'))... | stack_v2_sparse_classes_36k_train_032830 | 829 | no_license | [
{
"docstring": "md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码",
"name": "md5",
"signature": "def md5(user, pwd)"
},
{
"docstring": "随机验证码 :param n: 验证码长度 :return: 返回验证码",
"name": "code",
"signature": "def code(n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000864 | Implement the Python class `Public` described below.
Class description:
Implement the Public class.
Method signatures and docstrings:
- def md5(user, pwd): md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码
- def code(n): 随机验证码 :param n: 验证码长度 :return: 返回验证码 | Implement the Python class `Public` described below.
Class description:
Implement the Public class.
Method signatures and docstrings:
- def md5(user, pwd): md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码
- def code(n): 随机验证码 :param n: 验证码长度 :return: 返回验证码
<|skeleton|>
class Public:
def md5(user,... | d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7 | <|skeleton|>
class Public:
def md5(user, pwd):
"""md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码"""
<|body_0|>
def code(n):
"""随机验证码 :param n: 验证码长度 :return: 返回验证码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Public:
def md5(user, pwd):
"""md5加密(采用动态加盐加密) :param user: 用户名 :param pwd: 密码 :return: 加密后的密码"""
obj = hashlib.md5(user.encode('utf-8'))
obj.update(pwd.encode('utf-8'))
return obj.hexdigest()
def code(n):
"""随机验证码 :param n: 验证码长度 :return: 返回验证码"""
code = '... | the_stack_v2_python_sparse | day18/HostManagement/user/public.py | 214031230/Python21 | train | 0 | |
60302b984384069445ac8e17abe3149213fa76b6 | [
"parser.add_argument('--current', action='store_true', help='Version stored in database')\nparser.add_argument('--target', action='store_true', help='Version stored in settings')\nparser.add_argument('--update', action='store_true', help='Update database version')",
"site = models.SiteSettings.objects.get()\ncurr... | <|body_start_0|>
parser.add_argument('--current', action='store_true', help='Version stored in database')
parser.add_argument('--target', action='store_true', help='Version stored in settings')
parser.add_argument('--update', action='store_true', help='Update database version')
<|end_body_0|>
<... | command-line options | Command | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""command-line options"""
def add_arguments(self, parser):
"""specify which function to run"""
<|body_0|>
def handle(self, *args, **options):
"""execute init"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser.add_argument('--curren... | stack_v2_sparse_classes_36k_train_032831 | 1,408 | no_license | [
{
"docstring": "specify which function to run",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "execute init",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016889 | Implement the Python class `Command` described below.
Class description:
command-line options
Method signatures and docstrings:
- def add_arguments(self, parser): specify which function to run
- def handle(self, *args, **options): execute init | Implement the Python class `Command` described below.
Class description:
command-line options
Method signatures and docstrings:
- def add_arguments(self, parser): specify which function to run
- def handle(self, *args, **options): execute init
<|skeleton|>
class Command:
"""command-line options"""
def add_a... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class Command:
"""command-line options"""
def add_arguments(self, parser):
"""specify which function to run"""
<|body_0|>
def handle(self, *args, **options):
"""execute init"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""command-line options"""
def add_arguments(self, parser):
"""specify which function to run"""
parser.add_argument('--current', action='store_true', help='Version stored in database')
parser.add_argument('--target', action='store_true', help='Version stored in settings')... | the_stack_v2_python_sparse | bookwyrm/management/commands/instance_version.py | bookwyrm-social/bookwyrm | train | 1,398 |
7c0691e37058110fab8a976ded266ab51fb38443 | [
"sc.logger.info(u'创作页面初始状态检查测试开始')\ntime.sleep(2)\nel_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')\nel_home.click()\ntime.sleep(0.5)\nsc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])\nassert el_home is not None",
"sc.logger.info(u'创作页面下拉刷新测试开始')\nstart_x = self.width // 2\... | <|body_start_0|>
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])
assert el_home is not None
<|... | 创作页面的测试类,分步截图 | TestCreationUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_36k_train_032832 | 2,643 | no_license | [
{
"docstring": "测试创作页面初始UI状态",
"name": "test_origin",
"signature": "def test_origin()"
},
{
"docstring": "测试下拉刷新",
"name": "test_refresh",
"signature": "def test_refresh(self)"
},
{
"docstring": "测试上下方向的滑动",
"name": "test_swipe_vertical",
"signature": "def test_swipe_vert... | 4 | stack_v2_sparse_classes_30k_test_000719 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能
<|skeleton|>
class TestCreationU... | b1190e3df62fa85562c14625c06a9794b8ce29a0 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_scree... | the_stack_v2_python_sparse | Android/VivaVideo/test_creations/test_ui.py | hicheng/UItest | train | 0 |
bcdbebfa4d8693a33adb23b2d37d47237b4ba330 | [
"data = first_line(filename)\ndata = json.loads(data)\nreturn total_nums(data)",
"data = first_line(filename)\ndata = json.loads(data)\nreturn total_nums_no_red(data)"
] | <|body_start_0|>
data = first_line(filename)
data = json.loads(data)
return total_nums(data)
<|end_body_0|>
<|body_start_1|>
data = first_line(filename)
data = json.loads(data)
return total_nums_no_red(data)
<|end_body_1|>
| AoC 2015 Day 12 | Day12 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day12:
"""AoC 2015 Day 12"""
def part1(filename: str) -> int:
"""Given a filename, solve 2015 day 12 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2015 day 12 part 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032833 | 1,440 | no_license | [
{
"docstring": "Given a filename, solve 2015 day 12 part 1",
"name": "part1",
"signature": "def part1(filename: str) -> int"
},
{
"docstring": "Given a filename, solve 2015 day 12 part 2",
"name": "part2",
"signature": "def part2(filename: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_000762 | Implement the Python class `Day12` described below.
Class description:
AoC 2015 Day 12
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2015 day 12 part 1
- def part2(filename: str) -> int: Given a filename, solve 2015 day 12 part 2 | Implement the Python class `Day12` described below.
Class description:
AoC 2015 Day 12
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2015 day 12 part 1
- def part2(filename: str) -> int: Given a filename, solve 2015 day 12 part 2
<|skeleton|>
class Day12:
"""AoC 201... | e89db235837d2d05848210a18c9c2a4456085570 | <|skeleton|>
class Day12:
"""AoC 2015 Day 12"""
def part1(filename: str) -> int:
"""Given a filename, solve 2015 day 12 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2015 day 12 part 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Day12:
"""AoC 2015 Day 12"""
def part1(filename: str) -> int:
"""Given a filename, solve 2015 day 12 part 1"""
data = first_line(filename)
data = json.loads(data)
return total_nums(data)
def part2(filename: str) -> int:
"""Given a filename, solve 2015 day 12 p... | the_stack_v2_python_sparse | 2015/python2015/aoc/day12.py | mreishus/aoc | train | 16 |
c487812957807152cdb3705ed0a56a3d1169edb6 | [
"project = ProjectPermissionsMixin.get_object(self)\nobject_list = project.jobs.all()\nobject_list = self._get_status({}, object_list)\nobject_list = self._get_method({}, object_list)\nobject_list = self._get_users({}, project, object_list)\nreturn object_list.order_by('-id')",
"context = super().get_context_data... | <|body_start_0|>
project = ProjectPermissionsMixin.get_object(self)
object_list = project.jobs.all()
object_list = self._get_status({}, object_list)
object_list = self._get_method({}, object_list)
object_list = self._get_users({}, project, object_list)
return object_list.... | Display job list for a project to the user. | JobListView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobListView:
"""Display job list for a project to the user."""
def get_queryset(self):
"""Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and will raise `PermissionDenied` if not."""
<|body_0|... | stack_v2_sparse_classes_36k_train_032834 | 6,467 | permissive | [
{
"docstring": "Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and will raise `PermissionDenied` if not.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Update context to suppl... | 6 | stack_v2_sparse_classes_30k_train_017024 | Implement the Python class `JobListView` described below.
Class description:
Display job list for a project to the user.
Method signatures and docstrings:
- def get_queryset(self): Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and w... | Implement the Python class `JobListView` described below.
Class description:
Display job list for a project to the user.
Method signatures and docstrings:
- def get_queryset(self): Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and w... | 47c6377ccbfe8576b35854053d726537e533e78c | <|skeleton|>
class JobListView:
"""Display job list for a project to the user."""
def get_queryset(self):
"""Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and will raise `PermissionDenied` if not."""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobListView:
"""Display job list for a project to the user."""
def get_queryset(self):
"""Get all jobs for the project. `ProjectPermissionsMixin.get_object` checks that the request user has the required project permission and will raise `PermissionDenied` if not."""
project = ProjectPermi... | the_stack_v2_python_sparse | director/jobs/ui/views.py | gxf1986/hub | train | 0 |
fd638627f40b8529819621985418841132e7cb64 | [
"ReplayBuffer.__init__(self, capacity, storage_unit)\nself._num_add_calls = 0\nself._num_evicted = 0",
"self._num_timesteps_added += item.count\nself._num_timesteps_added_wrap += item.count\nself._num_add_calls += 1\nif self._num_timesteps_added < self.capacity:\n self._storage.append(item)\n self._est_size... | <|body_start_0|>
ReplayBuffer.__init__(self, capacity, storage_unit)
self._num_add_calls = 0
self._num_evicted = 0
<|end_body_0|>
<|body_start_1|>
self._num_timesteps_added += item.count
self._num_timesteps_added_wrap += item.count
self._num_add_calls += 1
if sel... | This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir". | ReservoirReplayBuffer | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReservoirReplayBuffer:
"""This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir"."""
def __init__(self, capacity: int=10000, storage_unit: str='timesteps', **kwargs):
"""Initializes a ReservoirBuffer inst... | stack_v2_sparse_classes_36k_train_032835 | 4,533 | permissive | [
{
"docstring": "Initializes a ReservoirBuffer instance. Args: capacity: Max number of timesteps to store in the FIFO buffer. After reaching this number, older samples will be dropped to make space for new ones. storage_unit: Either 'timesteps', 'sequences' or 'episodes'. Specifies how experiences are stored.",
... | 5 | stack_v2_sparse_classes_30k_val_000243 | Implement the Python class `ReservoirReplayBuffer` described below.
Class description:
This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir".
Method signatures and docstrings:
- def __init__(self, capacity: int=10000, storage_unit: str='... | Implement the Python class `ReservoirReplayBuffer` described below.
Class description:
This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir".
Method signatures and docstrings:
- def __init__(self, capacity: int=10000, storage_unit: str='... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class ReservoirReplayBuffer:
"""This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir"."""
def __init__(self, capacity: int=10000, storage_unit: str='timesteps', **kwargs):
"""Initializes a ReservoirBuffer inst... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReservoirReplayBuffer:
"""This buffer implements reservoir sampling. The algorithm has been described by Jeffrey S. Vitter in "Random sampling with a reservoir"."""
def __init__(self, capacity: int=10000, storage_unit: str='timesteps', **kwargs):
"""Initializes a ReservoirBuffer instance. Args: c... | the_stack_v2_python_sparse | rllib/utils/replay_buffers/reservoir_replay_buffer.py | ray-project/ray | train | 29,482 |
43a4b6bf413a136a01c40f1e679bf53c2a7e63f8 | [
"self.auth_type = auth_type\nself.authenticating_database_name = authenticating_database_name\nself.requires_ssl = requires_ssl\nself.secondary_node_tag = secondary_node_tag\nself.seeds = seeds\nself.use_secondary_for_backup = use_secondary_for_backup",
"if dictionary is None:\n return None\nauth_type = dictio... | <|body_start_0|>
self.auth_type = auth_type
self.authenticating_database_name = authenticating_database_name
self.requires_ssl = requires_ssl
self.secondary_node_tag = secondary_node_tag
self.seeds = seeds
self.use_secondary_for_backup = use_secondary_for_backup
<|end_bod... | Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cluster. Specifies the type of an MongoDB source entity. 'SCRAM' 'LDAP' 'NONE' 'KERBEROS'... | MongoDBConnectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoDBConnectParams:
"""Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cluster. Specifies the type of an MongoDB... | stack_v2_sparse_classes_36k_train_032836 | 3,374 | permissive | [
{
"docstring": "Constructor for the MongoDBConnectParams class",
"name": "__init__",
"signature": "def __init__(self, auth_type=None, authenticating_database_name=None, requires_ssl=None, secondary_node_tag=None, seeds=None, use_secondary_for_backup=None)"
},
{
"docstring": "Creates an instance ... | 2 | null | Implement the Python class `MongoDBConnectParams` described below.
Class description:
Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cl... | Implement the Python class `MongoDBConnectParams` described below.
Class description:
Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cl... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MongoDBConnectParams:
"""Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cluster. Specifies the type of an MongoDB... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoDBConnectParams:
"""Implementation of the 'MongoDBConnectParams' model. Specifies an Object containing information about a registered mongodb source. Attributes: auth_type (AuthTypeEnum): Specifies whether authentication is configured on this MongoDB cluster. Specifies the type of an MongoDB source entit... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mongo_db_connect_params.py | cohesity/management-sdk-python | train | 24 |
7578735fd55a91e11cb242efa8da1c8004b618be | [
"super().__init__()\nself.root = root\nfilepath = os.path.join(root, 'mappings.csv')\nif not os.path.exists(filepath):\n raise FileNotFoundError(f'Dataset not found in `root={self.root}`')\ntry:\n import pandas as pd\nexcept ImportError:\n raise ImportError('pandas is not installed and is required to use t... | <|body_start_0|>
super().__init__()
self.root = root
filepath = os.path.join(root, 'mappings.csv')
if not os.path.exists(filepath):
raise FileNotFoundError(f'Dataset not found in `root={self.root}`')
try:
import pandas as pd
except ImportError:
... | Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Species and Ecosystem Health at the University of Georgia, it was originally des... | EDDMapS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EDDMapS:
"""Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Species and Ecosystem Health at the Universit... | stack_v2_sparse_classes_36k_train_032837 | 3,732 | permissive | [
{
"docstring": "Initialize a new Dataset instance. Args: root: root directory where dataset can be found Raises: FileNotFoundError: if no files are found in ``root`` ImportError: if pandas is not installed",
"name": "__init__",
"signature": "def __init__(self, root: str='data') -> None"
},
{
"do... | 2 | null | Implement the Python class `EDDMapS` described below.
Class description:
Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Specie... | Implement the Python class `EDDMapS` described below.
Class description:
Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Specie... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class EDDMapS:
"""Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Species and Ecosystem Health at the Universit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EDDMapS:
"""Dataset for EDDMapS. `EDDMapS <https://www.eddmaps.org/>`__, Early Detection and Distribution Mapping System, is a web-based mapping system for documenting invasive species and pest distribution. Launched in 2005 by the Center for Invasive Species and Ecosystem Health at the University of Georgia,... | the_stack_v2_python_sparse | torchgeo/datasets/eddmaps.py | microsoft/torchgeo | train | 1,724 |
4d2b97b3d5493bf74f2437bd64365f203305a16f | [
"data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)\nthresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)\nself.cube = set_up_probability_cube(data.copy(), thresholds)\nself.cell_method1 = iris.coords.CellMethod('mean', 'realization')\nself.cell_method... | <|body_start_0|>
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array([273.0, 275.0, 277.0], dtype=np.float32)
self.cube = set_up_probability_cube(data.copy(), thresholds)
self.cell_method1 = iris.coords.CellMethod... | Test the _equalise_cell_methods method | Test__equalise_cell_methods | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
<|body_0|>
def test_basic(self):
"""Test returns an iris.cube.CubeList."""
<|body_1|>
def test_different_c... | stack_v2_sparse_classes_36k_train_032838 | 13,177 | permissive | [
{
"docstring": "Use temperature probability cube to test with.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test returns an iris.cube.CubeList.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test returns an iris.cube.CubeLis... | 3 | null | Implement the Python class `Test__equalise_cell_methods` described below.
Class description:
Test the _equalise_cell_methods method
Method signatures and docstrings:
- def setUp(self): Use temperature probability cube to test with.
- def test_basic(self): Test returns an iris.cube.CubeList.
- def test_different_cell_... | Implement the Python class `Test__equalise_cell_methods` described below.
Class description:
Test the _equalise_cell_methods method
Method signatures and docstrings:
- def setUp(self): Use temperature probability cube to test with.
- def test_basic(self): Test returns an iris.cube.CubeList.
- def test_different_cell_... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
<|body_0|>
def test_basic(self):
"""Test returns an iris.cube.CubeList."""
<|body_1|>
def test_different_c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__equalise_cell_methods:
"""Test the _equalise_cell_methods method"""
def setUp(self):
"""Use temperature probability cube to test with."""
data = np.array([0.9 * np.ones((3, 3)), 0.5 * np.ones((3, 3)), 0.1 * np.ones((3, 3))], dtype=np.float32)
thresholds = np.array([273.0, 27... | the_stack_v2_python_sparse | improver_tests/utilities/cube_manipulation/test_MergeCubes.py | metoppv/improver | train | 101 |
4a8ff6fa01acc2efecfffd76f33347534842ba9a | [
"self.partner_id = partner_id\nself.customer_id = customer_id\nself.consumer_id = consumer_id\nself.mtype = mtype\nself.institution_id = institution_id\nself.skip_report = skip_report\nself.from_date = from_date\nself.paystubs = paystubs\nself.redirect_uri = redirect_uri\nself.webhook = webhook\nself.webhook_conten... | <|body_start_0|>
self.partner_id = partner_id
self.customer_id = customer_id
self.consumer_id = consumer_id
self.mtype = mtype
self.institution_id = institution_id
self.skip_report = skip_report
self.from_date = from_date
self.paystubs = paystubs
s... | Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (string): Finicity’s customer ID. Obtained from the Add Customer call. consumer_id (string): Finicity... | GenerateConnectURLRequestLending | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateConnectURLRequestLending:
"""Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (string): Finicity’s customer ID. Obtaine... | stack_v2_sparse_classes_36k_train_032839 | 9,315 | permissive | [
{
"docstring": "Constructor for the GenerateConnectURLRequestLending class",
"name": "__init__",
"signature": "def __init__(self, partner_id=None, customer_id=None, consumer_id=None, mtype=None, institution_id=None, skip_report=False, from_date=None, paystubs=None, redirect_uri=None, webhook=None, webho... | 2 | null | Implement the Python class `GenerateConnectURLRequestLending` described below.
Class description:
Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (s... | Implement the Python class `GenerateConnectURLRequestLending` described below.
Class description:
Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (s... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class GenerateConnectURLRequestLending:
"""Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (string): Finicity’s customer ID. Obtaine... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerateConnectURLRequestLending:
"""Implementation of the 'Generate Connect URL Request (Lending)' model. TODO: type model description here. Attributes: partner_id (string): The partner id you can obtain from your Finicity developer dashboard customer_id (string): Finicity’s customer ID. Obtained from the Ad... | the_stack_v2_python_sparse | finicityapi/models/generate_connect_url_request_lending.py | monarchmoney/finicity-python | train | 0 |
95a00bf540728437bb745b9e5ca5eb3cdfbb087e | [
"super(IdentityMapping, self).__init__()\nself.identity = nn.MaxPool2d(1, stride=stride)\nself.num_zeros = num_filters - channels_in",
"out = func.pad(x, [0, 0, 0, 0, 0, self.num_zeros])\nout = self.identity(out)\nreturn out"
] | <|body_start_0|>
super(IdentityMapping, self).__init__()
self.identity = nn.MaxPool2d(1, stride=stride)
self.num_zeros = num_filters - channels_in
<|end_body_0|>
<|body_start_1|>
out = func.pad(x, [0, 0, 0, 0, 0, self.num_zeros])
out = self.identity(out)
return out
<|end... | Class for identity mappings in ResNet. | IdentityMapping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityMapping:
"""Class for identity mappings in ResNet."""
def __init__(self, num_filters, channels_in, stride):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032840 | 4,467 | permissive | [
{
"docstring": "Class initializer.",
"name": "__init__",
"signature": "def __init__(self, num_filters, channels_in, stride)"
},
{
"docstring": "Forward propagation.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014120 | Implement the Python class `IdentityMapping` described below.
Class description:
Class for identity mappings in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in, stride): Class initializer.
- def forward(self, x): Forward propagation. | Implement the Python class `IdentityMapping` described below.
Class description:
Class for identity mappings in ResNet.
Method signatures and docstrings:
- def __init__(self, num_filters, channels_in, stride): Class initializer.
- def forward(self, x): Forward propagation.
<|skeleton|>
class IdentityMapping:
"""... | fe5d1eb5ab5453be70c4be473fd3da71afe4b06c | <|skeleton|>
class IdentityMapping:
"""Class for identity mappings in ResNet."""
def __init__(self, num_filters, channels_in, stride):
"""Class initializer."""
<|body_0|>
def forward(self, x):
"""Forward propagation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityMapping:
"""Class for identity mappings in ResNet."""
def __init__(self, num_filters, channels_in, stride):
"""Class initializer."""
super(IdentityMapping, self).__init__()
self.identity = nn.MaxPool2d(1, stride=stride)
self.num_zeros = num_filters - channels_in
... | the_stack_v2_python_sparse | src/kegnet/classifier/models/resnet.py | videoturingtest/KegNet | train | 0 |
02774c1261595edc12f3a21ea68dcdbe2bf3c05f | [
"identities = {'identity-uuid': {'uuid': 'identity-uuid'}}\nprocess_change(identities, 'identity-uuid', 'unknown-action', {}, datetime.datetime(2020, 1, 1))\nself.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid'}})",
"identities = {'identity-uuid': {'uuid': 'identity-uuid'}}\nprocess_change(iden... | <|body_start_0|>
identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
process_change(identities, 'identity-uuid', 'unknown-action', {}, datetime.datetime(2020, 1, 1))
self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid'}})
<|end_body_0|>
<|body_start_1|>
identiti... | ProcessChangeTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessChangeTests:
def test_unknown_action(self):
"""We should skip processing changes that are not optout or baby_switch"""
<|body_0|>
def test_optout(self):
"""If there is no optout, one should be added"""
<|body_1|>
def test_optout_overwrite(self):
... | stack_v2_sparse_classes_36k_train_032841 | 17,808 | permissive | [
{
"docstring": "We should skip processing changes that are not optout or baby_switch",
"name": "test_unknown_action",
"signature": "def test_unknown_action(self)"
},
{
"docstring": "If there is no optout, one should be added",
"name": "test_optout",
"signature": "def test_optout(self)"
... | 6 | stack_v2_sparse_classes_30k_train_003934 | Implement the Python class `ProcessChangeTests` described below.
Class description:
Implement the ProcessChangeTests class.
Method signatures and docstrings:
- def test_unknown_action(self): We should skip processing changes that are not optout or baby_switch
- def test_optout(self): If there is no optout, one should... | Implement the Python class `ProcessChangeTests` described below.
Class description:
Implement the ProcessChangeTests class.
Method signatures and docstrings:
- def test_unknown_action(self): We should skip processing changes that are not optout or baby_switch
- def test_optout(self): If there is no optout, one should... | e1ea0beaf079f4f4d5f9562fb9d9a4f0670f459f | <|skeleton|>
class ProcessChangeTests:
def test_unknown_action(self):
"""We should skip processing changes that are not optout or baby_switch"""
<|body_0|>
def test_optout(self):
"""If there is no optout, one should be added"""
<|body_1|>
def test_optout_overwrite(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessChangeTests:
def test_unknown_action(self):
"""We should skip processing changes that are not optout or baby_switch"""
identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
process_change(identities, 'identity-uuid', 'unknown-action', {}, datetime.datetime(2020, 1, 1))
... | the_stack_v2_python_sparse | scripts/migrate_to_rapidpro/test_collect_information.py | praekeltfoundation/ndoh-hub | train | 0 | |
bac7b7b23f10dcdd42adc1e2cd71e32dd23ca1e2 | [
"report = view.report\nform_name = ('%s%s%s' % (slugify(report.name).title(), slugify(view.name).title(), 'ViewAggregationForm')).encode('ascii')\nindicators = [(i.pk, i.name) for i in report.indicators.all()]\nindicators += [(0, 'None of them')]\ntry:\n aggregator = Aggregator.objects.get(view=view)\n initia... | <|body_start_0|>
report = view.report
form_name = ('%s%s%s' % (slugify(report.name).title(), slugify(view.name).title(), 'ViewAggregationForm')).encode('ascii')
indicators = [(i.pk, i.name) for i in report.indicators.all()]
indicators += [(0, 'None of them')]
try:
agg... | Factory to create ViewAggregationForms on the fly. | ViewAggregationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewAggregationForm:
"""Factory to create ViewAggregationForms on the fly."""
def get_form(cls, view):
"""List all indicators in the view and make a choice list with it"""
<|body_0|>
def __new__(cls, *args, **kwargs):
"""Create the proper form according to the vi... | stack_v2_sparse_classes_36k_train_032842 | 5,190 | no_license | [
{
"docstring": "List all indicators in the view and make a choice list with it",
"name": "get_form",
"signature": "def get_form(cls, view)"
},
{
"docstring": "Create the proper form according to the view then instanciate the form with the proper args",
"name": "__new__",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_010704 | Implement the Python class `ViewAggregationForm` described below.
Class description:
Factory to create ViewAggregationForms on the fly.
Method signatures and docstrings:
- def get_form(cls, view): List all indicators in the view and make a choice list with it
- def __new__(cls, *args, **kwargs): Create the proper for... | Implement the Python class `ViewAggregationForm` described below.
Class description:
Factory to create ViewAggregationForms on the fly.
Method signatures and docstrings:
- def get_form(cls, view): List all indicators in the view and make a choice list with it
- def __new__(cls, *args, **kwargs): Create the proper for... | 15a4500ccb039e2d7e19dee2b0c5ce755e29da70 | <|skeleton|>
class ViewAggregationForm:
"""Factory to create ViewAggregationForms on the fly."""
def get_form(cls, view):
"""List all indicators in the view and make a choice list with it"""
<|body_0|>
def __new__(cls, *args, **kwargs):
"""Create the proper form according to the vi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewAggregationForm:
"""Factory to create ViewAggregationForms on the fly."""
def get_form(cls, view):
"""List all indicators in the view and make a choice list with it"""
report = view.report
form_name = ('%s%s%s' % (slugify(report.name).title(), slugify(view.name).title(), 'View... | the_stack_v2_python_sparse | django_mangrove/generic_report_admin/forms/_view_forms.py | joelimome/Mangrove | train | 0 |
78f845f03bfe70fa64158a2e35c122d2760964bf | [
"PostProcessorInterfaceBase.initialize(self)\nself.inputFormat = 'HistorySet'\nself.outputFormat = 'HistorySet'",
"if len(inputDic) > 1:\n self.raiseAnError(IOError, 'testInterfacedPP Interfaced Post-Processor ' + str(self.name) + ' accepts only one dataObject')\nelse:\n return inputDic[0]",
"for child in... | <|body_start_0|>
PostProcessorInterfaceBase.initialize(self)
self.inputFormat = 'HistorySet'
self.outputFormat = 'HistorySet'
<|end_body_0|>
<|body_start_1|>
if len(inputDic) > 1:
self.raiseAnError(IOError, 'testInterfacedPP Interfaced Post-Processor ' + str(self.name) + ' a... | This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML | testInterfacedPP | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to... | stack_v2_sparse_classes_36k_train_032843 | 2,159 | permissive | [
{
"docstring": "Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "This method is transparent: it passes the inputDic directly as output @ In, inputDic, dict, dictionary which contains the dat... | 3 | stack_v2_sparse_classes_30k_train_006486 | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML
Method sig... | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML
Method sig... | fbee9e3def3c1ee576d1af85f3258cc816ceaaaf | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run - readMoreXML"""
def initialize(self):
"""Method to initialize t... | the_stack_v2_python_sparse | framework/PostProcessorFunctions/testInterfacedPP.py | jbae11/raven | train | 0 |
2ac69cee63dcdf4f3a0af040c96d73abd2bdd2f1 | [
"self.show_non_use = kwargs.pop('show_non_use', False)\nself.show_non_edit = kwargs.pop('show_non_edit', False)\nsuper().__init__(caller, *args, session=session, **kwargs)",
"dbprot_query, modprot_list = inp\ndbprot_paged = Paginator(dbprot_query, max(1, int(self.height / 2)))\nn_mod = len(modprot_list)\nself._np... | <|body_start_0|>
self.show_non_use = kwargs.pop('show_non_use', False)
self.show_non_edit = kwargs.pop('show_non_edit', False)
super().__init__(caller, *args, session=session, **kwargs)
<|end_body_0|>
<|body_start_1|>
dbprot_query, modprot_list = inp
dbprot_paged = Paginator(dbp... | Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it. | PrototypeEvMore | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrototypeEvMore:
"""Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it."""
def __init__(self, caller, *args, session=None, **kwargs):
"""Store so... | stack_v2_sparse_classes_36k_train_032844 | 46,537 | permissive | [
{
"docstring": "Store some extra properties on the EvMore class",
"name": "__init__",
"signature": "def __init__(self, caller, *args, session=None, **kwargs)"
},
{
"docstring": "This will be initialized with a tuple (mod_prototype_list, paginated_db_query) and we must handle these separately sin... | 4 | null | Implement the Python class `PrototypeEvMore` described below.
Class description:
Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it.
Method signatures and docstrings:
- def __init... | Implement the Python class `PrototypeEvMore` described below.
Class description:
Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it.
Method signatures and docstrings:
- def __init... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class PrototypeEvMore:
"""Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it."""
def __init__(self, caller, *args, session=None, **kwargs):
"""Store so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrototypeEvMore:
"""Listing 1000+ prototypes can be very slow. So we customize EvMore to display an EvTable per paginated page rather than to try creating an EvTable for the entire dataset and then paginate it."""
def __init__(self, caller, *args, session=None, **kwargs):
"""Store some extra prop... | the_stack_v2_python_sparse | evennia/prototypes/prototypes.py | evennia/evennia | train | 1,781 |
83fe44b7891ba4bc2ba5998ea992489a41418624 | [
"super().__init__()\nself.optimizer = optimizer\nself.problem = problem\nself.x0 = x0\nself.id = id\nself.optimize_options = optimize_options\nself.history_options = history_options",
"logger.debug(f'Executing task {self.id}.')\nself.optimizer.check_x0_support(self.problem.x_guesses)\noptimizer_result = self.opti... | <|body_start_0|>
super().__init__()
self.optimizer = optimizer
self.problem = problem
self.x0 = x0
self.id = id
self.optimize_options = optimize_options
self.history_options = history_options
<|end_body_0|>
<|body_start_1|>
logger.debug(f'Executing task {... | A multistart optimization task, performed in `pypesto.minimize`. | OptimizerTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, history_options: HistoryOptions, optimize_options: 'pypesto.optimize.OptimizeOptions'):
"""Crea... | stack_v2_sparse_classes_36k_train_032845 | 2,000 | permissive | [
{
"docstring": "Create the task object. Parameters ---------- optimizer: The optimizer to use. problem: The problem to solve. x0: The point from which to start. id: The multistart id. options: Options object applying to optimization. history_options: Optimizer history options.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_003126 | Implement the Python class `OptimizerTask` described below.
Class description:
A multistart optimization task, performed in `pypesto.minimize`.
Method signatures and docstrings:
- def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, history_options: HistoryOptions, op... | Implement the Python class `OptimizerTask` described below.
Class description:
A multistart optimization task, performed in `pypesto.minimize`.
Method signatures and docstrings:
- def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, history_options: HistoryOptions, op... | 9a754573a7b77d30d5dc1f67a8dc1be6c29f1640 | <|skeleton|>
class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, history_options: HistoryOptions, optimize_options: 'pypesto.optimize.OptimizeOptions'):
"""Crea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, history_options: HistoryOptions, optimize_options: 'pypesto.optimize.OptimizeOptions'):
"""Create the task o... | the_stack_v2_python_sparse | pypesto/optimize/task.py | ICB-DCM/pyPESTO | train | 174 |
c6013f131a6b3e35cb594c75e7cd391dcc7d983f | [
"user = get_object_or_404(User, username=username)\ncanvases = Canvas.objects.filter(user=user).order_by('-pk').values_list('slug', 'canvas')\nreturn JsonResponse(dict(canvases), safe=False)",
"user = self.get_user(request, username)\ndata = request.POST.get('imgBase64', '')\nslug = request.POST.get('slug', '')\n... | <|body_start_0|>
user = get_object_or_404(User, username=username)
canvases = Canvas.objects.filter(user=user).order_by('-pk').values_list('slug', 'canvas')
return JsonResponse(dict(canvases), safe=False)
<|end_body_0|>
<|body_start_1|>
user = self.get_user(request, username)
da... | CanvasesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasesView:
def get(self, _, username=None):
"""Get list of user canvases."""
<|body_0|>
def post(self, request, username=None):
"""Save or create canvas."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = get_object_or_404(User, username=user... | stack_v2_sparse_classes_36k_train_032846 | 30,576 | permissive | [
{
"docstring": "Get list of user canvases.",
"name": "get",
"signature": "def get(self, _, username=None)"
},
{
"docstring": "Save or create canvas.",
"name": "post",
"signature": "def post(self, request, username=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016447 | Implement the Python class `CanvasesView` described below.
Class description:
Implement the CanvasesView class.
Method signatures and docstrings:
- def get(self, _, username=None): Get list of user canvases.
- def post(self, request, username=None): Save or create canvas. | Implement the Python class `CanvasesView` described below.
Class description:
Implement the CanvasesView class.
Method signatures and docstrings:
- def get(self, _, username=None): Get list of user canvases.
- def post(self, request, username=None): Save or create canvas.
<|skeleton|>
class CanvasesView:
def ge... | 51a2ae2b29ae5c91a3cf7171f89edf225cc8a6f0 | <|skeleton|>
class CanvasesView:
def get(self, _, username=None):
"""Get list of user canvases."""
<|body_0|>
def post(self, request, username=None):
"""Save or create canvas."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanvasesView:
def get(self, _, username=None):
"""Get list of user canvases."""
user = get_object_or_404(User, username=username)
canvases = Canvas.objects.filter(user=user).order_by('-pk').values_list('slug', 'canvas')
return JsonResponse(dict(canvases), safe=False)
def p... | the_stack_v2_python_sparse | tool/views/views.py | mikekeda/tools | train | 0 | |
3c206aee7d51eef5fc21349e7c28dde8e3cd5231 | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.reduction = reduction\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob, attention=False, attention_type=attention_type... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.reduction = reduction
self.down_sample_layers = nn.ModuleList([ConvBlock(in_ch... | PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015. | UnetModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S... | stack_v2_sparse_classes_36k_train_032847 | 17,906 | no_license | [
{
"docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ... | 2 | stack_v2_sparse_classes_30k_train_019663 | Implement the Python class `UnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-... | Implement the Python class `UnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015... | the_stack_v2_python_sparse | mrn5/models.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
a639412340c7c976da22e0ae2f1cb875ddf94df8 | [
"r = Round.query.get(round_id)\nif r is not None:\n if r.has_dance(dance_id):\n return r.floor_management_data(dance_id)\n abort(404, 'Round does not have dance with given dance_id')\nabort(404, 'Unknown round_id')",
"r = Round.query.get(round_id)\nif r is not None:\n if r.has_dance(dance_id):\n ... | <|body_start_0|>
r = Round.query.get(round_id)
if r is not None:
if r.has_dance(dance_id):
return r.floor_management_data(dance_id)
abort(404, 'Round does not have dance with given dance_id')
abort(404, 'Unknown round_id')
<|end_body_0|>
<|body_start_1|>
... | RoundAPIFloorManagementDance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoundAPIFloorManagementDance:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
<|body_0|>
def patch(self, round_id, dance_id):
"""Marks list of couples as present for a specific dance"""
<|body_1|>
def delete(self, ... | stack_v2_sparse_classes_36k_train_032848 | 25,303 | no_license | [
{
"docstring": "Get floor management data for a specific dance",
"name": "get",
"signature": "def get(self, round_id, dance_id)"
},
{
"docstring": "Marks list of couples as present for a specific dance",
"name": "patch",
"signature": "def patch(self, round_id, dance_id)"
},
{
"do... | 3 | null | Implement the Python class `RoundAPIFloorManagementDance` described below.
Class description:
Implement the RoundAPIFloorManagementDance class.
Method signatures and docstrings:
- def get(self, round_id, dance_id): Get floor management data for a specific dance
- def patch(self, round_id, dance_id): Marks list of cou... | Implement the Python class `RoundAPIFloorManagementDance` described below.
Class description:
Implement the RoundAPIFloorManagementDance class.
Method signatures and docstrings:
- def get(self, round_id, dance_id): Get floor management data for a specific dance
- def patch(self, round_id, dance_id): Marks list of cou... | 079b109fd13683a31d1d632faa5ab72cf0e78ddf | <|skeleton|>
class RoundAPIFloorManagementDance:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
<|body_0|>
def patch(self, round_id, dance_id):
"""Marks list of couples as present for a specific dance"""
<|body_1|>
def delete(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoundAPIFloorManagementDance:
def get(self, round_id, dance_id):
"""Get floor management data for a specific dance"""
r = Round.query.get(round_id)
if r is not None:
if r.has_dance(dance_id):
return r.floor_management_data(dance_id)
abort(404, 'R... | the_stack_v2_python_sparse | backend/apis/round/apis.py | AlenAlic/DANCE | train | 0 | |
87092e7e3671dbeaf32b3c821ba9b6ad6cc03e0b | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | [summary] Args: tf ([type]): [description] | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k_train_032849 | 2,420 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | null | Implement the Python class `DecoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `DecoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Dec... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
98e7efbc326906abe8af70dc8d963417e2f794f8 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings. | AdGroupExtensionSettingServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupExtensionSettingServiceServicer:
"""Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings."""
def GetAdGroupExtensionSetting(self, request, context):
"""Returns the requested ad group extension setting in full detail."""
... | stack_v2_sparse_classes_36k_train_032850 | 6,279 | permissive | [
{
"docstring": "Returns the requested ad group extension setting in full detail.",
"name": "GetAdGroupExtensionSetting",
"signature": "def GetAdGroupExtensionSetting(self, request, context)"
},
{
"docstring": "Creates, updates, or removes ad group extension settings. Operation statuses are retur... | 2 | stack_v2_sparse_classes_30k_train_008812 | Implement the Python class `AdGroupExtensionSettingServiceServicer` described below.
Class description:
Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings.
Method signatures and docstrings:
- def GetAdGroupExtensionSetting(self, request, context): Returns the requ... | Implement the Python class `AdGroupExtensionSettingServiceServicer` described below.
Class description:
Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings.
Method signatures and docstrings:
- def GetAdGroupExtensionSetting(self, request, context): Returns the requ... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class AdGroupExtensionSettingServiceServicer:
"""Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings."""
def GetAdGroupExtensionSetting(self, request, context):
"""Returns the requested ad group extension setting in full detail."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdGroupExtensionSettingServiceServicer:
"""Proto file describing the AdGroupExtensionSetting service. Service to manage ad group extension settings."""
def GetAdGroupExtensionSetting(self, request, context):
"""Returns the requested ad group extension setting in full detail."""
context.se... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/ad_group_extension_setting_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
63ea6c80b85ec8423b499ca8d82fc1ae417781f6 | [
"self.tolerance = kwargs.pop('tolerance', 1e-12)\n' Convergence criteria for determining inside/outside BZ criteria. '\nsuper(InnerBPoints, self).__init__(*args, **kwargs)",
"from numpy import any, abs, dot, array\nfrom numpy.linalg import inv\nif len(self.lines) == 0:\n return\nif self.relax:\n deformation... | <|body_start_0|>
self.tolerance = kwargs.pop('tolerance', 1e-12)
' Convergence criteria for determining inside/outside BZ criteria. '
super(InnerBPoints, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
from numpy import any, abs, dot, array
from numpy.linalg impo... | Cuts off band-structure directions to fit inside first Brillouin Zone. | InnerBPoints | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InnerBPoints:
"""Cuts off band-structure directions to fit inside first Brillouin Zone."""
def __init__(self, *args, **kwargs):
"""See BPoints for parameters."""
<|body_0|>
def _mnk(self, input, output):
"""Yields lines of k-points with appropriate density."""
... | stack_v2_sparse_classes_36k_train_032851 | 11,484 | no_license | [
{
"docstring": "See BPoints for parameters.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Yields lines of k-points with appropriate density.",
"name": "_mnk",
"signature": "def _mnk(self, input, output)"
},
{
"docstring": "Finds inter... | 4 | null | Implement the Python class `InnerBPoints` described below.
Class description:
Cuts off band-structure directions to fit inside first Brillouin Zone.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): See BPoints for parameters.
- def _mnk(self, input, output): Yields lines of k-points with appro... | Implement the Python class `InnerBPoints` described below.
Class description:
Cuts off band-structure directions to fit inside first Brillouin Zone.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): See BPoints for parameters.
- def _mnk(self, input, output): Yields lines of k-points with appro... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class InnerBPoints:
"""Cuts off band-structure directions to fit inside first Brillouin Zone."""
def __init__(self, *args, **kwargs):
"""See BPoints for parameters."""
<|body_0|>
def _mnk(self, input, output):
"""Yields lines of k-points with appropriate density."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InnerBPoints:
"""Cuts off band-structure directions to fit inside first Brillouin Zone."""
def __init__(self, *args, **kwargs):
"""See BPoints for parameters."""
self.tolerance = kwargs.pop('tolerance', 1e-12)
' Convergence criteria for determining inside/outside BZ criteria. '
... | the_stack_v2_python_sparse | escan/_bandstructure.py | Shibu778/LaDa | train | 0 |
f6c15ee933ac1850139fd66446faddf52a1bbf8e | [
"if not inorder:\n return None\np = None\nroot = TreeNode(preorder[0])\ndel preorder[0]\nstack = [root]\nwhile True:\n if inorder[0] == stack[-1].val:\n p = stack.pop()\n del inorder[0]\n if not inorder:\n break\n if stack and inorder[0] == stack[-1].val:\n co... | <|body_start_0|>
if not inorder:
return None
p = None
root = TreeNode(preorder[0])
del preorder[0]
stack = [root]
while True:
if inorder[0] == stack[-1].val:
p = stack.pop()
del inorder[0]
if not inor... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree_self(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|bod... | stack_v2_sparse_classes_36k_train_032852 | 1,927 | no_license | [
{
"docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree_self",
"signature":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree_self(self, preorder, inorder): :type preorder: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree_self(self, preorder, inorder): :type preorder: List[in... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree_self(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
if not inorder:
return None
p = None
root = TreeNode(preorder[0])
del preorder[0]
stack = [root]
while True:
... | the_stack_v2_python_sparse | 105_construct_binary_tree_from_preorder_and_inorder_traversal/sol.py | lianke123321/leetcode_sol | train | 0 | |
2917d4d981ea280b119b4d23c1d564f9870db7f4 | [
"key = self.request.get('key')\nif not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):\n return\nuser = self.get_user()\nif user is None:\n return\nstudent = models.Student.get_enrolled_student_by_user(user)\nif student is None:\n return\nentity = StudentFormEntity.load_or_... | <|body_start_0|>
key = self.request.get('key')
if not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):
return
user = self.get_user()
if user is None:
return
student = models.Student.get_enrolled_student_by_user(user)
... | The REST Handler provides GET and PUT methods for the form data. | QuestionnaireHandler | [
"Apache-2.0",
"CC-BY-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
<|body_0|>
def post(self):
"""POST method called when the student submits answers.""... | stack_v2_sparse_classes_36k_train_032853 | 11,898 | permissive | [
{
"docstring": "GET method is called when the page with the questionnaire loads.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "POST method called when the student submits answers.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011574 | Implement the Python class `QuestionnaireHandler` described below.
Class description:
The REST Handler provides GET and PUT methods for the form data.
Method signatures and docstrings:
- def get(self): GET method is called when the page with the questionnaire loads.
- def post(self): POST method called when the stude... | Implement the Python class `QuestionnaireHandler` described below.
Class description:
The REST Handler provides GET and PUT methods for the form data.
Method signatures and docstrings:
- def get(self): GET method is called when the page with the questionnaire loads.
- def post(self): POST method called when the stude... | 64f5ea13a8d85b9ef057dddae888a427b1396df6 | <|skeleton|>
class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
<|body_0|>
def post(self):
"""POST method called when the student submits answers.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
key = self.request.get('key')
if not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_T... | the_stack_v2_python_sparse | coursebuilder/modules/questionnaire/questionnaire.py | ram8647/gcb-clone-v111 | train | 1 |
8e419dd4daffbd51e106252a8ad6b1d0425b18a9 | [
"future_question = create_question(question_text='Future question.', days=5)\nresponse = self.client.get(reverse('polls:detail', args=(future_question.id,)))\nself.assertEqual(response.status_code, 404)",
"past_question = create_question(question_text='Past Question.', days=-5)\nresponse = self.client.get(reverse... | <|body_start_0|>
future_question = create_question(question_text='Future question.', days=5)
response = self.client.get(reverse('polls:detail', args=(future_question.id,)))
self.assertEqual(response.status_code, 404)
<|end_body_0|>
<|body_start_1|>
past_question = create_question(questi... | QuestionIndexDetailTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionIndexDetailTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
<|body_0|>
def test_detail_view_with_a_past_question(self):
"""The detail view of a question ... | stack_v2_sparse_classes_36k_train_032854 | 12,478 | no_license | [
{
"docstring": "The detail view of a question with a pub_date in the future should return a 404 not found.",
"name": "test_detail_view_with_a_future_question",
"signature": "def test_detail_view_with_a_future_question(self)"
},
{
"docstring": "The detail view of a question with a pub_date in the... | 2 | stack_v2_sparse_classes_30k_train_000638 | Implement the Python class `QuestionIndexDetailTests` described below.
Class description:
Implement the QuestionIndexDetailTests class.
Method signatures and docstrings:
- def test_detail_view_with_a_future_question(self): The detail view of a question with a pub_date in the future should return a 404 not found.
- de... | Implement the Python class `QuestionIndexDetailTests` described below.
Class description:
Implement the QuestionIndexDetailTests class.
Method signatures and docstrings:
- def test_detail_view_with_a_future_question(self): The detail view of a question with a pub_date in the future should return a 404 not found.
- de... | 43bca49c77eb16de7580e55f7418cdab92a9a596 | <|skeleton|>
class QuestionIndexDetailTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
<|body_0|>
def test_detail_view_with_a_past_question(self):
"""The detail view of a question ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionIndexDetailTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
future_question = create_question(question_text='Future question.', days=5)
response = self.client.get(reverse('... | the_stack_v2_python_sparse | sdd_project copy/labhelpers/tests.py | katrusso/LabHelpers | train | 0 | |
f81b9624f5cf47cb18d888e11d4cccfa83957f42 | [
"result = []\n\ndef dfs(root):\n if not root:\n return\n result.append(root.val)\n for child in root.children:\n dfs(child)\ndfs(root)\nreturn result",
"if not root:\n return []\nstack = []\nstack.append(root)\nresult = []\nwhile stack:\n cur_node = stack.pop()\n result.append(cur_... | <|body_start_0|>
result = []
def dfs(root):
if not root:
return
result.append(root.val)
for child in root.children:
dfs(child)
dfs(root)
return result
<|end_body_0|>
<|body_start_1|>
if not root:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""前序遍历,递归方式 :param root: :return:"""
<|body_0|>
def preorder1(self, root: 'Node') -> List[int]:
"""迭代方式, :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
def dfs(... | stack_v2_sparse_classes_36k_train_032855 | 1,238 | no_license | [
{
"docstring": "前序遍历,递归方式 :param root: :return:",
"name": "preorder",
"signature": "def preorder(self, root: 'Node') -> List[int]"
},
{
"docstring": "迭代方式, :return:",
"name": "preorder1",
"signature": "def preorder1(self, root: 'Node') -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: 'Node') -> List[int]: 前序遍历,递归方式 :param root: :return:
- def preorder1(self, root: 'Node') -> List[int]: 迭代方式, :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: 'Node') -> List[int]: 前序遍历,递归方式 :param root: :return:
- def preorder1(self, root: 'Node') -> List[int]: 迭代方式, :return:
<|skeleton|>
class Solution:
... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""前序遍历,递归方式 :param root: :return:"""
<|body_0|>
def preorder1(self, root: 'Node') -> List[int]:
"""迭代方式, :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""前序遍历,递归方式 :param root: :return:"""
result = []
def dfs(root):
if not root:
return
result.append(root.val)
for child in root.children:
dfs(child)
dfs(... | the_stack_v2_python_sparse | datastructure/n_ary_tree/Preorder.py | yinhuax/leet_code | train | 0 | |
b64d71f4b6e74e3322f4c66f923e10847d27158e | [
"d = set(''.join(wordDict))\nfor c in set(s):\n if c not in d:\n return False\n\ndef help(s, wordDict):\n if not s:\n return True\n for i, w in enumerate(wordDict):\n if s.startswith(w):\n if help(s[len(w):], wordDict):\n return True\n return False\nreturn ... | <|body_start_0|>
d = set(''.join(wordDict))
for c in set(s):
if c not in d:
return False
def help(s, wordDict):
if not s:
return True
for i, w in enumerate(wordDict):
if s.startswith(w):
if h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032856 | 1,399 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak1",
"signature": "def wordBreak1(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009800 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<|... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
d = set(''.join(wordDict))
for c in set(s):
if c not in d:
return False
def help(s, wordDict):
if not s:
return True
... | the_stack_v2_python_sparse | py/leetcode/139.py | wfeng1991/learnpy | train | 0 | |
8560c0068eff894e5aa1d0788bd9e5ad05c14997 | [
"h = u.planck\nc = u.speed_of_light\npi = np.pi\nreturn 8 * pi / (h * c) ** 3 * ((pi * kT) ** 4 / 15)",
"if kT is not None:\n kT = kT\nelif T is not None:\n kT = u.boltzmann * T\nelse:\n raise Exception('kT or k must be passed to BlackBody')\nenergy_density = BlackBody.compute_energy_density(kT)\nsuper(B... | <|body_start_0|>
h = u.planck
c = u.speed_of_light
pi = np.pi
return 8 * pi / (h * c) ** 3 * ((pi * kT) ** 4 / 15)
<|end_body_0|>
<|body_start_1|>
if kT is not None:
kT = kT
elif T is not None:
kT = u.boltzmann * T
else:
raise ... | BlackBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi... | stack_v2_sparse_classes_36k_train_032857 | 4,887 | no_license | [
{
"docstring": "Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi*kT)^4/15.",
"name": "compute_energy_density",
... | 2 | stack_v2_sparse_classes_30k_train_009558 | Implement the Python class `BlackBody` described below.
Class description:
Implement the BlackBody class.
Method signatures and docstrings:
- def compute_energy_density(kT): Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*k... | Implement the Python class `BlackBody` described below.
Class description:
Implement the BlackBody class.
Method signatures and docstrings:
- def compute_energy_density(kT): Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*k... | 21d24c0ae70925201b05f73c8044cc39639f8859 | <|skeleton|>
class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi*kT)^4/15."""
... | the_stack_v2_python_sparse | lande/pysed/sed_thermal.py | zimmerst/PhD-python | train | 0 | |
fce13c1fc668522367ea9f8bbe0eb33620fc9437 | [
"self.webAddress = webAddress\nself.redirectAddress = redirectAddress\nself.clientId = clientId\nself.clientSecret = clientSecret\nif type(scopes) == list:\n self.scopes = ''\n for scope in scopes:\n self.scopes += '{} '.format(scope)\nelif type(scopes) == str:\n self.scopes = scopes\nelse:\n rai... | <|body_start_0|>
self.webAddress = webAddress
self.redirectAddress = redirectAddress
self.clientId = clientId
self.clientSecret = clientSecret
if type(scopes) == list:
self.scopes = ''
for scope in scopes:
self.scopes += '{} '.format(scope)... | Class to negotiate the authentication with the Autodesk Forge Api Authentication servers. | OAuth2Negotiator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuth2Negotiator:
"""Class to negotiate the authentication with the Autodesk Forge Api Authentication servers."""
def __init__(self, webAddress, clientId, clientSecret, scopes, redirectAddress=None, endAddress=None, timeout=1):
"""Initialize the OAuth2Negotiator class and assign the ... | stack_v2_sparse_classes_36k_train_032858 | 3,381 | permissive | [
{
"docstring": "Initialize the OAuth2Negotiator class and assign the needed parameters for authentication. Args: webAddress (str): Web address for the Autodesk Forge API authentication server. clientId (str): Client id for the Forge App this authentication is used for. clientSecret (str): Client secret for the ... | 2 | stack_v2_sparse_classes_30k_train_012849 | Implement the Python class `OAuth2Negotiator` described below.
Class description:
Class to negotiate the authentication with the Autodesk Forge Api Authentication servers.
Method signatures and docstrings:
- def __init__(self, webAddress, clientId, clientSecret, scopes, redirectAddress=None, endAddress=None, timeout=... | Implement the Python class `OAuth2Negotiator` described below.
Class description:
Class to negotiate the authentication with the Autodesk Forge Api Authentication servers.
Method signatures and docstrings:
- def __init__(self, webAddress, clientId, clientSecret, scopes, redirectAddress=None, endAddress=None, timeout=... | 50a95378e2cf37df210269c8576bdae57d232c3b | <|skeleton|>
class OAuth2Negotiator:
"""Class to negotiate the authentication with the Autodesk Forge Api Authentication servers."""
def __init__(self, webAddress, clientId, clientSecret, scopes, redirectAddress=None, endAddress=None, timeout=1):
"""Initialize the OAuth2Negotiator class and assign the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OAuth2Negotiator:
"""Class to negotiate the authentication with the Autodesk Forge Api Authentication servers."""
def __init__(self, webAddress, clientId, clientSecret, scopes, redirectAddress=None, endAddress=None, timeout=1):
"""Initialize the OAuth2Negotiator class and assign the needed parame... | the_stack_v2_python_sparse | PyForge/AuthNegotiator.py | eduardhendriksen/PyForge | train | 2 |
3f1e0dfa4e628761c7e5f02c13a2df77ead14a2e | [
"self.is_vertex_event = isv\nself.time = time\nself.event_vertex = evertex\nself.spoke = spoke\nself.other = other",
"if self.is_vertex_event:\n c = 'V'\nelse:\n c = 'E'\nreturn '%s t=%5f %s %s %s' % (c, self.time, str(self.event_vertex), repr(self.spoke), repr(self.other))"
] | <|body_start_0|>
self.is_vertex_event = isv
self.time = time
self.event_vertex = evertex
self.spoke = spoke
self.other = other
<|end_body_0|>
<|body_start_1|>
if self.is_vertex_event:
c = 'V'
else:
c = 'E'
return '%s t=%5f %s %s %s... | An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: True if this is a vertex event (else it is edge event) time: float - time at whi... | OffsetEvent | [
"Unlicense",
"GPL-3.0-only",
"Font-exception-2.0",
"GPL-3.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer",
"Bitstream-Vera",
"LicenseRef-scancode-blender-2010",
"LGPL-2.1-or-later",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OffsetEvent:
"""An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: True if this is a vertex event (else it i... | stack_v2_sparse_classes_36k_train_032859 | 28,642 | permissive | [
{
"docstring": "Creates and initializes attributes of an OffsetEvent.",
"name": "__init__",
"signature": "def __init__(self, isv, time, evertex, spoke, other)"
},
{
"docstring": "Printing representation of an event.",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | null | Implement the Python class `OffsetEvent` described below.
Class description:
An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: Tr... | Implement the Python class `OffsetEvent` described below.
Class description:
An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: Tr... | f7d23a489c2b4bcc3c1961ac955926484ff8b8d9 | <|skeleton|>
class OffsetEvent:
"""An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: True if this is a vertex event (else it i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OffsetEvent:
"""An event involving a spoke during offset computation. The events kinds are: vertex event: the spoke intersects an adjacent spoke and makes a new vertex edge event: the spoke hits an advancing edge and splits it Attributes: is_vertex_event: True if this is a vertex event (else it is edge event)... | the_stack_v2_python_sparse | engine/2.80/scripts/addons/mesh_inset/offset.py | byteinc/Phasor | train | 3 |
f9a06a9bdc9abbaca4bf160c174011bef5b8dda9 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd = data.shape[0]\nn = data.shape[1]\nself.d = d\nmean = np.mean(data.T, axis=0).reshape(1, d)\nself.mean = me... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
d = data.shape[0]
n = data.shape[1]
self.d = d... | Create the class MultiNormal | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Create the class MultiNormal"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set the public instance variables: mean: numpy.ndarray of shap... | stack_v2_sparse_classes_36k_train_032860 | 1,922 | no_license | [
{
"docstring": "data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set the public instance variables: mean: numpy.ndarray of shape (d, 1) with the mean of data cov: numpy.ndarray of shape (d, d) with the covariance mat... | 2 | null | Implement the Python class `MultiNormal` described below.
Class description:
Create the class MultiNormal
Method signatures and docstrings:
- def __init__(self, data): data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set t... | Implement the Python class `MultiNormal` described below.
Class description:
Create the class MultiNormal
Method signatures and docstrings:
- def __init__(self, data): data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set t... | 4a7a8ff0c4f785656a395d0abf4f182ce1fef5bc | <|skeleton|>
class MultiNormal:
"""Create the class MultiNormal"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set the public instance variables: mean: numpy.ndarray of shap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""Create the class MultiNormal"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point Set the public instance variables: mean: numpy.ndarray of shape (d, 1) with... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | xica369/holbertonschool-machine_learning | train | 0 |
e4a95a51e7a54dff532a80d0e466c0fc95d3cc4f | [
"if occlusion not in cls.__mai_occlusion_level.keys():\n text = 'Invalid occlusion value: %s \\n' % occlusion\n text += '\\t- Available occlusion values:\\n'\n text += '\\n;'.join(['\\t\\t-%s' % occ for occ in cls.__mai_occlusion_level.keys()])\n raise Exception(text)\nreturn cls.__mai_occlusion_level[o... | <|body_start_0|>
if occlusion not in cls.__mai_occlusion_level.keys():
text = 'Invalid occlusion value: %s \n' % occlusion
text += '\t- Available occlusion values:\n'
text += '\n;'.join(['\t\t-%s' % occ for occ in cls.__mai_occlusion_level.keys()])
raise Exception... | :Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values. | OcclusionLevel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OcclusionLevel:
""":Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values."""
def get_occlusion_level_from_mai(cls, occlusion):
""":Description: This is a class method used to retrieve the occlusion level based on MAI occlusion va... | stack_v2_sparse_classes_36k_train_032861 | 3,679 | permissive | [
{
"docstring": ":Description: This is a class method used to retrieve the occlusion level based on MAI occlusion value. :param cls: Default class method parameter, part of the signature. :param occlusion: the occlusion from MAI annotation. :return: the occlusion level as an integer :raise: An exception will be ... | 3 | stack_v2_sparse_classes_30k_train_015453 | Implement the Python class `OcclusionLevel` described below.
Class description:
:Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values.
Method signatures and docstrings:
- def get_occlusion_level_from_mai(cls, occlusion): :Description: This is a class method used ... | Implement the Python class `OcclusionLevel` described below.
Class description:
:Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values.
Method signatures and docstrings:
- def get_occlusion_level_from_mai(cls, occlusion): :Description: This is a class method used ... | 597d9dda472c09bafea58ea69853948d63197eca | <|skeleton|>
class OcclusionLevel:
""":Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values."""
def get_occlusion_level_from_mai(cls, occlusion):
""":Description: This is a class method used to retrieve the occlusion level based on MAI occlusion va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OcclusionLevel:
""":Description: The **OcclusionLevel** class is a container mapping annotated occlusion values to Valeo values."""
def get_occlusion_level_from_mai(cls, occlusion):
""":Description: This is a class method used to retrieve the occlusion level based on MAI occlusion value. :param c... | the_stack_v2_python_sparse | scripts/parsers/detection/occlusion_level.py | valeoai/WoodScape | train | 530 |
dff53f89f1a92c45a8c6ac70f1d2f166a20f41e7 | [
"if not num_feat_per_dim > 1:\n raise pyrado.ValueErr(given=num_feat_per_dim, g_constraint='1')\nif not len(bounds) == 2:\n raise pyrado.ShapeErr(given=bounds, expected_match=np.empty(2))\nbounds_to = [None, None]\nfor i, b in enumerate(bounds):\n if isinstance(b, np.ndarray):\n bounds_to[i] = to.fr... | <|body_start_0|>
if not num_feat_per_dim > 1:
raise pyrado.ValueErr(given=num_feat_per_dim, g_constraint='1')
if not len(bounds) == 2:
raise pyrado.ShapeErr(given=bounds, expected_match=np.empty(2))
bounds_to = [None, None]
for i, b in enumerate(bounds):
... | Normalized Gaussian radial basis function features | RBFFeat | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBFFeat:
"""Normalized Gaussian radial basis function features"""
def __init__(self, num_feat_per_dim: int, bounds: [Sequence[np.ndarray], Sequence[to.Tensor], Sequence[float]], scale: float=None, state_wise_norm: bool=True):
"""Constructor :param num_feat_per_dim: number of radial b... | stack_v2_sparse_classes_36k_train_032862 | 17,010 | permissive | [
{
"docstring": "Constructor :param num_feat_per_dim: number of radial basis functions, identical for every dimension of the input :param bounds: lower and upper bound for the Gaussians' centers, the input dimension is inferred from them :param scale: scaling factor for the squared distance, if `None` the factor... | 3 | null | Implement the Python class `RBFFeat` described below.
Class description:
Normalized Gaussian radial basis function features
Method signatures and docstrings:
- def __init__(self, num_feat_per_dim: int, bounds: [Sequence[np.ndarray], Sequence[to.Tensor], Sequence[float]], scale: float=None, state_wise_norm: bool=True)... | Implement the Python class `RBFFeat` described below.
Class description:
Normalized Gaussian radial basis function features
Method signatures and docstrings:
- def __init__(self, num_feat_per_dim: int, bounds: [Sequence[np.ndarray], Sequence[to.Tensor], Sequence[float]], scale: float=None, state_wise_norm: bool=True)... | 15901f70f0538bce19acdda2a0018984f67cc0fe | <|skeleton|>
class RBFFeat:
"""Normalized Gaussian radial basis function features"""
def __init__(self, num_feat_per_dim: int, bounds: [Sequence[np.ndarray], Sequence[to.Tensor], Sequence[float]], scale: float=None, state_wise_norm: bool=True):
"""Constructor :param num_feat_per_dim: number of radial b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RBFFeat:
"""Normalized Gaussian radial basis function features"""
def __init__(self, num_feat_per_dim: int, bounds: [Sequence[np.ndarray], Sequence[to.Tensor], Sequence[float]], scale: float=None, state_wise_norm: bool=True):
"""Constructor :param num_feat_per_dim: number of radial basis function... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/features.py | arlene-kuehn/SimuRLacra | train | 0 |
72040cb633ae07525be2bebe9921f641e9784d34 | [
"clase = 'actions_fase'\nvalue = '<div>'\nif PoseePermiso('modificar usuario').is_met(request.environ):\n value += '<div>' + '<a href=\"/usuarios/' + str(obj.id_usuario) + '/edit\" ' + 'class=\"' + clase + '\">Modificar</a>' + '</div><br />'\nif PoseePermiso('asignar-desasignar rol').is_met(request.environ):\n ... | <|body_start_0|>
clase = 'actions_fase'
value = '<div>'
if PoseePermiso('modificar usuario').is_met(request.environ):
value += '<div>' + '<a href="/usuarios/' + str(obj.id_usuario) + '/edit" ' + 'class="' + clase + '">Modificar</a>' + '</div><br />'
if PoseePermiso('asignar-d... | UsuarioTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsuarioTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, **kw):
"""Se muestra la lista de usuario si se tiene un permiso necesario. Caso contrario se muestra solo su usuario"""
... | stack_v2_sparse_classes_36k_train_032863 | 15,192 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de usuario si se tiene un permiso necesario. Caso contrario se muestra solo su usuario",
"name": "_do_get_provider_count_and_objs"... | 2 | stack_v2_sparse_classes_30k_train_006545 | Implement the Python class `UsuarioTableFiller` described below.
Class description:
Implement the UsuarioTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, **kw): Se muestra la lista de usuario si se ti... | Implement the Python class `UsuarioTableFiller` described below.
Class description:
Implement the UsuarioTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, **kw): Se muestra la lista de usuario si se ti... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class UsuarioTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, **kw):
"""Se muestra la lista de usuario si se tiene un permiso necesario. Caso contrario se muestra solo su usuario"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsuarioTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
clase = 'actions_fase'
value = '<div>'
if PoseePermiso('modificar usuario').is_met(request.environ):
value += '<div>' + '<a href="/usuarios/' + str(obj.id_usuario) + '/edit... | the_stack_v2_python_sparse | lpm/controllers/usuario.py | jorgeramirez/LPM | train | 1 | |
94602e1fb02942065bb21bcd3ac0801c77000f83 | [
"if not settings.REGISTER_ENABLED:\n raise BadRequest(_('Public register is disabled.'))\nserializer = RegisterSerializer(data=request.data)\nif not serializer.is_valid():\n raise RequestValidationError(serializer.errors)\ndata = serializer.data\nregister(**data)\nreturn Response(data, status=status.HTTP_201_... | <|body_start_0|>
if not settings.REGISTER_ENABLED:
raise BadRequest(_('Public register is disabled.'))
serializer = RegisterSerializer(data=request.data)
if not serializer.is_valid():
raise RequestValidationError(serializer.errors)
data = serializer.data
r... | AuthViewSet | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: em... | stack_v2_sparse_classes_36k_train_032864 | 6,297 | permissive | [
{
"docstring": "Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: email description: user email required: true type: string paramTy... | 6 | stack_v2_sparse_classes_30k_train_014979 | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def register(self, request, **kwargs): Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form ... | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def register(self, request, **kwargs): Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form ... | 665de9832e8a262f9051f4075572f5aed0553f6e | <|skeleton|>
class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthViewSet:
def register(self, request, **kwargs):
"""Register for a new user. --- parameters: - name: first_name description: user first name required: true type: string paramType: form - name: last_name description: user last name required: true type: string paramType: form - name: email descriptio... | the_stack_v2_python_sparse | app/auth/api.py | sololuz/cibb-web | train | 0 | |
17ee8b278261bc72253f124fb039d6b2fba0c4bb | [
"with tf.Graph().as_default():\n with tf.gfile.FastGFile('one_b_data/graph-2016-09-10.pbtxt', 'r') as f:\n s = f.read()\n gd = tf.GraphDef()\n text_format.Merge(s, gd)\n tf.logging.info('Recovering Graph %s', 'one_b_data/graph-2016-09-10.pbtxt')\n self.t = {}\n [self.t['states_init'... | <|body_start_0|>
with tf.Graph().as_default():
with tf.gfile.FastGFile('one_b_data/graph-2016-09-10.pbtxt', 'r') as f:
s = f.read()
gd = tf.GraphDef()
text_format.Merge(s, gd)
tf.logging.info('Recovering Graph %s', 'one_b_data/graph-2016-09... | Wrapping class for google model | google_model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class google_model:
"""Wrapping class for google model"""
def __init__(self):
"""Do whatever set-up it takes"""
<|body_0|>
def tokenize(self, word):
"""returns a list of tokens according to the models desired tokenization scheme"""
<|body_1|>
def empty_sen... | stack_v2_sparse_classes_36k_train_032865 | 5,065 | no_license | [
{
"docstring": "Do whatever set-up it takes",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "returns a list of tokens according to the models desired tokenization scheme",
"name": "tokenize",
"signature": "def tokenize(self, word)"
},
{
"docstring": "Ini... | 5 | stack_v2_sparse_classes_30k_train_008594 | Implement the Python class `google_model` described below.
Class description:
Wrapping class for google model
Method signatures and docstrings:
- def __init__(self): Do whatever set-up it takes
- def tokenize(self, word): returns a list of tokens according to the models desired tokenization scheme
- def empty_sentenc... | Implement the Python class `google_model` described below.
Class description:
Wrapping class for google model
Method signatures and docstrings:
- def __init__(self): Do whatever set-up it takes
- def tokenize(self, word): returns a list of tokens according to the models desired tokenization scheme
- def empty_sentenc... | 101908743bff7084f9ffd13ca6162a2977744716 | <|skeleton|>
class google_model:
"""Wrapping class for google model"""
def __init__(self):
"""Do whatever set-up it takes"""
<|body_0|>
def tokenize(self, word):
"""returns a list of tokens according to the models desired tokenization scheme"""
<|body_1|>
def empty_sen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class google_model:
"""Wrapping class for google model"""
def __init__(self):
"""Do whatever set-up it takes"""
with tf.Graph().as_default():
with tf.gfile.FastGFile('one_b_data/graph-2016-09-10.pbtxt', 'r') as f:
s = f.read()
gd = tf.GraphDef()
... | the_stack_v2_python_sparse | maze_automate/google_model.py | vboyce/Maze | train | 19 |
548595759e64bb458fb856da69c22e483317f509 | [
"if mortgage_profile:\n if mortgage_profile.kind == 'refinance':\n return MortgageProfileRefinance.objects.get(id=mortgage_profile.id)\n elif mortgage_profile.kind == 'purchase':\n return MortgageProfilePurchase.objects.get(id=mortgage_profile.id)",
"salesforce_client = beatbox.PythonClient()\... | <|body_start_0|>
if mortgage_profile:
if mortgage_profile.kind == 'refinance':
return MortgageProfileRefinance.objects.get(id=mortgage_profile.id)
elif mortgage_profile.kind == 'purchase':
return MortgageProfilePurchase.objects.get(id=mortgage_profile.id)
... | Utility methods for Salesforce interaction | SalesforceUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SalesforceUtils:
"""Utility methods for Salesforce interaction"""
def typed_mortgage_profile(mortgage_profile):
"""Get the typed MortgageProfile subclass for an MP id"""
<|body_0|>
def create_salesforce_client():
"""Build a beatbox Salesforce client and log in"""... | stack_v2_sparse_classes_36k_train_032866 | 1,503 | no_license | [
{
"docstring": "Get the typed MortgageProfile subclass for an MP id",
"name": "typed_mortgage_profile",
"signature": "def typed_mortgage_profile(mortgage_profile)"
},
{
"docstring": "Build a beatbox Salesforce client and log in",
"name": "create_salesforce_client",
"signature": "def crea... | 2 | stack_v2_sparse_classes_30k_train_011789 | Implement the Python class `SalesforceUtils` described below.
Class description:
Utility methods for Salesforce interaction
Method signatures and docstrings:
- def typed_mortgage_profile(mortgage_profile): Get the typed MortgageProfile subclass for an MP id
- def create_salesforce_client(): Build a beatbox Salesforce... | Implement the Python class `SalesforceUtils` described below.
Class description:
Utility methods for Salesforce interaction
Method signatures and docstrings:
- def typed_mortgage_profile(mortgage_profile): Get the typed MortgageProfile subclass for an MP id
- def create_salesforce_client(): Build a beatbox Salesforce... | f1a8cd8268d032ea8321e1588e226da09925b7aa | <|skeleton|>
class SalesforceUtils:
"""Utility methods for Salesforce interaction"""
def typed_mortgage_profile(mortgage_profile):
"""Get the typed MortgageProfile subclass for an MP id"""
<|body_0|>
def create_salesforce_client():
"""Build a beatbox Salesforce client and log in"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SalesforceUtils:
"""Utility methods for Salesforce interaction"""
def typed_mortgage_profile(mortgage_profile):
"""Get the typed MortgageProfile subclass for an MP id"""
if mortgage_profile:
if mortgage_profile.kind == 'refinance':
return MortgageProfileRefinan... | the_stack_v2_python_sparse | website/apps/vendors/sf_utils.py | protoprojects/worksample | train | 0 |
e66aa8fbfca505c7c7c6bf7ab459eb326ce76504 | [
"self.app_marker_detection = app_marker_detection\nself.cloud_spill_vault_id = cloud_spill_vault_id\nself.compression_policy = compression_policy\nself.deduplicate_compress_delay_secs = deduplicate_compress_delay_secs\nself.deduplication_enabled = deduplication_enabled\nself.encryption_policy = encryption_policy\ns... | <|body_start_0|>
self.app_marker_detection = app_marker_detection
self.cloud_spill_vault_id = cloud_spill_vault_id
self.compression_policy = compression_policy
self.deduplicate_compress_delay_secs = deduplicate_compress_delay_secs
self.deduplication_enabled = deduplication_enable... | Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app markers (like commvault markers) will be removed from data and put in separate chun... | StoragePolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoragePolicy:
"""Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app markers (like commvault markers) will be r... | stack_v2_sparse_classes_36k_train_032867 | 7,562 | permissive | [
{
"docstring": "Constructor for the StoragePolicy class",
"name": "__init__",
"signature": "def __init__(self, app_marker_detection=None, cloud_spill_vault_id=None, compression_policy=None, deduplicate_compress_delay_secs=None, deduplication_enabled=None, encryption_policy=None, erasure_coding_info=None... | 2 | null | Implement the Python class `StoragePolicy` described below.
Class description:
Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app mar... | Implement the Python class `StoragePolicy` described below.
Class description:
Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app mar... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class StoragePolicy:
"""Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app markers (like commvault markers) will be r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoragePolicy:
"""Implementation of the 'StoragePolicy' model. Specifies the storage options applied to a Storage Domain (View Box). Attributes: app_marker_detection (bool): Specifies Whether to support app marker detection. When this is set to true, app markers (like commvault markers) will be removed from d... | the_stack_v2_python_sparse | cohesity_management_sdk/models/storage_policy.py | cohesity/management-sdk-python | train | 24 |
a7c902c8a499105dab33b1cc70f58badb44835de | [
"p = self.make('Prescription')\nday_state = p.day_state\nself.assertFalse(day_state.pre_actions)\nday_state.pre_actions = True\nwith self.assertRaises(ValidationError) as cm:\n day_state.full_clean()\n self.assertEqual(cm.exception.messages_dict, {'pre_actions': ['Pre-burn actions cannot be marked as complete... | <|body_start_0|>
p = self.make('Prescription')
day_state = p.day_state
self.assertFalse(day_state.pre_actions)
day_state.pre_actions = True
with self.assertRaises(ValidationError) as cm:
day_state.full_clean()
self.assertEqual(cm.exception.messages_dict, {... | BurnImplementationStateTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
<|body_0|>
def test_day_of_burn_actions(self):
"""Test that marking day of burn actions as complete works as expected."""
<|... | stack_v2_sparse_classes_36k_train_032868 | 5,840 | permissive | [
{
"docstring": "Test that marking pre-burn actions as complete works as expected.",
"name": "test_pre_burn_actions",
"signature": "def test_pre_burn_actions(self)"
},
{
"docstring": "Test that marking day of burn actions as complete works as expected.",
"name": "test_day_of_burn_actions",
... | 2 | stack_v2_sparse_classes_30k_train_018325 | Implement the Python class `BurnImplementationStateTests` described below.
Class description:
Implement the BurnImplementationStateTests class.
Method signatures and docstrings:
- def test_pre_burn_actions(self): Test that marking pre-burn actions as complete works as expected.
- def test_day_of_burn_actions(self): T... | Implement the Python class `BurnImplementationStateTests` described below.
Class description:
Implement the BurnImplementationStateTests class.
Method signatures and docstrings:
- def test_pre_burn_actions(self): Test that marking pre-burn actions as complete works as expected.
- def test_day_of_burn_actions(self): T... | 37113bfd3a18824f3cd3368e68672607b7a89cb3 | <|skeleton|>
class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
<|body_0|>
def test_day_of_burn_actions(self):
"""Test that marking day of burn actions as complete works as expected."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BurnImplementationStateTests:
def test_pre_burn_actions(self):
"""Test that marking pre-burn actions as complete works as expected."""
p = self.make('Prescription')
day_state = p.day_state
self.assertFalse(day_state.pre_actions)
day_state.pre_actions = True
with... | the_stack_v2_python_sparse | pbs/report/tests.py | patrickmaslen/pbs | train | 0 | |
979fc2e331c6159cb3d6aff9d5c2200125ce5619 | [
"self._parser = SafeConfigParser()\nif len(self._parser.read(filename)) == 0:\n raise RuntimeError('Failed to find configuration file with name: {0}'.format(filename))",
"widgets = {}\nfor section in self._parser.sections():\n if not self._parser.has_option(section, 'type'):\n continue\n type_name... | <|body_start_0|>
self._parser = SafeConfigParser()
if len(self._parser.read(filename)) == 0:
raise RuntimeError('Failed to find configuration file with name: {0}'.format(filename))
<|end_body_0|>
<|body_start_1|>
widgets = {}
for section in self._parser.sections():
... | Class to load and process dashboard configuration file data. | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Class to load and process dashboard configuration file data."""
def __init__(self, filename):
"""Create an instance of the configuration by loading data from the provided config filename."""
<|body_0|>
def get_widgets(self):
"""Return a dict of widget ... | stack_v2_sparse_classes_36k_train_032869 | 3,552 | permissive | [
{
"docstring": "Create an instance of the configuration by loading data from the provided config filename.",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Return a dict of widget instances defined in the configuration file. The key of the dict is the widget i... | 2 | null | Implement the Python class `Config` described below.
Class description:
Class to load and process dashboard configuration file data.
Method signatures and docstrings:
- def __init__(self, filename): Create an instance of the configuration by loading data from the provided config filename.
- def get_widgets(self): Ret... | Implement the Python class `Config` described below.
Class description:
Class to load and process dashboard configuration file data.
Method signatures and docstrings:
- def __init__(self, filename): Create an instance of the configuration by loading data from the provided config filename.
- def get_widgets(self): Ret... | 0c14c316898d4d06015912ac4a8cb7b71a3980c0 | <|skeleton|>
class Config:
"""Class to load and process dashboard configuration file data."""
def __init__(self, filename):
"""Create an instance of the configuration by loading data from the provided config filename."""
<|body_0|>
def get_widgets(self):
"""Return a dict of widget ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""Class to load and process dashboard configuration file data."""
def __init__(self, filename):
"""Create an instance of the configuration by loading data from the provided config filename."""
self._parser = SafeConfigParser()
if len(self._parser.read(filename)) == 0:
... | the_stack_v2_python_sparse | Pi_Physical_Dashboard/config.py | pranavlathigara/Raspberry-Pi-DIY-Projects | train | 1 |
83041592f69d5feb5005e60b631cf601eb447b87 | [
"PROVIDER_ID = kwargs.get('id')\nprovider = providerModel.ProviderModel.get_by_id(self.db.session, PROVIDER_ID)\nif not provider:\n raise HTTPNotFound(description='Entry not found', code=5)\nresp.status = HTTP_200\nresp.media = {'provider': provider.as_dict}",
"if 'id' in kwargs:\n provider = providerModel.... | <|body_start_0|>
PROVIDER_ID = kwargs.get('id')
provider = providerModel.ProviderModel.get_by_id(self.db.session, PROVIDER_ID)
if not provider:
raise HTTPNotFound(description='Entry not found', code=5)
resp.status = HTTP_200
resp.media = {'provider': provider.as_dict}... | API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI. | ProvidersResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvidersResource:
"""API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get... | stack_v2_sparse_classes_36k_train_032870 | 5,502 | permissive | [
{
"docstring": "Get a provider by its ID --- summary: Fetches a provider by its ID description: Endpoint that retrieves provider by ID parameters: - in: path name: id description: id of provider to get schema: type: integer tags: - providers responses: 200: description: OK 404: description: Not found code: 5",
... | 2 | stack_v2_sparse_classes_30k_test_001031 | Implement the Python class `ProvidersResource` described below.
Class description:
API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI.
Method signatures and... | Implement the Python class `ProvidersResource` described below.
Class description:
API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI.
Method signatures and... | e2c74c36d5eb8492764205fe99558b0818473cb7 | <|skeleton|>
class ProvidersResource:
"""API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProvidersResource:
"""API Resource to interact with Providers BD model. This resource exposes an Option, GET, POST and PATCH methods. This converts providers data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get a provider b... | the_stack_v2_python_sparse | mobility-service-provider---service/msp/resources/providers.py | vicinityh2020/vicinity-vas-dreven | train | 0 |
32c546a97030310d32425154aa05e00b0ee36eae | [
"m, n = (len(nums1), len(nums2))\ndp = [[0] * (n + 1) for _ in range(m + 1)]\nres = 0\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = dp[i - 1][j - 1] + 1 if nums1[i - 1] == nums2[j - 1] else 0\n res = max(res, dp[i][j])\nreturn res",
"m, n = (len(nums1), len(nums2))\ndp = [0]... | <|body_start_0|>
m, n = (len(nums1), len(nums2))
dp = [[0] * (n + 1) for _ in range(m + 1)]
res = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j - 1] + 1 if nums1[i - 1] == nums2[j - 1] else 0
res = max(res, dp[i][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: int"""
<|body_0|>
def findLengthONSpace(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: int"""
<|body_1|>
def findLengthB... | stack_v2_sparse_classes_36k_train_032871 | 3,123 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: int",
"name": "findLength",
"signature": "def findLength(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: int",
"name": "findLengthONSpace",
"signature": "def findLengthONSp... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: int
- def findLengthONSpace(self, nums1, nums2): :type nums1: List[int] :type nums2: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: int
- def findLengthONSpace(self, nums1, nums2): :type nums1: List[int] :type nums2: Lis... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findLength(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: int"""
<|body_0|>
def findLengthONSpace(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: int"""
<|body_1|>
def findLengthB... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLength(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: int"""
m, n = (len(nums1), len(nums2))
dp = [[0] * (n + 1) for _ in range(m + 1)]
res = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
... | the_stack_v2_python_sparse | M/MaximumLengthofRepeatedSubarray.py | bssrdf/pyleet | train | 2 | |
e66c4f3a29a2422e4cf1357bf37648830b614353 | [
"params = base.get_params(None, locals())\nrequest = http.Request('GET', self.get_url(), params)\nreturn (request, parsers.parse_json)",
"params = base.get_params(None, locals())\nrequest = http.Request('DELETE', self.get_url(), params)\nreturn (request, parsers.parse_json)"
] | <|body_start_0|>
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(None, locals())
request = http.Request('DELETE', self.get_url(), params)
... | Activities | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Activities:
def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None):
"""Returns all activities assigned to a particular user Upstream documentation: https://developers.pipedrive.com/v1#methods-Activities"""
<|body_0|>
def delete(self, ids):
... | stack_v2_sparse_classes_36k_train_032872 | 1,606 | permissive | [
{
"docstring": "Returns all activities assigned to a particular user Upstream documentation: https://developers.pipedrive.com/v1#methods-Activities",
"name": "get",
"signature": "def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None)"
},
{
"docstring": "Marks multipl... | 2 | null | Implement the Python class `Activities` described below.
Class description:
Implement the Activities class.
Method signatures and docstrings:
- def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None): Returns all activities assigned to a particular user Upstream documentation: https://deve... | Implement the Python class `Activities` described below.
Class description:
Implement the Activities class.
Method signatures and docstrings:
- def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None): Returns all activities assigned to a particular user Upstream documentation: https://deve... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Activities:
def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None):
"""Returns all activities assigned to a particular user Upstream documentation: https://developers.pipedrive.com/v1#methods-Activities"""
<|body_0|>
def delete(self, ids):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Activities:
def get(self, user_id=None, start=None, limit=None, start_date=None, end_date=None):
"""Returns all activities assigned to a particular user Upstream documentation: https://developers.pipedrive.com/v1#methods-Activities"""
params = base.get_params(None, locals())
request = ... | the_stack_v2_python_sparse | libsaas/services/pipedrive/activities.py | piplcom/libsaas | train | 1 | |
f012624da3d3c51b57055a66c85e430f80f9bb90 | [
"self._entry_id = entry_id\nself._device_id = device_id\nself.sonarr = sonarr",
"if self._device_id is None:\n return None\nreturn {ATTR_IDENTIFIERS: {(DOMAIN, self._device_id)}, ATTR_NAME: 'Activity Sensor', ATTR_MANUFACTURER: 'Sonarr', ATTR_SOFTWARE_VERSION: self.sonarr.app.info.version, 'entry_type': 'servi... | <|body_start_0|>
self._entry_id = entry_id
self._device_id = device_id
self.sonarr = sonarr
<|end_body_0|>
<|body_start_1|>
if self._device_id is None:
return None
return {ATTR_IDENTIFIERS: {(DOMAIN, self._device_id)}, ATTR_NAME: 'Activity Sensor', ATTR_MANUFACTURER:... | Defines a base Sonarr entity. | SonarrEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SonarrEntity:
"""Defines a base Sonarr entity."""
def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None:
"""Initialize the Sonarr entity."""
<|body_0|>
def device_info(self) -> DeviceInfo | None:
"""Return device information about the appli... | stack_v2_sparse_classes_36k_train_032873 | 1,083 | permissive | [
{
"docstring": "Initialize the Sonarr entity.",
"name": "__init__",
"signature": "def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None"
},
{
"docstring": "Return device information about the application.",
"name": "device_info",
"signature": "def device_info(self)... | 2 | stack_v2_sparse_classes_30k_train_013797 | Implement the Python class `SonarrEntity` described below.
Class description:
Defines a base Sonarr entity.
Method signatures and docstrings:
- def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None: Initialize the Sonarr entity.
- def device_info(self) -> DeviceInfo | None: Return device inform... | Implement the Python class `SonarrEntity` described below.
Class description:
Defines a base Sonarr entity.
Method signatures and docstrings:
- def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None: Initialize the Sonarr entity.
- def device_info(self) -> DeviceInfo | None: Return device inform... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class SonarrEntity:
"""Defines a base Sonarr entity."""
def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None:
"""Initialize the Sonarr entity."""
<|body_0|>
def device_info(self) -> DeviceInfo | None:
"""Return device information about the appli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SonarrEntity:
"""Defines a base Sonarr entity."""
def __init__(self, *, sonarr: Sonarr, entry_id: str, device_id: str) -> None:
"""Initialize the Sonarr entity."""
self._entry_id = entry_id
self._device_id = device_id
self.sonarr = sonarr
def device_info(self) -> Devi... | the_stack_v2_python_sparse | homeassistant/components/sonarr/entity.py | BenWoodford/home-assistant | train | 11 |
27220f36d04dc168c24d6fbfbae0a50d72f42e7d | [
"super().__init__(netg_a_to_b, netg_b_to_a, netd_a, netd_b, is_train, lambda_cycle, lambda_idt_a, lambda_idt_b, is_l1, optimizer_type, lr_policy, beta1, lr, cycle_noise_stddev)\nif is_train:\n self.fake_a_pool = ImagePool(pool_size)\n self.fake_b_pool = ImagePool(pool_size)\n\n def gan_loss(prediction: tor... | <|body_start_0|>
super().__init__(netg_a_to_b, netg_b_to_a, netd_a, netd_b, is_train, lambda_cycle, lambda_idt_a, lambda_idt_b, is_l1, optimizer_type, lr_policy, beta1, lr, cycle_noise_stddev)
if is_train:
self.fake_a_pool = ImagePool(pool_size)
self.fake_b_pool = ImagePool(pool_... | This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf | CycleGANModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CycleGANModel:
"""This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf"""
def __init__(self, netg_a_to_b: nn.Module, netg_b_to_a: nn.Module, netd_a: nn.Module=None, netd_b: nn.Module=None, ... | stack_v2_sparse_classes_36k_train_032874 | 6,724 | permissive | [
{
"docstring": "Initialize the CycleGAN class. Args: is_train: enable or disable training mode cycle_noise_stddev: Standard deviation of noise added to the cycle input. Mean is 0. pool_size: the size of image buffer that stores previously generated images beta1: momentum term of adam lr: initial learning rate f... | 5 | null | Implement the Python class `CycleGANModel` described below.
Class description:
This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
Method signatures and docstrings:
- def __init__(self, netg_a_to_b: nn.Module, netg... | Implement the Python class `CycleGANModel` described below.
Class description:
This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
Method signatures and docstrings:
- def __init__(self, netg_a_to_b: nn.Module, netg... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class CycleGANModel:
"""This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf"""
def __init__(self, netg_a_to_b: nn.Module, netg_b_to_a: nn.Module, netd_a: nn.Module=None, netd_b: nn.Module=None, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CycleGANModel:
"""This class implements the CycleGAN model, for learning image-to-image translation without paired data. CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf"""
def __init__(self, netg_a_to_b: nn.Module, netg_b_to_a: nn.Module, netd_a: nn.Module=None, netd_b: nn.Module=None, is_train: boo... | the_stack_v2_python_sparse | simulation/utils/machine_learning/cycle_gan/models/cycle_gan_model.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 |
96647a534284a3a0c57ba511cb75f8bb8cd45ddb | [
"session = db_apis.get_session()\nwith session.begin():\n db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))\n db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID])\nvrrp_port = data_models.Port(**amphorae_network_config[amphora.get(constants.ID)][constants... | <|body_start_0|>
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))
db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID])
vrrp_port = data_models.Port(**amphorae_net... | Task to notify the amphora post VIP plug. | AmphoraPostVIPPlug | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmphoraPostVIPPlug:
"""Task to notify the amphora post VIP plug."""
def execute(self, amphora, loadbalancer, amphorae_network_config):
"""Execute post_vip_routine."""
<|body_0|>
def revert(self, result, amphora, loadbalancer, *args, **kwargs):
"""Handle a failed ... | stack_v2_sparse_classes_36k_train_032875 | 28,773 | permissive | [
{
"docstring": "Execute post_vip_routine.",
"name": "execute",
"signature": "def execute(self, amphora, loadbalancer, amphorae_network_config)"
},
{
"docstring": "Handle a failed amphora vip plug notification.",
"name": "revert",
"signature": "def revert(self, result, amphora, loadbalanc... | 2 | null | Implement the Python class `AmphoraPostVIPPlug` described below.
Class description:
Task to notify the amphora post VIP plug.
Method signatures and docstrings:
- def execute(self, amphora, loadbalancer, amphorae_network_config): Execute post_vip_routine.
- def revert(self, result, amphora, loadbalancer, *args, **kwar... | Implement the Python class `AmphoraPostVIPPlug` described below.
Class description:
Task to notify the amphora post VIP plug.
Method signatures and docstrings:
- def execute(self, amphora, loadbalancer, amphorae_network_config): Execute post_vip_routine.
- def revert(self, result, amphora, loadbalancer, *args, **kwar... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class AmphoraPostVIPPlug:
"""Task to notify the amphora post VIP plug."""
def execute(self, amphora, loadbalancer, amphorae_network_config):
"""Execute post_vip_routine."""
<|body_0|>
def revert(self, result, amphora, loadbalancer, *args, **kwargs):
"""Handle a failed ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmphoraPostVIPPlug:
"""Task to notify the amphora post VIP plug."""
def execute(self, amphora, loadbalancer, amphorae_network_config):
"""Execute post_vip_routine."""
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=ampho... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/amphora_driver_tasks.py | openstack/octavia | train | 147 |
f7fab97b2d41897777e21973d724792c3959b3df | [
"if s1 == s2:\n return True\nif sorted(s1) != sorted(s2):\n return False\nfor i in range(1, len(s1)):\n if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):\n return True\n if self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i]):\n return True\nreturn Fa... | <|body_start_0|>
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
for i in range(1, len(s1)):
if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):
return True
if self.isScramble(s1[:i], s2[-i:]) ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isScramble_1(self, s1: str, s2: str) -> bool:
"""递归:"""
<|body_0|>
def isScramble(self, s1: str, s2: str) -> bool:
"""TODO: 动态规划: dp[i][j][len] 表示 s1[i:i+len] 与 s2[j:j+len] 是否为扰乱字符串"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s1... | stack_v2_sparse_classes_36k_train_032876 | 3,244 | no_license | [
{
"docstring": "递归:",
"name": "isScramble_1",
"signature": "def isScramble_1(self, s1: str, s2: str) -> bool"
},
{
"docstring": "TODO: 动态规划: dp[i][j][len] 表示 s1[i:i+len] 与 s2[j:j+len] 是否为扰乱字符串",
"name": "isScramble",
"signature": "def isScramble(self, s1: str, s2: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_012052 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble_1(self, s1: str, s2: str) -> bool: 递归:
- def isScramble(self, s1: str, s2: str) -> bool: TODO: 动态规划: dp[i][j][len] 表示 s1[i:i+len] 与 s2[j:j+len] 是否为扰乱字符串 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble_1(self, s1: str, s2: str) -> bool: 递归:
- def isScramble(self, s1: str, s2: str) -> bool: TODO: 动态规划: dp[i][j][len] 表示 s1[i:i+len] 与 s2[j:j+len] 是否为扰乱字符串
<|skeleto... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def isScramble_1(self, s1: str, s2: str) -> bool:
"""递归:"""
<|body_0|>
def isScramble(self, s1: str, s2: str) -> bool:
"""TODO: 动态规划: dp[i][j][len] 表示 s1[i:i+len] 与 s2[j:j+len] 是否为扰乱字符串"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isScramble_1(self, s1: str, s2: str) -> bool:
"""递归:"""
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
for i in range(1, len(s1)):
if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):
... | the_stack_v2_python_sparse | .leetcode/87.扰乱字符串.py | xiaoruijiang/algorithm | train | 0 | |
ebfa0e47039799c2f5187d5d81727f11b50aef35 | [
"from .context import Context\nstate_factories = context.environment[Context.STATE_FACTORIES]\nfor state_factory in state_factories:\n state = state_factory.get_state_to_bind(obj, name, context)\n if state is not None:\n break\nelse:\n state = obj\nreturn state",
"from .context import Context\nobj... | <|body_start_0|>
from .context import Context
state_factories = context.environment[Context.STATE_FACTORIES]
for state_factory in state_factories:
state = state_factory.get_state_to_bind(obj, name, context)
if state is not None:
break
else:
... | The naming manager. | NamingManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamingManager:
"""The naming manager."""
def get_state_to_bind(self, obj, name, context):
"""Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them one by one until it gets a non-None result indicating that ... | stack_v2_sparse_classes_36k_train_032877 | 2,743 | no_license | [
{
"docstring": "Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them one by one until it gets a non-None result indicating that the factory recognised the object and created state information for it. If none of the factories recogniz... | 2 | stack_v2_sparse_classes_30k_test_001087 | Implement the Python class `NamingManager` described below.
Class description:
The naming manager.
Method signatures and docstrings:
- def get_state_to_bind(self, obj, name, context): Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them on... | Implement the Python class `NamingManager` described below.
Class description:
The naming manager.
Method signatures and docstrings:
- def get_state_to_bind(self, obj, name, context): Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them on... | 08218b697db91e55e8e0c49664a0b0cb44b4ab93 | <|skeleton|>
class NamingManager:
"""The naming manager."""
def get_state_to_bind(self, obj, name, context):
"""Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them one by one until it gets a non-None result indicating that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamingManager:
"""The naming manager."""
def get_state_to_bind(self, obj, name, context):
"""Returns the state of an object for binding. The naming manager asks the context for its list of STATE factories and then calls them one by one until it gets a non-None result indicating that the factory r... | the_stack_v2_python_sparse | .venv/Lib/site-packages/apptools/naming/naming_manager.py | Bdye15/Sample_Programs | train | 0 |
377810d07b9d61c9129779459ac6f0ecbb23a903 | [
"file = open(postgap.Globals.DATABASES_DIR + '/GRASP.txt')\nres = [self.get_association(line, diseases, iris) for line in file]\nres = filter(lambda X: X is not None, res)\nlogging.info('\\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in GRASP' % (len(res), ', '.join(diseases), ', '.join(iris)))\n... | <|body_start_0|>
file = open(postgap.Globals.DATABASES_DIR + '/GRASP.txt')
res = [self.get_association(line, diseases, iris) for line in file]
res = filter(lambda X: X is not None, res)
logging.info('\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in GRASP' % (len(res), ... | GRASP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRASP:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases, iris):
... | stack_v2_sparse_classes_36k_train_032878 | 27,853 | permissive | [
{
"docstring": "Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]",
"name": "run",
"signature": "def run(self, diseases, iris)"
},
{
"docstring": "GRASP file format: 1. NHLBIkey 2. HU... | 2 | stack_v2_sparse_classes_30k_val_000796 | Implement the Python class `GRASP` described below.
Class description:
Implement the GRASP class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Asso... | Implement the Python class `GRASP` described below.
Class description:
Implement the GRASP class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Asso... | d5a2d7b9238347c9a598fa8ac0da8cb737c6b6a6 | <|skeleton|>
class GRASP:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases, iris):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRASP:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GRASP Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
file = open(postgap.Globals.DATABASES_DIR + '/GRASP.txt')
res = [self.get_assoc... | the_stack_v2_python_sparse | lib/postgap/GWAS.py | Ensembl/postgap | train | 41 | |
93ddfae7b0cf462b776b38564f526ce2a41107c5 | [
"words = sorted(words, key=lambda x: len(x), reverse=True)\ntrie = Trie()\nres = 0\nfor word in words:\n res += trie.insert(word[::-1])\nreturn res",
"reversed_word = []\nsize = len(words)\nfor word in words:\n reversed_word.append(word[::-1])\nres = 0\nreversed_word.sort()\nfor i in range(len(reversed_word... | <|body_start_0|>
words = sorted(words, key=lambda x: len(x), reverse=True)
trie = Trie()
res = 0
for word in words:
res += trie.insert(word[::-1])
return res
<|end_body_0|>
<|body_start_1|>
reversed_word = []
size = len(words)
for word in word... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
"""前缀树解法"""
<|body_0|>
def minimumLengthEncoding(self, words: List[str]) -> int:
"""排序检查解法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
words = sorted(words, key=lambda x: len(x)... | stack_v2_sparse_classes_36k_train_032879 | 1,547 | no_license | [
{
"docstring": "前缀树解法",
"name": "minimumLengthEncoding",
"signature": "def minimumLengthEncoding(self, words: List[str]) -> int"
},
{
"docstring": "排序检查解法",
"name": "minimumLengthEncoding",
"signature": "def minimumLengthEncoding(self, words: List[str]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words: List[str]) -> int: 前缀树解法
- def minimumLengthEncoding(self, words: List[str]) -> int: 排序检查解法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words: List[str]) -> int: 前缀树解法
- def minimumLengthEncoding(self, words: List[str]) -> int: 排序检查解法
<|skeleton|>
class Solution:
def minimumL... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
"""前缀树解法"""
<|body_0|>
def minimumLengthEncoding(self, words: List[str]) -> int:
"""排序检查解法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
"""前缀树解法"""
words = sorted(words, key=lambda x: len(x), reverse=True)
trie = Trie()
res = 0
for word in words:
res += trie.insert(word[::-1])
return res
def minimumLengthEncodin... | the_stack_v2_python_sparse | 二刷+题解/中等/minimumLengthEncoding.py | 1oser5/LeetCode | train | 0 | |
42c8bbb15a1f1955b74b23c755b69fabcac104cb | [
"if self.setting('USE_UNIQUE_USER_ID', False):\n if 'sub' in response:\n return response['sub']\n else:\n return response['id']\nelse:\n return details['email']",
"email = response.get('email', '')\nname, given_name, family_name = (response.get('name', ''), response.get('given_name', ''), r... | <|body_start_0|>
if self.setting('USE_UNIQUE_USER_ID', False):
if 'sub' in response:
return response['sub']
else:
return response['id']
else:
return details['email']
<|end_body_0|>
<|body_start_1|>
email = response.get('email',... | BaseGoogleAuth | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
<|body_0|>
def get_user_details(self, response):
"""Return user details from Google API account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.set... | stack_v2_sparse_classes_36k_train_032880 | 6,302 | permissive | [
{
"docstring": "Use google email as unique id",
"name": "get_user_id",
"signature": "def get_user_id(self, details, response)"
},
{
"docstring": "Return user details from Google API account",
"name": "get_user_details",
"signature": "def get_user_details(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017655 | Implement the Python class `BaseGoogleAuth` described below.
Class description:
Implement the BaseGoogleAuth class.
Method signatures and docstrings:
- def get_user_id(self, details, response): Use google email as unique id
- def get_user_details(self, response): Return user details from Google API account | Implement the Python class `BaseGoogleAuth` described below.
Class description:
Implement the BaseGoogleAuth class.
Method signatures and docstrings:
- def get_user_id(self, details, response): Use google email as unique id
- def get_user_details(self, response): Return user details from Google API account
<|skeleto... | cf95380a177e9b8d1f3b4da03543fb2f0d248bf3 | <|skeleton|>
class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
<|body_0|>
def get_user_details(self, response):
"""Return user details from Google API account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
if self.setting('USE_UNIQUE_USER_ID', False):
if 'sub' in response:
return response['sub']
else:
return response['id']
else:
... | the_stack_v2_python_sparse | social_core/backends/google.py | python-social-auth/social-core | train | 831 | |
82b7a1472da221a53d8a2485753057f9610a160d | [
"self.name = _name\nself.region_code_list = []\nself.status = 'enabled'\nself.memberships = {}\nself.vCPUs = 0\nself.original_vCPUs = 0\nself.avail_vCPUs = 0\nself.mem_cap = 0\nself.original_mem_cap = 0\nself.avail_mem_cap = 0\nself.local_disk_cap = 0\nself.original_local_disk_cap = 0\nself.avail_local_disk_cap = 0... | <|body_start_0|>
self.name = _name
self.region_code_list = []
self.status = 'enabled'
self.memberships = {}
self.vCPUs = 0
self.original_vCPUs = 0
self.avail_vCPUs = 0
self.mem_cap = 0
self.original_mem_cap = 0
self.avail_mem_cap = 0
... | Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter. | Datacenter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Datacenter:
"""Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter."""
def __init__(self, _name):
"""Init Datacenter object."""
<|body_0... | stack_v2_sparse_classes_36k_train_032881 | 21,975 | permissive | [
{
"docstring": "Init Datacenter object.",
"name": "__init__",
"signature": "def __init__(self, _name)"
},
{
"docstring": "Init datacenter resources to 0.",
"name": "init_resources",
"signature": "def init_resources(self)"
},
{
"docstring": "Return JSON info for datacenter object.... | 3 | stack_v2_sparse_classes_30k_train_015541 | Implement the Python class `Datacenter` described below.
Class description:
Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `Datacenter` described below.
Class description:
Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter.
Method signatures and docstrings:
- def __init__(... | ea89fbfbbb488938ac322e2a9bb7f8f448a7cd76 | <|skeleton|>
class Datacenter:
"""Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter."""
def __init__(self, _name):
"""Init Datacenter object."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Datacenter:
"""Datacenter Class. This object represents a datacenter. It contains all memberships or logical groups in the datacenter, all resources available, placed vms, and more throughout the datacenter."""
def __init__(self, _name):
"""Init Datacenter object."""
self.name = _name
... | the_stack_v2_python_sparse | valet/engine/resource_manager/resource_base.py | att-comdev/valet | train | 5 |
6b3264ea2fa1f419a4a2667f54cd1af1a5707c20 | [
"current_app.logger.debug('Create chat message from DTO')\nnew_message = cls()\nnew_message.project_id = dto.project_id\nnew_message.user_id = dto.user_id\nallowed_tags = ['a', 'b', 'blockquote', 'br', 'code', 'em', 'h1', 'h2', 'h3', 'img', 'i', 'li', 'ol', 'p', 'pre', 'strong', 'ul']\nallowed_atrributes = {'a': ['... | <|body_start_0|>
current_app.logger.debug('Create chat message from DTO')
new_message = cls()
new_message.project_id = dto.project_id
new_message.user_id = dto.user_id
allowed_tags = ['a', 'b', 'blockquote', 'br', 'code', 'em', 'h1', 'h2', 'h3', 'img', 'i', 'li', 'ol', 'p', 'pre'... | Contains all project info localized into supported languages | ProjectChat | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectChat:
"""Contains all project info localized into supported languages"""
def create_from_dto(cls, dto: ChatMessageDTO):
"""Creates a new ProjectInfo class from dto, used from project edit"""
<|body_0|>
def get_messages(project_id: int, page: int, per_page: int=20)... | stack_v2_sparse_classes_36k_train_032882 | 2,959 | permissive | [
{
"docstring": "Creates a new ProjectInfo class from dto, used from project edit",
"name": "create_from_dto",
"signature": "def create_from_dto(cls, dto: ChatMessageDTO)"
},
{
"docstring": "Get all messages on the project",
"name": "get_messages",
"signature": "def get_messages(project_i... | 2 | stack_v2_sparse_classes_30k_train_017226 | Implement the Python class `ProjectChat` described below.
Class description:
Contains all project info localized into supported languages
Method signatures and docstrings:
- def create_from_dto(cls, dto: ChatMessageDTO): Creates a new ProjectInfo class from dto, used from project edit
- def get_messages(project_id: i... | Implement the Python class `ProjectChat` described below.
Class description:
Contains all project info localized into supported languages
Method signatures and docstrings:
- def create_from_dto(cls, dto: ChatMessageDTO): Creates a new ProjectInfo class from dto, used from project edit
- def get_messages(project_id: i... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class ProjectChat:
"""Contains all project info localized into supported languages"""
def create_from_dto(cls, dto: ChatMessageDTO):
"""Creates a new ProjectInfo class from dto, used from project edit"""
<|body_0|>
def get_messages(project_id: int, page: int, per_page: int=20)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectChat:
"""Contains all project info localized into supported languages"""
def create_from_dto(cls, dto: ChatMessageDTO):
"""Creates a new ProjectInfo class from dto, used from project edit"""
current_app.logger.debug('Create chat message from DTO')
new_message = cls()
... | the_stack_v2_python_sparse | backend/models/postgis/project_chat.py | hotosm/tasking-manager | train | 526 |
654d1d3cc6e6dc4341c4c2ae4627f6b58877500d | [
"self.psum = []\ns = 0\nfor n in w:\n s += n\n self.psum.append(s)\nself.total = s",
"target = self.total * random.random()\nfor i, x in enumerate(self.psum):\n if target < x:\n return i\nreturn -1"
] | <|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
<|end_body_0|>
<|body_start_1|>
target = self.total * random.random()
for i, x in enumerate(self.psum):
if target < x:
return i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.psum = []
s = 0
for n in w:
s += n
self.psum.append... | stack_v2_sparse_classes_36k_train_032883 | 1,609 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 6aaf58b1e1170a994affd6330d90b89aaaf582d9 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.psum = []
s = 0
for n in w:
s += n
self.psum.append(s)
self.total = s
def pickIndex(self):
""":rtype: int"""
target = self.total * random.random()
for i, ... | the_stack_v2_python_sparse | Python/528.py | skywhat/leetcode | train | 82 | |
786981f34fbbbe5895356d53224c4c2665930c17 | [
"if len(args) == 0:\n return ()\nif len(args) == 2:\n substitution_pairs = (args,)\nelif len(args) == 1:\n arg = args[0]\n if isinstance(arg, dict):\n if arg == {}:\n return ()\n substitution_pairs = arg.items()\n else:\n if len(arg) == 0:\n return ()\n ... | <|body_start_0|>
if len(args) == 0:
return ()
if len(args) == 2:
substitution_pairs = (args,)
elif len(args) == 1:
arg = args[0]
if isinstance(arg, dict):
if arg == {}:
return ()
substitution_pair... | SubstitutionPairsParsingUtility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubstitutionPairsParsingUtility:
def parse(*args, required_object_type: Optional[Type]=object):
"""Extracts substitution pairs from general argument and check them. While extracting, also checks some invariants regarding the shape and content of the substitution pairs. The object is iter... | stack_v2_sparse_classes_36k_train_032884 | 16,598 | no_license | [
{
"docstring": "Extracts substitution pairs from general argument and check them. While extracting, also checks some invariants regarding the shape and content of the substitution pairs. The object is iterable of pairs (sequence of length 2). The first element is a pair occur only once among first elements (i.e... | 2 | stack_v2_sparse_classes_30k_train_017019 | Implement the Python class `SubstitutionPairsParsingUtility` described below.
Class description:
Implement the SubstitutionPairsParsingUtility class.
Method signatures and docstrings:
- def parse(*args, required_object_type: Optional[Type]=object): Extracts substitution pairs from general argument and check them. Whi... | Implement the Python class `SubstitutionPairsParsingUtility` described below.
Class description:
Implement the SubstitutionPairsParsingUtility class.
Method signatures and docstrings:
- def parse(*args, required_object_type: Optional[Type]=object): Extracts substitution pairs from general argument and check them. Whi... | acaf4d340f8ab0807ac655186a154b064d49f12c | <|skeleton|>
class SubstitutionPairsParsingUtility:
def parse(*args, required_object_type: Optional[Type]=object):
"""Extracts substitution pairs from general argument and check them. While extracting, also checks some invariants regarding the shape and content of the substitution pairs. The object is iter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubstitutionPairsParsingUtility:
def parse(*args, required_object_type: Optional[Type]=object):
"""Extracts substitution pairs from general argument and check them. While extracting, also checks some invariants regarding the shape and content of the substitution pairs. The object is iterable of pairs ... | the_stack_v2_python_sparse | neads/activation_model/symbolic_objects/symbolic_object.py | Thrayld/neads | train | 0 | |
f5c2a3b7c94256000266547f28661a49c4e681f2 | [
"if request.dbsession is None:\n raise DBAPIError\npreferences = cls(**kwargs)\nrequest.dbsession.add(preferences)\nreturn request.dbsession.query(cls).filter(cls.account_id == kwargs['account_id']).one_or_none()",
"if request.dbsession is None:\n raise DBAPIError\nprefs_to_update = request.dbsession.query(... | <|body_start_0|>
if request.dbsession is None:
raise DBAPIError
preferences = cls(**kwargs)
request.dbsession.add(preferences)
return request.dbsession.query(cls).filter(cls.account_id == kwargs['account_id']).one_or_none()
<|end_body_0|>
<|body_start_1|>
if request.... | Preferences | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preferences:
def set_default(cls, request, **kwargs):
"""Method to create new user preferences in database"""
<|body_0|>
def update_prefs(cls, request, **kwargs):
"""Method to update user preferences in database by reassigning cls on the correct account id column to ... | stack_v2_sparse_classes_36k_train_032885 | 2,084 | no_license | [
{
"docstring": "Method to create new user preferences in database",
"name": "set_default",
"signature": "def set_default(cls, request, **kwargs)"
},
{
"docstring": "Method to update user preferences in database by reassigning cls on the correct account id column to the new preferences on the kwa... | 3 | stack_v2_sparse_classes_30k_test_000803 | Implement the Python class `Preferences` described below.
Class description:
Implement the Preferences class.
Method signatures and docstrings:
- def set_default(cls, request, **kwargs): Method to create new user preferences in database
- def update_prefs(cls, request, **kwargs): Method to update user preferences in ... | Implement the Python class `Preferences` described below.
Class description:
Implement the Preferences class.
Method signatures and docstrings:
- def set_default(cls, request, **kwargs): Method to create new user preferences in database
- def update_prefs(cls, request, **kwargs): Method to update user preferences in ... | 6612a93e1e1b5e4a47a10e5ba15cb1e2a4a68525 | <|skeleton|>
class Preferences:
def set_default(cls, request, **kwargs):
"""Method to create new user preferences in database"""
<|body_0|>
def update_prefs(cls, request, **kwargs):
"""Method to update user preferences in database by reassigning cls on the correct account id column to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preferences:
def set_default(cls, request, **kwargs):
"""Method to create new user preferences in database"""
if request.dbsession is None:
raise DBAPIError
preferences = cls(**kwargs)
request.dbsession.add(preferences)
return request.dbsession.query(cls).fi... | the_stack_v2_python_sparse | news_api/models/preferences.py | Intellinewz/intellinews_api | train | 3 | |
26b8f682be2c7d50539c11bb8c0724884c0b153c | [
"meetup = get_meetup(meetup_id)\nif not meetup:\n error_response['message'] = 'Meetup not found'\n return (error_response, 404)\nsuccess_response['message'] = 'Meetup successfully fetched'\nsuccess_response['data'] = {'meetup': meetup}\nreturn (success_response, 200)",
"meetup = Meetup.query.filter_by(id=me... | <|body_start_0|>
meetup = get_meetup(meetup_id)
if not meetup:
error_response['message'] = 'Meetup not found'
return (error_response, 404)
success_response['message'] = 'Meetup successfully fetched'
success_response['data'] = {'meetup': meetup}
return (suc... | SingleMeetupResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleMeetupResource:
def get(self, meetup_id):
""""Endpoint to get a single meetup"""
<|body_0|>
def put(self, meetup_id):
""""Endpoint to update a meetup"""
<|body_1|>
def delete(self, meetup_id):
""""Endpoint to delete a meetup"""
<|bo... | stack_v2_sparse_classes_36k_train_032886 | 5,967 | no_license | [
{
"docstring": "\"Endpoint to get a single meetup",
"name": "get",
"signature": "def get(self, meetup_id)"
},
{
"docstring": "\"Endpoint to update a meetup",
"name": "put",
"signature": "def put(self, meetup_id)"
},
{
"docstring": "\"Endpoint to delete a meetup",
"name": "del... | 3 | stack_v2_sparse_classes_30k_train_021327 | Implement the Python class `SingleMeetupResource` described below.
Class description:
Implement the SingleMeetupResource class.
Method signatures and docstrings:
- def get(self, meetup_id): "Endpoint to get a single meetup
- def put(self, meetup_id): "Endpoint to update a meetup
- def delete(self, meetup_id): "Endpoi... | Implement the Python class `SingleMeetupResource` described below.
Class description:
Implement the SingleMeetupResource class.
Method signatures and docstrings:
- def get(self, meetup_id): "Endpoint to get a single meetup
- def put(self, meetup_id): "Endpoint to update a meetup
- def delete(self, meetup_id): "Endpoi... | aa62556731fdc5b83c3819b0d94df34a28e98dcd | <|skeleton|>
class SingleMeetupResource:
def get(self, meetup_id):
""""Endpoint to get a single meetup"""
<|body_0|>
def put(self, meetup_id):
""""Endpoint to update a meetup"""
<|body_1|>
def delete(self, meetup_id):
""""Endpoint to delete a meetup"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleMeetupResource:
def get(self, meetup_id):
""""Endpoint to get a single meetup"""
meetup = get_meetup(meetup_id)
if not meetup:
error_response['message'] = 'Meetup not found'
return (error_response, 404)
success_response['message'] = 'Meetup success... | the_stack_v2_python_sparse | resources/meetup.py | Paccy10/Questioner-python | train | 0 | |
a69841c6f3d8d7535cd32ac056029ea5752f9a7f | [
"for obj in obj_list['hits']['hits']:\n obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)\nreturn obj_list['hits']",
"aggs = obj_list.get('aggregations')\nif not aggs:\n return missing\nfor name, agg in aggs.items():\n vocab = Vocabularies.get_vocabulary(name)\n if not vo... | <|body_start_0|>
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits']
<|end_body_0|>
<|body_start_1|>
aggs = obj_list.get('aggregations')
if not aggs:
return missing
f... | Schema for dumping extra information in the UI. | UIListSchema | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_032887 | 6,926 | permissive | [
{
"docstring": "Apply hits transformation.",
"name": "get_hits",
"signature": "def get_hits(self, obj_list)"
},
{
"docstring": "Apply aggregations transformation.",
"name": "get_aggs",
"signature": "def get_aggs(self, obj_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006602 | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation. | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation.
<|skeleton|>
class UIListSchema... | 78ad536dbb95494967bf8de248cf922e5040e844 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits... | the_stack_v2_python_sparse | invenio_rdm_records/resources/serializers/ui/schema.py | tu-graz-library/invenio-rdm-records | train | 0 |
f867a615154881cb7f13f173ac17da7082512838 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Relation()",
"from ..entity import Entity\nfrom .relation_type import RelationType\nfrom .set import Set\nfrom .term import Term\nfrom ..entity import Entity\nfrom .relation_type import RelationType\nfrom .set import Set\nfrom .term im... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Relation()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .relation_type import RelationType
from .set import Set
from .term import Term
from ..... | Relation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Relation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Relation:
"""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: Relation... | stack_v2_sparse_classes_36k_train_032888 | 3,127 | 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: Relation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | null | Implement the Python class `Relation` described below.
Class description:
Implement the Relation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Relation: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | Implement the Python class `Relation` described below.
Class description:
Implement the Relation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Relation: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Relation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Relation:
"""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: Relation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Relation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Relation:
"""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: Relation"""
if... | the_stack_v2_python_sparse | msgraph/generated/models/term_store/relation.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
43ad4d1e8c2b29aa8fc1db4f7f1add73fcbd0b9e | [
"catalog = RestaurantCatalog()\ntry:\n res = requests.get(self.ENDPOINT, timeout=4)\n if res.status_code == 200:\n catalog.add_many([Restaurant.from_json(row) for row in res.json()])\nexcept ConnectionError:\n print('Failed to connect to API')\nreturn catalog",
"if len(data) == 0:\n return\nput... | <|body_start_0|>
catalog = RestaurantCatalog()
try:
res = requests.get(self.ENDPOINT, timeout=4)
if res.status_code == 200:
catalog.add_many([Restaurant.from_json(row) for row in res.json()])
except ConnectionError:
print('Failed to connect to ... | DatabaseOutputter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
<|body_0|>
def insert(self, data: Union[dict, list], token: str) -> None:
"""Send restaurants marked as insert to API :param data: a list of restaurants or a si... | stack_v2_sparse_classes_36k_train_032889 | 7,558 | no_license | [
{
"docstring": "Retrieve all current restaurants from the API",
"name": "get",
"signature": "def get(self) -> RestaurantCatalog"
},
{
"docstring": "Send restaurants marked as insert to API :param data: a list of restaurants or a single restaurant :param token: an identifier for the current sessi... | 4 | stack_v2_sparse_classes_30k_train_013811 | Implement the Python class `DatabaseOutputter` described below.
Class description:
Implement the DatabaseOutputter class.
Method signatures and docstrings:
- def get(self) -> RestaurantCatalog: Retrieve all current restaurants from the API
- def insert(self, data: Union[dict, list], token: str) -> None: Send restaura... | Implement the Python class `DatabaseOutputter` described below.
Class description:
Implement the DatabaseOutputter class.
Method signatures and docstrings:
- def get(self) -> RestaurantCatalog: Retrieve all current restaurants from the API
- def insert(self, data: Union[dict, list], token: str) -> None: Send restaura... | b9d4dd32b4d0dfaa287fd138887a616d962227b7 | <|skeleton|>
class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
<|body_0|>
def insert(self, data: Union[dict, list], token: str) -> None:
"""Send restaurants marked as insert to API :param data: a list of restaurants or a si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
catalog = RestaurantCatalog()
try:
res = requests.get(self.ENDPOINT, timeout=4)
if res.status_code == 200:
catalog.add_many([Restaurant.fro... | the_stack_v2_python_sparse | filter_xml/data_outputter.py | sw814f21/filter_xml | train | 0 | |
0c8dbca23cac908046cf4b261aa2d4d0d57964ba | [
"add_tuple, error_tuple = database.import_data('csv_files', 'products.csv', 'customers.csv', 'rentals.csv')\nself.assertEqual(add_tuple, (3, 3, 5))\nself.assertEqual(error_tuple, (0, 0, 0))\nadd_tuple, error_tuple = database.import_data('csv_files', 'products1.csv', 'customers1.csv', 'rentals1.csv')\nself.assertEqu... | <|body_start_0|>
add_tuple, error_tuple = database.import_data('csv_files', 'products.csv', 'customers.csv', 'rentals.csv')
self.assertEqual(add_tuple, (3, 3, 5))
self.assertEqual(error_tuple, (0, 0, 0))
add_tuple, error_tuple = database.import_data('csv_files', 'products1.csv', 'custome... | Define a class for testing database functions | DatabaseTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseTests:
"""Define a class for testing database functions"""
def test_import_data(self):
"""Test importing data from csv files"""
<|body_0|>
def test_show_available_products(self):
"""Test showing available products"""
<|body_1|>
def test_show_... | stack_v2_sparse_classes_36k_train_032890 | 2,440 | no_license | [
{
"docstring": "Test importing data from csv files",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Test showing available products",
"name": "test_show_available_products",
"signature": "def test_show_available_products(self)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_000774 | Implement the Python class `DatabaseTests` described below.
Class description:
Define a class for testing database functions
Method signatures and docstrings:
- def test_import_data(self): Test importing data from csv files
- def test_show_available_products(self): Test showing available products
- def test_show_rent... | Implement the Python class `DatabaseTests` described below.
Class description:
Define a class for testing database functions
Method signatures and docstrings:
- def test_import_data(self): Test importing data from csv files
- def test_show_available_products(self): Test showing available products
- def test_show_rent... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class DatabaseTests:
"""Define a class for testing database functions"""
def test_import_data(self):
"""Test importing data from csv files"""
<|body_0|>
def test_show_available_products(self):
"""Test showing available products"""
<|body_1|>
def test_show_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseTests:
"""Define a class for testing database functions"""
def test_import_data(self):
"""Test importing data from csv files"""
add_tuple, error_tuple = database.import_data('csv_files', 'products.csv', 'customers.csv', 'rentals.csv')
self.assertEqual(add_tuple, (3, 3, 5))... | the_stack_v2_python_sparse | students/bcoates/lesson05/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
b153aa7700ec53e4c2af5cacb65e70c00561f9ff | [
"self.with_unknown = with_unknown\nif osp.isfile(character):\n with open(character, 'r', encoding='utf-8') as character_file:\n if character.endswith('.txt'):\n print_log('loading user predefined recognition dictionary from txt file: %s to build the ACE converter !!!' % character)\n ... | <|body_start_0|>
self.with_unknown = with_unknown
if osp.isfile(character):
with open(character, 'r', encoding='utf-8') as character_file:
if character.endswith('.txt'):
print_log('loading user predefined recognition dictionary from txt file: %s to build t... | Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019 | ACELabelConverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACELabelConverter:
"""Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019"""
def __init__(self, character, with_unknown=False):
"""Convert between text-label and text-index Args: character (st... | stack_v2_sparse_classes_36k_train_032891 | 5,144 | permissive | [
{
"docstring": "Convert between text-label and text-index Args: character (str): set of the possible recognition characters dictionary. with_unknown (bool): whether to encode the characters which are out of the dictionary to ['[UNK]']",
"name": "__init__",
"signature": "def __init__(self, character, wit... | 3 | stack_v2_sparse_classes_30k_train_000551 | Implement the Python class `ACELabelConverter` described below.
Class description:
Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019
Method signatures and docstrings:
- def __init__(self, character, with_unknown=False): Conv... | Implement the Python class `ACELabelConverter` described below.
Class description:
Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019
Method signatures and docstrings:
- def __init__(self, character, with_unknown=False): Conv... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class ACELabelConverter:
"""Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019"""
def __init__(self, character, with_unknown=False):
"""Convert between text-label and text-index Args: character (st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ACELabelConverter:
"""Convert between text-label and text-index, ACE Loss Converter in Ref [1] Ref: [1] Aggregation Cross-Entropy for Sequence Recognition. CVPR-2019"""
def __init__(self, character, with_unknown=False):
"""Convert between text-label and text-index Args: character (str): set of th... | the_stack_v2_python_sparse | davarocr/davarocr/davar_rcg/core/converter/ace_converter.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
c6163fe8727199a6420f51b12472e1f9ff0cca4a | [
"import os\nuppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])\nbase_dir = uppath(__file__, 2)\nbest_setting = torch.load(base_dir + '/states/{}.pth'.format(filename))\nif 'LF' in filename.upper():\n self.ML_integrator = MLP2H_Separable_Hamil_LF(2, 20)\nelif 'VV' in filename.upper():\n self.ML_in... | <|body_start_0|>
import os
uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
base_dir = uppath(__file__, 2)
best_setting = torch.load(base_dir + '/states/{}.pth'.format(filename))
if 'LF' in filename.upper():
self.ML_integrator = MLP2H_Separable_Hamil_LF... | list of class of ML integrator, since all of them use the same interface but just different pth | ML_integrator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ML_integrator:
"""list of class of ML integrator, since all of them use the same interface but just different pth"""
def __init__(self, filename):
"""base initializer for all ML Parameters ---------- filename : string filename is the name of the states that to be initialized Precauti... | stack_v2_sparse_classes_36k_train_032892 | 3,015 | no_license | [
{
"docstring": "base initializer for all ML Parameters ---------- filename : string filename is the name of the states that to be initialized Precaution ---------- for states for LF, its must be written with LF code in the string so its recognizeable the same goes for VV and PV or other methods to be introduced... | 2 | stack_v2_sparse_classes_30k_train_020686 | Implement the Python class `ML_integrator` described below.
Class description:
list of class of ML integrator, since all of them use the same interface but just different pth
Method signatures and docstrings:
- def __init__(self, filename): base initializer for all ML Parameters ---------- filename : string filename ... | Implement the Python class `ML_integrator` described below.
Class description:
list of class of ML integrator, since all of them use the same interface but just different pth
Method signatures and docstrings:
- def __init__(self, filename): base initializer for all ML Parameters ---------- filename : string filename ... | fe939de84a8d8f3ad74c0f3172214e0304bff05f | <|skeleton|>
class ML_integrator:
"""list of class of ML integrator, since all of them use the same interface but just different pth"""
def __init__(self, filename):
"""base initializer for all ML Parameters ---------- filename : string filename is the name of the states that to be initialized Precauti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ML_integrator:
"""list of class of ML integrator, since all of them use the same interface but just different pth"""
def __init__(self, filename):
"""base initializer for all ML Parameters ---------- filename : string filename is the name of the states that to be initialized Precaution ----------... | the_stack_v2_python_sparse | Integrator/methods/ML_integrator.py | simonjulianl/Langevin_Machine_Learning | train | 4 |
302d001a01951485ae839b1d9e47a52aeee4b6ea | [
"names_file = tfds.core.tfds_path(_LABELS_FNAME)\nfeatures_dict = {'image': tfds.features.Image(), 'label': tfds.features.ClassLabel(names_file=names_file)}\nif self.version > '2.0.0':\n features_dict['id'] = tfds.features.Text()\nreturn tfds.core.DatasetInfo(builder=self, description=_DESCRIPTION, features=tfds... | <|body_start_0|>
names_file = tfds.core.tfds_path(_LABELS_FNAME)
features_dict = {'image': tfds.features.Image(), 'label': tfds.features.ClassLabel(names_file=names_file)}
if self.version > '2.0.0':
features_dict['id'] = tfds.features.Text()
return tfds.core.DatasetInfo(build... | Food-101 Images dataset. | Food101 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Food101:
"""Food-101 Images dataset."""
def _info(self):
"""Define Dataset Info."""
<|body_0|>
def _split_generators(self, dl_manager):
"""Define Splits."""
<|body_1|>
def _generate_examples(self, json_file_path, image_dir_path):
"""Generate ... | stack_v2_sparse_classes_36k_train_032893 | 3,810 | permissive | [
{
"docstring": "Define Dataset Info.",
"name": "_info",
"signature": "def _info(self)"
},
{
"docstring": "Define Splits.",
"name": "_split_generators",
"signature": "def _split_generators(self, dl_manager)"
},
{
"docstring": "Generate images and labels for splits.",
"name": "... | 3 | null | Implement the Python class `Food101` described below.
Class description:
Food-101 Images dataset.
Method signatures and docstrings:
- def _info(self): Define Dataset Info.
- def _split_generators(self, dl_manager): Define Splits.
- def _generate_examples(self, json_file_path, image_dir_path): Generate images and labe... | Implement the Python class `Food101` described below.
Class description:
Food-101 Images dataset.
Method signatures and docstrings:
- def _info(self): Define Dataset Info.
- def _split_generators(self, dl_manager): Define Splits.
- def _generate_examples(self, json_file_path, image_dir_path): Generate images and labe... | 41ae3cf1439711ed2f50f99caa0e6702082e6d37 | <|skeleton|>
class Food101:
"""Food-101 Images dataset."""
def _info(self):
"""Define Dataset Info."""
<|body_0|>
def _split_generators(self, dl_manager):
"""Define Splits."""
<|body_1|>
def _generate_examples(self, json_file_path, image_dir_path):
"""Generate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Food101:
"""Food-101 Images dataset."""
def _info(self):
"""Define Dataset Info."""
names_file = tfds.core.tfds_path(_LABELS_FNAME)
features_dict = {'image': tfds.features.Image(), 'label': tfds.features.ClassLabel(names_file=names_file)}
if self.version > '2.0.0':
... | the_stack_v2_python_sparse | tensorflow_datasets/image_classification/food101.py | tensorflow/datasets | train | 4,224 |
ca9dea3d3c0eba3e8403d17bc98621fac91824d5 | [
"super().__init__(layer_options, *args, **kwargs)\nif 'dropout_rate' in layer_options:\n self._dropout_rate = float(layer_options['dropout_rate'])\n self._dropout_rate = min(0.9999, self._dropout_rate)\nelse:\n self._dropout_rate = 0.5\nlogging.debug(' dropout_rate=%f', self._dropout_rate)\ninput_size = s... | <|body_start_0|>
super().__init__(layer_options, *args, **kwargs)
if 'dropout_rate' in layer_options:
self._dropout_rate = float(layer_options['dropout_rate'])
self._dropout_rate = min(0.9999, self._dropout_rate)
else:
self._dropout_rate = 0.5
logging.... | Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitting Journal of Machine Learning Research... | DropoutLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitt... | stack_v2_sparse_classes_36k_train_032894 | 2,727 | permissive | [
{
"docstring": "Validates the parameters of this layer.",
"name": "__init__",
"signature": "def __init__(self, layer_options, *args, **kwargs)"
},
{
"docstring": "Creates the symbolic graph of this layer. Sets ``self.output`` to a symbolic matrix that describes the output of this layer. During t... | 2 | stack_v2_sparse_classes_30k_train_007888 | Implement the Python class `DropoutLayer` described below.
Class description:
Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way t... | Implement the Python class `DropoutLayer` described below.
Class description:
Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way t... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitting Journal o... | the_stack_v2_python_sparse | theanolm/network/dropoutlayer.py | senarvi/theanolm | train | 95 |
c6cebaece7e95949133e1f3112a133f9cb7abcbc | [
"if not heights:\n return 0\nn = len(heights)\ncnt = [0] * 101\nfor h in heights:\n cnt[h] += 1\nline = []\nfor i in range(1, 101):\n line.extend([i] * cnt[i])\nres = 0\nfor i in range(n):\n if heights[i] != line[i]:\n res += 1\nreturn res",
"if not heights:\n return 0\ncnt = [0] * 101\nfor ... | <|body_start_0|>
if not heights:
return 0
n = len(heights)
cnt = [0] * 101
for h in heights:
cnt[h] += 1
line = []
for i in range(1, 101):
line.extend([i] * cnt[i])
res = 0
for i in range(n):
if heights[i] !=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def heightChecker1(self, heights: List[int]) -> int:
"""思路:计数排序 @param heights: @return:"""
<|body_0|>
def heightChecker2(self, heights: List[int]) -> int:
"""思路:不用新建line数组 @param heights: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_032895 | 2,301 | no_license | [
{
"docstring": "思路:计数排序 @param heights: @return:",
"name": "heightChecker1",
"signature": "def heightChecker1(self, heights: List[int]) -> int"
},
{
"docstring": "思路:不用新建line数组 @param heights: @return:",
"name": "heightChecker2",
"signature": "def heightChecker2(self, heights: List[int])... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def heightChecker1(self, heights: List[int]) -> int: 思路:计数排序 @param heights: @return:
- def heightChecker2(self, heights: List[int]) -> int: 思路:不用新建line数组 @param heights: @return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def heightChecker1(self, heights: List[int]) -> int: 思路:计数排序 @param heights: @return:
- def heightChecker2(self, heights: List[int]) -> int: 思路:不用新建line数组 @param heights: @return... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def heightChecker1(self, heights: List[int]) -> int:
"""思路:计数排序 @param heights: @return:"""
<|body_0|>
def heightChecker2(self, heights: List[int]) -> int:
"""思路:不用新建line数组 @param heights: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def heightChecker1(self, heights: List[int]) -> int:
"""思路:计数排序 @param heights: @return:"""
if not heights:
return 0
n = len(heights)
cnt = [0] * 101
for h in heights:
cnt[h] += 1
line = []
for i in range(1, 101):
... | the_stack_v2_python_sparse | LeetCode/排序算法(sort)/1051. 高度检查器.py | yiming1012/MyLeetCode | train | 2 | |
eed2bbbee19b54156cd53711d13af9e5329fe822 | [
"self.generate_short_description()\nif self.price is None:\n self.currency = None\nsuper(Offer, self).save(*args, **kwargs)\nself.generate_slug_and_permalink()\nsuper(Offer, self).save()",
"unique_title_es = '{slug}-{id}'.format(slug=self.title_es, id=self.id)\nunique_title_en = '{slug}-{id}'.format(slug=self.... | <|body_start_0|>
self.generate_short_description()
if self.price is None:
self.currency = None
super(Offer, self).save(*args, **kwargs)
self.generate_slug_and_permalink()
super(Offer, self).save()
<|end_body_0|>
<|body_start_1|>
unique_title_es = '{slug}-{id}... | Offer definition | Offer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
<|body_0|>
def generate_slug_and_permalink(self):
"""Generate a unique slug and unique permalink"""
<|body_1|>
def generate_short_description(self):
"""Generate... | stack_v2_sparse_classes_36k_train_032896 | 8,128 | no_license | [
{
"docstring": "Create Offer",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Generate a unique slug and unique permalink",
"name": "generate_slug_and_permalink",
"signature": "def generate_slug_and_permalink(self)"
},
{
"docstring": "Generate o... | 3 | stack_v2_sparse_classes_30k_train_011455 | Implement the Python class `Offer` described below.
Class description:
Offer definition
Method signatures and docstrings:
- def save(self, *args, **kwargs): Create Offer
- def generate_slug_and_permalink(self): Generate a unique slug and unique permalink
- def generate_short_description(self): Generate offer short_de... | Implement the Python class `Offer` described below.
Class description:
Offer definition
Method signatures and docstrings:
- def save(self, *args, **kwargs): Create Offer
- def generate_slug_and_permalink(self): Generate a unique slug and unique permalink
- def generate_short_description(self): Generate offer short_de... | 4dc6362ef624eb6591aad9d5c7de95eee40a01c9 | <|skeleton|>
class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
<|body_0|>
def generate_slug_and_permalink(self):
"""Generate a unique slug and unique permalink"""
<|body_1|>
def generate_short_description(self):
"""Generate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
self.generate_short_description()
if self.price is None:
self.currency = None
super(Offer, self).save(*args, **kwargs)
self.generate_slug_and_permalink()
super(Off... | the_stack_v2_python_sparse | app/offers/models.py | arielMilan1899/orbita-api | train | 0 |
b18736ac876a8e89366f5f07d55f9f8b1b3c6d19 | [
"validated_data = self.validated_data\nsync_task = NodeApi.sync_task_create(validated_data)\nreturn Response({'task_id': sync_task['task_id']})",
"validated_data = self.validated_data\ntask_status = NodeApi.sync_task_status(validated_data)\nresult = {'task_id': task_status['task_id'], 'status': task_status['statu... | <|body_start_0|>
validated_data = self.validated_data
sync_task = NodeApi.sync_task_create(validated_data)
return Response({'task_id': sync_task['task_id']})
<|end_body_0|>
<|body_start_1|>
validated_data = self.validated_data
task_status = NodeApi.sync_task_status(validated_dat... | SyncTaskViewSet | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncTaskViewSet:
def create_sync_task(self, request):
"""@api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task"""
<|body_0|>
def status(self, request):
"""@api {GET} /sync_task/status/ 查询同步任务状态 @apiName sync_task_status @apiGroup sync_ta... | stack_v2_sparse_classes_36k_train_032897 | 2,098 | permissive | [
{
"docstring": "@api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task",
"name": "create_sync_task",
"signature": "def create_sync_task(self, request)"
},
{
"docstring": "@api {GET} /sync_task/status/ 查询同步任务状态 @apiName sync_task_status @apiGroup sync_task",
"name... | 2 | null | Implement the Python class `SyncTaskViewSet` described below.
Class description:
Implement the SyncTaskViewSet class.
Method signatures and docstrings:
- def create_sync_task(self, request): @api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task
- def status(self, request): @api {GET} /sy... | Implement the Python class `SyncTaskViewSet` described below.
Class description:
Implement the SyncTaskViewSet class.
Method signatures and docstrings:
- def create_sync_task(self, request): @api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task
- def status(self, request): @api {GET} /sy... | 72d2104783443bff26c752c5bd934a013b302b6d | <|skeleton|>
class SyncTaskViewSet:
def create_sync_task(self, request):
"""@api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task"""
<|body_0|>
def status(self, request):
"""@api {GET} /sync_task/status/ 查询同步任务状态 @apiName sync_task_status @apiGroup sync_ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyncTaskViewSet:
def create_sync_task(self, request):
"""@api {POST} /sync_task/create/ 创建同步任务 @apiName sync_task_create @apiGroup sync_task"""
validated_data = self.validated_data
sync_task = NodeApi.sync_task_create(validated_data)
return Response({'task_id': sync_task['task_... | the_stack_v2_python_sparse | apps/node_man/views/sync_task.py | TencentBlueKing/bk-nodeman | train | 54 | |
a5c7fd15d448ce649314715547b3b1a028ace4d3 | [
"self._headers = headers.copy()\nself._name = name\nself._filename = filename\nself._body = body\nif self._filename is None:\n self._headers[Part.CONTENT_DISPOSITION] = 'form-data; name=\"%s\"' % self._name\n self._headers.setdefault(Part.CONTENT_TYPE, Part.DEFAULT_CONTENT_TYPE)\nelse:\n self._headers[Part... | <|body_start_0|>
self._headers = headers.copy()
self._name = name
self._filename = filename
self._body = body
if self._filename is None:
self._headers[Part.CONTENT_DISPOSITION] = 'form-data; name="%s"' % self._name
self._headers.setdefault(Part.CONTENT_TYP... | Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file. | Part | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Part:
"""Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file."""
def __init__(self, name, filename, body, headers):
"""Make a new part. The part will have the given headers added init... | stack_v2_sparse_classes_36k_train_032898 | 5,277 | permissive | [
{
"docstring": "Make a new part. The part will have the given headers added initially. @param name: The part name. @type name: str @param filename: If this is a file, the name of the file. Otherwise None. @type filename: str @param body: The body of the part. @type body: str @param headers: Additional headers, ... | 2 | stack_v2_sparse_classes_30k_val_001070 | Implement the Python class `Part` described below.
Class description:
Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file.
Method signatures and docstrings:
- def __init__(self, name, filename, body, headers): Make a ... | Implement the Python class `Part` described below.
Class description:
Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file.
Method signatures and docstrings:
- def __init__(self, name, filename, body, headers): Make a ... | 0b468bec744cc09a2c3f8d62e1d9f6e96e20ec35 | <|skeleton|>
class Part:
"""Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file."""
def __init__(self, name, filename, body, headers):
"""Make a new part. The part will have the given headers added init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Part:
"""Class holding a single part of the form. You should never need to use this class directly; instead, use the factory methods in Multipart: field and file."""
def __init__(self, name, filename, body, headers):
"""Make a new part. The part will have the given headers added initially. @param... | the_stack_v2_python_sparse | image_recognition_skybiometry/src/image_recognition_skybiometry/multipart.py | tue-robotics/image_recognition | train | 74 |
c5191b8059b81c1ff1e518c2a7b278c688be26da | [
"try:\n reply = self.get_reply(hotel, body)\nexcept ReplyNotFound:\n return\nelse:\n self.check_for_data_update(guest, reply)\n return reply",
"body = body.upper()\ntry:\n return self.get(hotel=hotel, letter=body)\nexcept Reply.DoesNotExist:\n try:\n return self.get(letter=body)\n exce... | <|body_start_0|>
try:
reply = self.get_reply(hotel, body)
except ReplyNotFound:
return
else:
self.check_for_data_update(guest, reply)
return reply
<|end_body_0|>
<|body_start_1|>
body = body.upper()
try:
return self.get... | ReplyManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplyManager:
def process_reply(self, guest, hotel, body):
"""Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes."""
<|body_0|>
def get_reply(self, hotel, body):
"""Resolve Reply in this order: - Hotel Reply - System Reply - no re... | stack_v2_sparse_classes_36k_train_032899 | 20,325 | no_license | [
{
"docstring": "Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes.",
"name": "process_reply",
"signature": "def process_reply(self, guest, hotel, body)"
},
{
"docstring": "Resolve Reply in this order: - Hotel Reply - System Reply - no reply",
"name": "ge... | 3 | stack_v2_sparse_classes_30k_train_002134 | Implement the Python class `ReplyManager` described below.
Class description:
Implement the ReplyManager class.
Method signatures and docstrings:
- def process_reply(self, guest, hotel, body): Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes.
- def get_reply(self, hotel, body): ... | Implement the Python class `ReplyManager` described below.
Class description:
Implement the ReplyManager class.
Method signatures and docstrings:
- def process_reply(self, guest, hotel, body): Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes.
- def get_reply(self, hotel, body): ... | 927519fec52f6df54d81e393597b55b3755103dd | <|skeleton|>
class ReplyManager:
def process_reply(self, guest, hotel, body):
"""Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes."""
<|body_0|>
def get_reply(self, hotel, body):
"""Resolve Reply in this order: - Hotel Reply - System Reply - no re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplyManager:
def process_reply(self, guest, hotel, body):
"""Check for an 'auto-reply'. If one exists, return it, and make an necessary data changes."""
try:
reply = self.get_reply(hotel, body)
except ReplyNotFound:
return
else:
self.check_f... | the_stack_v2_python_sparse | textress/concierge/models.py | aaronlelevier/textress_project | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.