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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a47911233f844849c984eb6c3d5768e95fc92b51 | [
"self.out_filters = out_filters\nself.strides = strides\nself.in_filters = None\nsuper(Upscore, self).__init__(name)",
"if self.in_filters is None:\n self.in_filters = x.get_shape().as_list()[-1]\nassert self.in_filters == x.get_shape().as_list()[-1], 'Module was initialised for a different input shape'\nif se... | <|body_start_0|>
self.out_filters = out_filters
self.strides = strides
self.in_filters = None
super(Upscore, self).__init__(name)
<|end_body_0|>
<|body_start_1|>
if self.in_filters is None:
self.in_filters = x.get_shape().as_list()[-1]
assert self.in_filters ... | Upscore module according to J. Long. | Upscore | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upscore:
"""Upscore module according to J. Long."""
def __init__(self, out_filters, strides, name='upscore'):
"""Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of t... | stack_v2_sparse_classes_36k_train_006500 | 11,734 | permissive | [
{
"docstring": "Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of the module",
"name": "__init__",
"signature": "def __init__(self, out_filters, strides, name='upscore')"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_016039 | Implement the Python class `Upscore` described below.
Class description:
Upscore module according to J. Long.
Method signatures and docstrings:
- def __init__(self, out_filters, strides, name='upscore'): Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tu... | Implement the Python class `Upscore` described below.
Class description:
Upscore module according to J. Long.
Method signatures and docstrings:
- def __init__(self, out_filters, strides, name='upscore'): Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tu... | 80d1a04dc163590aa44b62688b06aece78fb7fd6 | <|skeleton|>
class Upscore:
"""Upscore module according to J. Long."""
def __init__(self, out_filters, strides, name='upscore'):
"""Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Upscore:
"""Upscore module according to J. Long."""
def __init__(self, out_filters, strides, name='upscore'):
"""Constructs an Upscore module Parameters ---------- out_filters : int number of output filters strides : list or tuple strides to use for upsampling name : string name of the module"""
... | the_stack_v2_python_sparse | dltk/models/segmentation/deepmedic.py | pawni/DLTK-1 | train | 1 |
c5e0dad4cc0eed51beef649c18f3b2d6113f20b9 | [
"self.n_kernels = n_kernels\nself.n_strides = n_strides\nself.norm_type = normalization\nself.activation_type = activation\nself.filter_step = filter_step\nself.max_filter_size = max_filter_size\nself.init_kernel = tf.random_normal_initializer(0.0, 0.02)",
"activation = normalization_layer(self.norm_type)(input_t... | <|body_start_0|>
self.n_kernels = n_kernels
self.n_strides = n_strides
self.norm_type = normalization
self.activation_type = activation
self.filter_step = filter_step
self.max_filter_size = max_filter_size
self.init_kernel = tf.random_normal_initializer(0.0, 0.02)... | Class to build Residual blocks for the Encoder. | ResidualBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualBlock:
"""Class to build Residual blocks for the Encoder."""
def __init__(self, n_kernels, n_strides, activation, normalization, max_filter_size, filter_step=64):
"""Initialize the Residuel Blocks. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride s... | stack_v2_sparse_classes_36k_train_006501 | 11,636 | no_license | [
{
"docstring": "Initialize the Residuel Blocks. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activation (str): Type of activation layer to use. normalization (str): Type of normalization layer to use. max_filter_size (int): Maximum filter size. filter_step (int): Step size ... | 2 | stack_v2_sparse_classes_30k_train_012862 | Implement the Python class `ResidualBlock` described below.
Class description:
Class to build Residual blocks for the Encoder.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, activation, normalization, max_filter_size, filter_step=64): Initialize the Residuel Blocks. Args: n_kernels (int)... | Implement the Python class `ResidualBlock` described below.
Class description:
Class to build Residual blocks for the Encoder.
Method signatures and docstrings:
- def __init__(self, n_kernels, n_strides, activation, normalization, max_filter_size, filter_step=64): Initialize the Residuel Blocks. Args: n_kernels (int)... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class ResidualBlock:
"""Class to build Residual blocks for the Encoder."""
def __init__(self, n_kernels, n_strides, activation, normalization, max_filter_size, filter_step=64):
"""Initialize the Residuel Blocks. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualBlock:
"""Class to build Residual blocks for the Encoder."""
def __init__(self, n_kernels, n_strides, activation, normalization, max_filter_size, filter_step=64):
"""Initialize the Residuel Blocks. Args: n_kernels (int): Number of kernels for Conv2D. n_strides (int): Stride size. activati... | the_stack_v2_python_sparse | fmlwright/trainer/neural_networks/blocks.py | rgresia-umd/fml-wright | train | 0 |
a4159e952c777d4e53143b6d7862a1d51dbf7ed6 | [
"self.id = door_id\nself.rooms = []\nself.is_opened = False\nself.keys_to_open_this_door = {}\nself.is_visited = False",
"for key in list_of_keys:\n if key in self.keys_to_open_this_door:\n self.is_opened = True"
] | <|body_start_0|>
self.id = door_id
self.rooms = []
self.is_opened = False
self.keys_to_open_this_door = {}
self.is_visited = False
<|end_body_0|>
<|body_start_1|>
for key in list_of_keys:
if key in self.keys_to_open_this_door:
self.is_opened =... | Door | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Door:
def __init__(self, door_id):
""":param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitable for that door. That gives instant experience if you can open the door or no"""
<|bo... | stack_v2_sparse_classes_36k_train_006502 | 8,395 | no_license | [
{
"docstring": ":param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitable for that door. That gives instant experience if you can open the door or no",
"name": "__init__",
"signature": "def __init__(self... | 2 | stack_v2_sparse_classes_30k_train_017253 | Implement the Python class `Door` described below.
Class description:
Implement the Door class.
Method signatures and docstrings:
- def __init__(self, door_id): :param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitabl... | Implement the Python class `Door` described below.
Class description:
Implement the Door class.
Method signatures and docstrings:
- def __init__(self, door_id): :param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitabl... | 636b1f6b0ab28c6eef8f8900e68393f7b1fb931a | <|skeleton|>
class Door:
def __init__(self, door_id):
""":param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitable for that door. That gives instant experience if you can open the door or no"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Door:
def __init__(self, door_id):
""":param door_id: door id as its identity Regarding keys_to_open_this_door: The logic - when we insert key, we can immediately find out, if this key is suitable for that door. That gives instant experience if you can open the door or no"""
self.id = door_id
... | the_stack_v2_python_sparse | Graph/Labyrinth And Treasure.py | kotsky/programming-exercises | train | 0 | |
2b8bdcd46f7909d32358a40057f236bd3520e852 | [
"self.certfile = filename\nwith open(self.certfile) as file:\n self.der = ssl.PEM_cert_to_DER_cert(file.read())",
"i = asn1_node_root(self.der)\ni = asn1_node_first_child(self.der, i)\ni = asn1_node_first_child(self.der, i)\ni = asn1_node_next(self.der, i)\ni = asn1_node_next(self.der, i)\ni = asn1_node_next(s... | <|body_start_0|>
self.certfile = filename
with open(self.certfile) as file:
self.der = ssl.PEM_cert_to_DER_cert(file.read())
<|end_body_0|>
<|body_start_1|>
i = asn1_node_root(self.der)
i = asn1_node_first_child(self.der, i)
i = asn1_node_first_child(self.der, i)
... | A simple class to represent a X509 certificate. The certificate is encoding according the DER format. | X509 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
<|body_0|>
def check_validity_period(self):
"""Control the validity period. Raise an e... | stack_v2_sparse_classes_36k_train_006503 | 5,920 | permissive | [
{
"docstring": "Initialize the X509 object",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Control the validity period. Raise an exception if the control fails.",
"name": "check_validity_period",
"signature": "def check_validity_period(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017027 | Implement the Python class `X509` described below.
Class description:
A simple class to represent a X509 certificate. The certificate is encoding according the DER format.
Method signatures and docstrings:
- def __init__(self, filename): Initialize the X509 object
- def check_validity_period(self): Control the validi... | Implement the Python class `X509` described below.
Class description:
A simple class to represent a X509 certificate. The certificate is encoding according the DER format.
Method signatures and docstrings:
- def __init__(self, filename): Initialize the X509 object
- def check_validity_period(self): Control the validi... | e3957e8f5b0ed9908e62badacace7e581761dd96 | <|skeleton|>
class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
<|body_0|>
def check_validity_period(self):
"""Control the validity period. Raise an e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class X509:
"""A simple class to represent a X509 certificate. The certificate is encoding according the DER format."""
def __init__(self, filename):
"""Initialize the X509 object"""
self.certfile = filename
with open(self.certfile) as file:
self.der = ssl.PEM_cert_to_DER_ce... | the_stack_v2_python_sparse | mnemopwd/common/util/X509.py | thethythy/Mnemopwd | train | 3 |
dccb9a58a5fdd6a5cd902f44ed7b9dcc6fa92218 | [
"self.access_key = access_key\nself.s3_config = s3_config\nself.secret_key = secret_key",
"if dictionary is None:\n return None\naccess_key = dictionary.get('accessKey')\ns3_config = cohesity_management_sdk.models.s3_bucket_config_proto.S3BucketConfigProto.from_dictionary(dictionary.get('s3Config')) if diction... | <|body_start_0|>
self.access_key = access_key
self.s3_config = s3_config
self.secret_key = secret_key
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
access_key = dictionary.get('accessKey')
s3_config = cohesity_management_sdk.models.s3_buc... | Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to UDA for doing all s3 communications. s3_co... | UdaS3ViewBackupProperties | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UdaS3ViewBackupProperties:
"""Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be... | stack_v2_sparse_classes_36k_train_006504 | 2,459 | permissive | [
{
"docstring": "Constructor for the UdaS3ViewBackupProperties class",
"name": "__init__",
"signature": "def __init__(self, access_key=None, s3_config=None, secret_key=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represe... | 2 | null | Implement the Python class `UdaS3ViewBackupProperties` described below.
Class description:
Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the ... | Implement the Python class `UdaS3ViewBackupProperties` described below.
Class description:
Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UdaS3ViewBackupProperties:
"""Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UdaS3ViewBackupProperties:
"""Implementation of the 'UdaS3ViewBackupProperties' model. // ----------------------------------------------------------------------------- Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to UD... | the_stack_v2_python_sparse | cohesity_management_sdk/models/uda_s3_view_backup_properties.py | cohesity/management-sdk-python | train | 24 |
cd546587a5335ddbe39bbdd1a8a7bb914f85dea8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessPackage()",
"from .access_package_assignment_policy import AccessPackageAssignmentPolicy\nfrom .access_package_catalog import AccessPackageCatalog\nfrom .access_package_resource_role_scope import AccessPackageResourceRoleScope\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessPackage()
<|end_body_0|>
<|body_start_1|>
from .access_package_assignment_policy import AccessPackageAssignmentPolicy
from .access_package_catalog import AccessPackageCatalog
... | AccessPackage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPackage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackage:
"""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... | stack_v2_sparse_classes_36k_train_006505 | 6,428 | 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: AccessPackage",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_014672 | Implement the Python class `AccessPackage` described below.
Class description:
Implement the AccessPackage class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackage: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `AccessPackage` described below.
Class description:
Implement the AccessPackage class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackage: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessPackage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackage:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessPackage:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackage:
"""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: AccessPackag... | the_stack_v2_python_sparse | msgraph/generated/models/access_package.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
12966f92699ae5857ab02cbab03d7b4e078803e3 | [
"self.dmax = dmax\ndist, order = torch.sort(dist, dim=1)\nself.order = order\ndmax_vec = dmax * torch.ones(dist.shape[0], 1)\noff_one = torch.cat((dist[:, 1:], dmax_vec), dim=1)\nself.m = dist - off_one\nself.temp = temp\nself.hardmax = hardmax",
"x_sort = x[self.order]\nprobs = 1 - torch.cumprod(1 - x_sort, dim=... | <|body_start_0|>
self.dmax = dmax
dist, order = torch.sort(dist, dim=1)
self.order = order
dmax_vec = dmax * torch.ones(dist.shape[0], 1)
off_one = torch.cat((dist[:, 1:], dmax_vec), dim=1)
self.m = dist - off_one
self.temp = temp
self.hardmax = hardmax
<|... | CenterObjective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_006506 | 4,317 | permissive | [
{
"docstring": "dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers",
"name": "__init__",
"signature": "def __init__(self, dist, dmax, temp, hardmax=False)"
},
... | 2 | stack_v2_sparse_classes_30k_train_020139 | Implement the Python class `CenterObjective` described below.
Class description:
Implement the CenterObjective class.
Method signatures and docstrings:
- def __init__(self, dist, dmax, temp, hardmax=False): dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g... | Implement the Python class `CenterObjective` described below.
Class description:
Implement the CenterObjective class.
Method signatures and docstrings:
- def __init__(self, dist, dmax, temp, hardmax=False): dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g... | 911c90da4b2761678582108e6b7875a8aedce8ac | <|skeleton|>
class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CenterObjective:
def __init__(self, dist, dmax, temp, hardmax=False):
"""dist: (num customers) * (num locations) matrix dmax: maximum distance that can be suffered by any customer (e.g., if no facilities are chosen) temp: how hard to make the softmax over customers"""
self.dmax = dmax
... | the_stack_v2_python_sparse | kcenter.py | yuvalsimon/clusternet | train | 0 | |
879632dab31a02b73b45bdf9cbedc164388ea1a1 | [
"email = self.cleaned_data.get('email')\nif not email:\n raise forms.ValidationError(u'Email address must be included.')\nusername = self.cleaned_data.get('username')\nif User.objects.filter(email=email).exclude(username=username):\n raise forms.ValidationError(u'Email addresses must be unique.')\nreturn emai... | <|body_start_0|>
email = self.cleaned_data.get('email')
if not email:
raise forms.ValidationError(u'Email address must be included.')
username = self.cleaned_data.get('username')
if User.objects.filter(email=email).exclude(username=username):
raise forms.Validatio... | reisters user and is used to create new profile | UserRegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationForm:
"""reisters user and is used to create new profile"""
def clean_email(self):
"""checks for user of same address and raises error. Also ensure the fields have content in them."""
<|body_0|>
def clean_password2(self):
"""Compares passwords and... | stack_v2_sparse_classes_36k_train_006507 | 2,625 | no_license | [
{
"docstring": "checks for user of same address and raises error. Also ensure the fields have content in them.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Compares passwords and raises error if they are not matching",
"name": "clean_password2",
"signa... | 2 | stack_v2_sparse_classes_30k_train_004328 | Implement the Python class `UserRegistrationForm` described below.
Class description:
reisters user and is used to create new profile
Method signatures and docstrings:
- def clean_email(self): checks for user of same address and raises error. Also ensure the fields have content in them.
- def clean_password2(self): C... | Implement the Python class `UserRegistrationForm` described below.
Class description:
reisters user and is used to create new profile
Method signatures and docstrings:
- def clean_email(self): checks for user of same address and raises error. Also ensure the fields have content in them.
- def clean_password2(self): C... | 07445ddd12738a7e0bbc293619f92610d2df0c5e | <|skeleton|>
class UserRegistrationForm:
"""reisters user and is used to create new profile"""
def clean_email(self):
"""checks for user of same address and raises error. Also ensure the fields have content in them."""
<|body_0|>
def clean_password2(self):
"""Compares passwords and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRegistrationForm:
"""reisters user and is used to create new profile"""
def clean_email(self):
"""checks for user of same address and raises error. Also ensure the fields have content in them."""
email = self.cleaned_data.get('email')
if not email:
raise forms.Vali... | the_stack_v2_python_sparse | accounts/forms.py | brianscan14/XYfitness | train | 1 |
0a8ce45788453528e39b4050eb19686688584ae1 | [
"self._capacity = capacity\nself._hash = {}\nself._head = self.CacheObj(None, None)\nself._tail = self.CacheObj(None, None)\nself._head.next = self._tail\nself._tail.prev = self._head",
"if key not in self._hash:\n return -1\ncache_obj = self._hash[key]\ncache_obj.prev.next = cache_obj.next\ncache_obj.next.pre... | <|body_start_0|>
self._capacity = capacity
self._hash = {}
self._head = self.CacheObj(None, None)
self._tail = self.CacheObj(None, None)
self._head.next = self._tail
self._tail.prev = self._head
<|end_body_0|>
<|body_start_1|>
if key not in self._hash:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_006508 | 2,032 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 33b6b68a8136109d2aaa26bb8bf9e873f995d5ab | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self._capacity = capacity
self._hash = {}
self._head = self.CacheObj(None, None)
self._tail = self.CacheObj(None, None)
self._head.next = self._tail
self._tail.prev = self._head
def g... | the_stack_v2_python_sparse | python2/l0146_lru_cache.py | sprax/1337 | train | 0 | |
3563d01ecfe238a029ec2cd878deb16e4cde0cb3 | [
"details = encoding.force_text(details)\nbody = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}\nreturn self._create('/os-systemlogs', body, 'systemlog')",
"if filters:\n url = '/os-systemlogs?filters=%s' % filters\nelse:\n url = '/os-systemlogs'\nLOG.info... | <|body_start_0|>
details = encoding.force_text(details)
body = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}
return self._create('/os-systemlogs', body, 'systemlog')
<|end_body_0|>
<|body_start_1|>
if filters:
url = '/os-... | SystemlogManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
<|body_0|>
def list(self, filters=None):
"""Get list of system logs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
details = encoding.force_text(de... | stack_v2_sparse_classes_36k_train_006509 | 995 | permissive | [
{
"docstring": "Create action logs.",
"name": "create",
"signature": "def create(self, name, event_subject, result, details)"
},
{
"docstring": "Get list of system logs.",
"name": "list",
"signature": "def list(self, filters=None)"
}
] | 2 | null | Implement the Python class `SystemlogManager` described below.
Class description:
Implement the SystemlogManager class.
Method signatures and docstrings:
- def create(self, name, event_subject, result, details): Create action logs.
- def list(self, filters=None): Get list of system logs. | Implement the Python class `SystemlogManager` described below.
Class description:
Implement the SystemlogManager class.
Method signatures and docstrings:
- def create(self, name, event_subject, result, details): Create action logs.
- def list(self, filters=None): Get list of system logs.
<|skeleton|>
class Systemlog... | 54e45b2daa205132c05b0ff5a2c3db7fca2853a7 | <|skeleton|>
class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
<|body_0|>
def list(self, filters=None):
"""Get list of system logs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
details = encoding.force_text(details)
body = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}
return self._create('/os-systeml... | the_stack_v2_python_sparse | novaclient/v2/systemlogs.py | xuweiliang/Codelibrary | train | 0 | |
f8aa5b3b0b72ba967e03b6132f872fdfeda5aeaa | [
"logger.info('BS-Seeker FilterReads wrapper')\nTool.__init__(self)\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)",
"command_line = ('python ' + os.path.join(bss_path, 'FilterReads.py') + ' -i ' + infile + ' -o ' + outfile + '.tmp').format()\nlogger.info(command_line)... | <|body_start_0|>
logger.info('BS-Seeker FilterReads wrapper')
Tool.__init__(self)
if configuration is None:
configuration = {}
self.configuration.update(configuration)
<|end_body_0|>
<|body_start_1|>
command_line = ('python ' + os.path.join(bss_path, 'FilterReads.py'... | Script from BS-Seeker2 for filtering FASTQ files to remove repeats | filterReadsTool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class filterReadsTool:
"""Script from BS-Seeker2 for filtering FASTQ files to remove repeats"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation... | stack_v2_sparse_classes_36k_train_006510 | 5,136 | permissive | [
{
"docstring": "Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.",
"name": "__init__",
"signature": "def __init__(self, configuration=None)"
},... | 3 | stack_v2_sparse_classes_30k_train_001591 | Implement the Python class `filterReadsTool` described below.
Class description:
Script from BS-Seeker2 for filtering FASTQ files to remove repeats
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dicti... | Implement the Python class `filterReadsTool` described below.
Class description:
Script from BS-Seeker2 for filtering FASTQ files to remove repeats
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dicti... | 50c7115c0c1a6af48dc34f275e469d1b9eb02999 | <|skeleton|>
class filterReadsTool:
"""Script from BS-Seeker2 for filtering FASTQ files to remove repeats"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class filterReadsTool:
"""Script from BS-Seeker2 for filtering FASTQ files to remove repeats"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be ca... | the_stack_v2_python_sparse | tool/bs_seeker_filter.py | Multiscale-Genomics/mg-process-fastq | train | 2 |
1fa29a1c7b0f32a23a98940da7bc7c58fc5a0ab6 | [
"def build(nums, current):\n if not nums:\n output.append(list(current))\n return\n for i, n in enumerate(nums):\n current.append(n)\n build(nums[:i] + nums[i + 1:], current)\n current.pop()\noutput = []\nbuild(nums, [])\nreturn output",
"output = [[]]\nfor n in nums:\n ... | <|body_start_0|>
def build(nums, current):
if not nums:
output.append(list(current))
return
for i, n in enumerate(nums):
current.append(n)
build(nums[:i] + nums[i + 1:], current)
current.pop()
output ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_iterative(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def permute_recursive(self, nums):
""":type nums: ... | stack_v2_sparse_classes_36k_train_006511 | 2,697 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute_iterative",
"signature": "def permute_iterative(self, nums)"
},
{
"docstri... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_iterative(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_recursive(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_iterative(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_recursive(... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_iterative(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def permute_recursive(self, nums):
""":type nums: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
def build(nums, current):
if not nums:
output.append(list(current))
return
for i, n in enumerate(nums):
current.append(n)
... | the_stack_v2_python_sparse | src/lt_46.py | oxhead/CodingYourWay | train | 0 | |
dd6f9ffc3e6faf583bb2d8b006d6240d99d02bd9 | [
"sum_1 = 0\nresult = 0\nself.dict = {0: 1}\nfor i, num in enumerate(nums):\n sum_1 += num\n if sum_1 - k in self.dict.keys():\n result += self.dict[sum_1 - k]\n if sum_1 not in self.dict.keys():\n self.dict[sum_1] = 0\n self.dict[sum_1] += 1\nprint(self.dict)\nreturn result",
"import col... | <|body_start_0|>
sum_1 = 0
result = 0
self.dict = {0: 1}
for i, num in enumerate(nums):
sum_1 += num
if sum_1 - k in self.dict.keys():
result += self.dict[sum_1 - k]
if sum_1 not in self.dict.keys():
self.dict[sum_1] = 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum_1(self, A, K):
""":type nums: List[int] :type k: int :rtype: int 122MS"""
<|body_1|>
def subarraySum_2(self, nums, k):
""":t... | stack_v2_sparse_classes_36k_train_006512 | 2,347 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySum",
"signature": "def subarraySum(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int 122MS",
"name": "subarraySum_1",
"signature": "def subarraySum_1(self, A, K)"
},
{
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum_1(self, A, K): :type nums: List[int] :type k: int :rtype: int 122MS
- def subarra... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum_1(self, A, K): :type nums: List[int] :type k: int :rtype: int 122MS
- def subarra... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum_1(self, A, K):
""":type nums: List[int] :type k: int :rtype: int 122MS"""
<|body_1|>
def subarraySum_2(self, nums, k):
""":t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
sum_1 = 0
result = 0
self.dict = {0: 1}
for i, num in enumerate(nums):
sum_1 += num
if sum_1 - k in self.dict.keys():
result += self.di... | the_stack_v2_python_sparse | SubarraySumEqualsK_MID_560.py | 953250587/leetcode-python | train | 2 | |
051d98d928b1727f5ae46206de978dc480ffa208 | [
"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 Bidding Strategy service. Service to manage bidding strategies. | BiddingStrategyServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
<|body_0|>
def MutateBiddingStrate... | stack_v2_sparse_classes_36k_train_006513 | 3,550 | permissive | [
{
"docstring": "Returns the requested bidding strategy in full detail.",
"name": "GetBiddingStrategy",
"signature": "def GetBiddingStrategy(self, request, context)"
},
{
"docstring": "Creates, updates, or removes bidding strategies. Operation statuses are returned.",
"name": "MutateBiddingSt... | 2 | stack_v2_sparse_classes_30k_train_016677 | Implement the Python class `BiddingStrategyServiceServicer` described below.
Class description:
Proto file describing the Bidding Strategy service. Service to manage bidding strategies.
Method signatures and docstrings:
- def GetBiddingStrategy(self, request, context): Returns the requested bidding strategy in full d... | Implement the Python class `BiddingStrategyServiceServicer` described below.
Class description:
Proto file describing the Bidding Strategy service. Service to manage bidding strategies.
Method signatures and docstrings:
- def GetBiddingStrategy(self, request, context): Returns the requested bidding strategy in full d... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
<|body_0|>
def MutateBiddingStrate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/bidding_strategy_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
71228cb51ffbf75347fdee282d89cf5cdce688fe | [
"try:\n module_ = __import__(module_name)\nexcept ImportError as error:\n raise Exception(f'Cannot import module: {error.name}. Check sys.path')\nderived_types: Set[Type[T]] = set()\npackages = list(pkgutil.walk_packages(path=module_.__path__, prefix=module_.__name__ + '.'))\nmodules = [x for x in packages if... | <|body_start_0|>
try:
module_ = __import__(module_name)
except ImportError as error:
raise Exception(f'Cannot import module: {error.name}. Check sys.path')
derived_types: Set[Type[T]] = set()
packages = list(pkgutil.walk_packages(path=module_.__path__, prefix=modu... | Contains reflection based helper static methods. | ClassInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassInfo:
"""Contains reflection based helper static methods."""
def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]:
"""Extract all derived classes from specified module."""
<|body_0|>
def get_type(name: str) -> type:
"""Returns data der... | stack_v2_sparse_classes_36k_train_006514 | 5,944 | permissive | [
{
"docstring": "Extract all derived classes from specified module.",
"name": "get_derived_types",
"signature": "def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]"
},
{
"docstring": "Returns data derived type given its name.",
"name": "get_type",
"signature": "de... | 5 | null | Implement the Python class `ClassInfo` described below.
Class description:
Contains reflection based helper static methods.
Method signatures and docstrings:
- def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]: Extract all derived classes from specified module.
- def get_type(name: str) -> t... | Implement the Python class `ClassInfo` described below.
Class description:
Contains reflection based helper static methods.
Method signatures and docstrings:
- def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]: Extract all derived classes from specified module.
- def get_type(name: str) -> t... | 40113ddfb68e62d98b880b3c7427db5cc9fbd8cd | <|skeleton|>
class ClassInfo:
"""Contains reflection based helper static methods."""
def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]:
"""Extract all derived classes from specified module."""
<|body_0|>
def get_type(name: str) -> type:
"""Returns data der... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassInfo:
"""Contains reflection based helper static methods."""
def get_derived_types(module_name: str, base_type: Type[T]) -> Set[Type[T]]:
"""Extract all derived classes from specified module."""
try:
module_ = __import__(module_name)
except ImportError as error:
... | the_stack_v2_python_sparse | py/datacentric/storage/class_info.py | datacentricorg/datacentric-py | train | 1 |
a3ac01b465bcaf541c7789b907369192bae807dd | [
"wm = context.window_manager\nvrs_session = session.VerseSession.instance()\nuser_item = wm.verse_users[wm.cur_verse_user_index]\nuser_id = user_item.node_id\nobj_node = vrs_session.nodes[context.active_object.verse_node_id]\nvrs_session.send_node_perm(obj_node.prio, obj_node.id, user_id, vrs.PERM_NODE_WRITE | vrs.... | <|body_start_0|>
wm = context.window_manager
vrs_session = session.VerseSession.instance()
user_item = wm.verse_users[wm.cur_verse_user_index]
user_id = user_item.node_id
obj_node = vrs_session.nodes[context.active_object.verse_node_id]
vrs_session.send_node_perm(obj_node... | This operator tries to subscribe to Blender Mesh object at Verse server. | VerseObjectOtAddWritePerm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerseObjectOtAddWritePerm:
"""This operator tries to subscribe to Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
<|body_0|>
def poll(cls, context):
"... | stack_v2_sparse_classes_36k_train_006515 | 18,592 | no_license | [
{
"docstring": "This method will try to create new node representing Mesh Object at Verse server",
"name": "invoke",
"signature": "def invoke(self, context, event)"
},
{
"docstring": "This class method is used, when Blender check, if this operator can be executed",
"name": "poll",
"signa... | 2 | null | Implement the Python class `VerseObjectOtAddWritePerm` described below.
Class description:
This operator tries to subscribe to Blender Mesh object at Verse server.
Method signatures and docstrings:
- def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server
- d... | Implement the Python class `VerseObjectOtAddWritePerm` described below.
Class description:
This operator tries to subscribe to Blender Mesh object at Verse server.
Method signatures and docstrings:
- def invoke(self, context, event): This method will try to create new node representing Mesh Object at Verse server
- d... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class VerseObjectOtAddWritePerm:
"""This operator tries to subscribe to Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
<|body_0|>
def poll(cls, context):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerseObjectOtAddWritePerm:
"""This operator tries to subscribe to Blender Mesh object at Verse server."""
def invoke(self, context, event):
"""This method will try to create new node representing Mesh Object at Verse server"""
wm = context.window_manager
vrs_session = session.Vers... | the_stack_v2_python_sparse | All_In_One/addons/io_verse/ui_object3d.py | 2434325680/Learnbgame | train | 0 |
25f270f640e3e584c90da6cdc143480c60e589af | [
"asyncore.dispatcher.__init__(self)\nself.create_socket(socket.AF_INET, socket.SOCK_STREAM)\nself.set_reuse_addr()\nself.bind((host, port))\nself.listen(1)",
"pair = self.accept()\nif pair is not None:\n sock, addr = pair\n RPCHandle(sock, addr)",
"for i in range(n):\n pid = os.fork()\n if pid < 0:\... | <|body_start_0|>
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(1)
<|end_body_0|>
<|body_start_1|>
pair = self.accept()
if pair is not None:
sock, add... | RPCServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPCServer:
def __init__(self, host, port):
"""初始化server"""
<|body_0|>
def handle_accept(self):
"""处理连接"""
<|body_1|>
def prefork(self, n=10):
"""开启多进程"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
asyncore.dispatcher.__init__(... | stack_v2_sparse_classes_36k_train_006516 | 11,496 | no_license | [
{
"docstring": "初始化server",
"name": "__init__",
"signature": "def __init__(self, host, port)"
},
{
"docstring": "处理连接",
"name": "handle_accept",
"signature": "def handle_accept(self)"
},
{
"docstring": "开启多进程",
"name": "prefork",
"signature": "def prefork(self, n=10)"
}... | 3 | stack_v2_sparse_classes_30k_train_004059 | Implement the Python class `RPCServer` described below.
Class description:
Implement the RPCServer class.
Method signatures and docstrings:
- def __init__(self, host, port): 初始化server
- def handle_accept(self): 处理连接
- def prefork(self, n=10): 开启多进程 | Implement the Python class `RPCServer` described below.
Class description:
Implement the RPCServer class.
Method signatures and docstrings:
- def __init__(self, host, port): 初始化server
- def handle_accept(self): 处理连接
- def prefork(self, n=10): 开启多进程
<|skeleton|>
class RPCServer:
def __init__(self, host, port):
... | 3b16cf261b153ef9525fff592a34e8c5bd842f80 | <|skeleton|>
class RPCServer:
def __init__(self, host, port):
"""初始化server"""
<|body_0|>
def handle_accept(self):
"""处理连接"""
<|body_1|>
def prefork(self, n=10):
"""开启多进程"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPCServer:
def __init__(self, host, port):
"""初始化server"""
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(1)
def handle_accept(self):
"""处理连接"""
... | the_stack_v2_python_sparse | rpc_server.py | Jevade/python_script | train | 0 | |
a81894aa13b4d08edf7e2cffb4e8bb961adf1a91 | [
"self.optimizer = optimizer\nself.last_epoch = last_epoch\nself.scale = scale\nself.init_call = True\nsuper(LRScheduler, self).__init__(self.optimizer)",
"if self.init_call:\n self.init_call = False\n return [group['lr'] for group in self.optimizer.param_groups]\nlr = [group['lr'] * self.scale for group in ... | <|body_start_0|>
self.optimizer = optimizer
self.last_epoch = last_epoch
self.scale = scale
self.init_call = True
super(LRScheduler, self).__init__(self.optimizer)
<|end_body_0|>
<|body_start_1|>
if self.init_call:
self.init_call = False
return [g... | Scales the LR of a given factor every new metric update cycle | LRScheduler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRScheduler:
"""Scales the LR of a given factor every new metric update cycle"""
def __init__(self, optimizer, scale, last_epoch=0):
"""The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scale: The scaling factor :param last_epoch: The last epoch""... | stack_v2_sparse_classes_36k_train_006517 | 7,626 | no_license | [
{
"docstring": "The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scale: The scaling factor :param last_epoch: The last epoch",
"name": "__init__",
"signature": "def __init__(self, optimizer, scale, last_epoch=0)"
},
{
"docstring": "Get current LR :return: LR... | 2 | stack_v2_sparse_classes_30k_test_000908 | Implement the Python class `LRScheduler` described below.
Class description:
Scales the LR of a given factor every new metric update cycle
Method signatures and docstrings:
- def __init__(self, optimizer, scale, last_epoch=0): The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scal... | Implement the Python class `LRScheduler` described below.
Class description:
Scales the LR of a given factor every new metric update cycle
Method signatures and docstrings:
- def __init__(self, optimizer, scale, last_epoch=0): The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scal... | e50a0fbb346efe9866ee259fa3f96611fe1730f7 | <|skeleton|>
class LRScheduler:
"""Scales the LR of a given factor every new metric update cycle"""
def __init__(self, optimizer, scale, last_epoch=0):
"""The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scale: The scaling factor :param last_epoch: The last epoch""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRScheduler:
"""Scales the LR of a given factor every new metric update cycle"""
def __init__(self, optimizer, scale, last_epoch=0):
"""The LR scheduler for the LR of the nets :param optimizer: Optimizer of the nets :param scale: The scaling factor :param last_epoch: The last epoch"""
sel... | the_stack_v2_python_sparse | core/utils/utils.py | standardgalactic/taxons | train | 0 |
0b69e1c98d2ab57b44a3c5e019f41c3f7aebba3f | [
"super().__init__()\nself.mem_length = 1\nself.grudged = False\nself.grudge_memory = 1",
"if self.grudge_memory >= self.mem_length:\n self.grudge_memory = 0\n self.grudged = False\nif self.grudged:\n self.grudge_memory += 1\n return D\nelif D in opponent.history[-1:]:\n self.mem_length = opponent.d... | <|body_start_0|>
super().__init__()
self.mem_length = 1
self.grudged = False
self.grudge_memory = 1
<|end_body_0|>
<|body_start_1|>
if self.grudge_memory >= self.mem_length:
self.grudge_memory = 0
self.grudged = False
if self.grudged:
... | A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for playing D too often. Names: - Punisher: Original name by Geraint Palmer | Punisher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for playing D too often. Names: - Punisher: ... | stack_v2_sparse_classes_36k_train_006518 | 5,234 | permissive | [
{
"docstring": "Initialised the player",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Begins by playing C, then plays D for an amount of rounds proportional to the opponents historical '%' of playing D if the opponent ever plays D",
"name": "strategy",
... | 2 | stack_v2_sparse_classes_30k_train_001997 | Implement the Python class `Punisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for p... | Implement the Python class `Punisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for p... | fa748627cd4f0333bb2dbfcb1454372a78a9098a | <|skeleton|>
class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for playing D too often. Names: - Punisher: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played D, punishing that player for playing D too often. Names: - Punisher: Original name... | the_stack_v2_python_sparse | axelrod/strategies/punisher.py | Axelrod-Python/Axelrod | train | 673 |
33dc600db7ce92a78687b57bd2c3f663e13e6f8d | [
"handel_credit = public.CreditInquiry()\ninquiry_credit = handel_credit.save_to_mongoDB()\nif inquiry_credit:\n public.log_record('查询征信响应数据:', sys._getframe().f_lineno, inquiry_credit)\n self.assertEqual(str(inquiry_credit['code']), '0', '查询征信')\nelse:\n public.log_record('查询征信失败响应数据:', sys._getframe().f_l... | <|body_start_0|>
handel_credit = public.CreditInquiry()
inquiry_credit = handel_credit.save_to_mongoDB()
if inquiry_credit:
public.log_record('查询征信响应数据:', sys._getframe().f_lineno, inquiry_credit)
self.assertEqual(str(inquiry_credit['code']), '0', '查询征信')
else:
... | 征信查询 | CreditInquiry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditInquiry:
"""征信查询"""
def test_inquiry_credit(self):
"""查询征信报告"""
<|body_0|>
def test_fetch_credit_result(self):
"""查询征信结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
handel_credit = public.CreditInquiry()
inquiry_credit = handel... | stack_v2_sparse_classes_36k_train_006519 | 1,468 | permissive | [
{
"docstring": "查询征信报告",
"name": "test_inquiry_credit",
"signature": "def test_inquiry_credit(self)"
},
{
"docstring": "查询征信结果",
"name": "test_fetch_credit_result",
"signature": "def test_fetch_credit_result(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001115 | Implement the Python class `CreditInquiry` described below.
Class description:
征信查询
Method signatures and docstrings:
- def test_inquiry_credit(self): 查询征信报告
- def test_fetch_credit_result(self): 查询征信结果 | Implement the Python class `CreditInquiry` described below.
Class description:
征信查询
Method signatures and docstrings:
- def test_inquiry_credit(self): 查询征信报告
- def test_fetch_credit_result(self): 查询征信结果
<|skeleton|>
class CreditInquiry:
"""征信查询"""
def test_inquiry_credit(self):
"""查询征信报告"""
... | 8ed6723cab1f54f2ff8ea0947c6f982aef7e1b47 | <|skeleton|>
class CreditInquiry:
"""征信查询"""
def test_inquiry_credit(self):
"""查询征信报告"""
<|body_0|>
def test_fetch_credit_result(self):
"""查询征信结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreditInquiry:
"""征信查询"""
def test_inquiry_credit(self):
"""查询征信报告"""
handel_credit = public.CreditInquiry()
inquiry_credit = handel_credit.save_to_mongoDB()
if inquiry_credit:
public.log_record('查询征信响应数据:', sys._getframe().f_lineno, inquiry_credit)
... | the_stack_v2_python_sparse | auto/wpt_interface_test/case_suite/credit_inquiry.py | Strugglingrookie/oldboy2 | train | 1 |
e765dbc8566b91dcfbd1d8c31f363166d2b0c599 | [
"self.dev = dev\nself.metadata = metadata\nself.fs_type = get_filesystem_type(fs_stream)\nif self.fs_type == 'FAT':\n self.metadata.set_module('fat-bad-cluster')\n self.fs = FATBadCluster(fs_stream)\nelif self.fs_type == 'NTFS':\n self.metadata.set_module('ntfs-bad-cluster')\n self.fs = NTFSBadCluster(d... | <|body_start_0|>
self.dev = dev
self.metadata = metadata
self.fs_type = get_filesystem_type(fs_stream)
if self.fs_type == 'FAT':
self.metadata.set_module('fat-bad-cluster')
self.fs = FATBadCluster(fs_stream)
elif self.fs_type == 'NTFS':
self.me... | This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to read something from slack to stdout: >>> fs.read(... | BadClusterWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadClusterWrapper:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to read... | stack_v2_sparse_classes_36k_train_006520 | 5,056 | permissive | [
{
"docstring": ":param fs_stream: Stream of filesystem :param metadata: Metadata object",
"name": "__init__",
"signature": "def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None)"
},
{
"docstring": "writes data from instream into bad cluster. Metadata of this file will be... | 5 | stack_v2_sparse_classes_30k_train_019089 | Implement the Python class `BadClusterWrapper` described below.
Class description:
This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>... | Implement the Python class `BadClusterWrapper` described below.
Class description:
This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>... | b602e90ddecb8e469a28e092da3ca7fec514e3dc | <|skeleton|>
class BadClusterWrapper:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to read... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BadClusterWrapper:
"""This class wrapps the filesystem specific file cluster allocation implementations usage examples: >>> f = open('/dev/sdb1', 'rb+') >>> fs = BadClusterWrapper(f) >>> m = Metadata("BadCluster") to write something from stdin into slack: >>> fs.write(sys.stdin.buffer, m) to read something fr... | the_stack_v2_python_sparse | src/wrapper/bad_cluster.py | VanirLab/weever | train | 3 |
6e7e98e473f02067a09401f673a0372766c6ab12 | [
"if not matrix or not matrix[0]:\n return list()\nrows, columns = (len(matrix), len(matrix[0]))\nvisited = [[False] * columns for _ in range(rows)]\ntotal = rows * columns\norder = [0] * total\ndirections = [[0, 1], [1, 0], [0, -1], [-1, 0]]\nrow, column = (0, 0)\ndirectionIndex = 0\nfor i in range(total):\n ... | <|body_start_0|>
if not matrix or not matrix[0]:
return list()
rows, columns = (len(matrix), len(matrix[0]))
visited = [[False] * columns for _ in range(rows)]
total = rows * columns
order = [0] * total
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]:
"""方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :param matrix: :return:"""
<|body_0|>
def spiralOrder_2(self, matrix: List[List[int]]) -... | stack_v2_sparse_classes_36k_train_006521 | 3,194 | no_license | [
{
"docstring": "方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :param matrix: :return:",
"name": "spiralOrder_1",
"signature": "def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]"
},
{
"docstring": "方法二:按层模拟 时间复杂度:O(mn),其... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]: 方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :par... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]: 方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :par... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]:
"""方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :param matrix: :return:"""
<|body_0|>
def spiralOrder_2(self, matrix: List[List[int]]) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def spiralOrder_1(self, matrix: List[List[int]]) -> List[int]:
"""方法一:模拟 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。 :param matrix: :return:"""
if not matrix or not matrix[0]:
return list()
rows, columns ... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/spiralOrder.py | MaoningGuan/LeetCode | train | 3 | |
ea168550fdbb5510f0f0b37717f140602a6b6961 | [
"self.time = 0\nself.tweets = {}\nself.follows = {}",
"if userId in self.tweets:\n self.tweets[userId].append([-self.time, tweetId])\nelse:\n self.tweets[userId] = [[-self.time, tweetId]]\nself.time += 1",
"users = list(self.follows.get(userId, set()) | set([userId]))\npointers = [len(self.tweets.get(u, [... | <|body_start_0|>
self.time = 0
self.tweets = {}
self.follows = {}
<|end_body_0|>
<|body_start_1|>
if userId in self.tweets:
self.tweets[userId].append([-self.time, tweetId])
else:
self.tweets[userId] = [[-self.time, tweetId]]
self.time += 1
<|end_... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k_train_006522 | 2,393 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: void",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | stack_v2_sparse_classes_30k_train_017707 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | 616939d1599b5a135747b0c4dd1f989974835f40 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.time = 0
self.tweets = {}
self.follows = {}
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
if userId in self.twe... | the_stack_v2_python_sparse | 355. Design Twitter.py | BITMystery/leetcode-journey | train | 0 | |
0e5a14d238bc7cc34fd3aad87fc634e42a176871 | [
"super(WordDatatype_iter_with_caching, self).__init__(parent, iter, length)\nself._data, self._gen = itertools.tee(self._data)\nself._list = []\nself._last_index = -1",
"for a in self._list:\n yield a\nfor a in self._gen:\n self._list.append(a)\n self._last_index += 1\n yield a\nif self._len is None:\... | <|body_start_0|>
super(WordDatatype_iter_with_caching, self).__init__(parent, iter, length)
self._data, self._gen = itertools.tee(self._data)
self._list = []
self._last_index = -1
<|end_body_0|>
<|body_start_1|>
for a in self._list:
yield a
for a in self._gen... | WordDatatype_iter_with_caching | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDatatype_iter_with_caching:
def __init__(self, parent, iter, length=None):
"""INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababba... | stack_v2_sparse_classes_36k_train_006523 | 39,600 | no_license | [
{
"docstring": "INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle(\"abbabaab\")) word: abbabaababbabaababbabaababbabaababbabaab... sage: w = Word(iter(\"abbabaab\"), length=\"finite\"); w... | 5 | stack_v2_sparse_classes_30k_train_012723 | Implement the Python class `WordDatatype_iter_with_caching` described below.
Class description:
Implement the WordDatatype_iter_with_caching class.
Method signatures and docstrings:
- def __init__(self, parent, iter, length=None): INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None... | Implement the Python class `WordDatatype_iter_with_caching` described below.
Class description:
Implement the WordDatatype_iter_with_caching class.
Method signatures and docstrings:
- def __init__(self, parent, iter, length=None): INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class WordDatatype_iter_with_caching:
def __init__(self, parent, iter, length=None):
"""INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDatatype_iter_with_caching:
def __init__(self, parent, iter, length=None):
"""INPUT: - ``parent`` - a parent - ``iter`` - an iterator - ``length`` - (default: ``None``) the length of the word EXAMPLES:: sage: import itertools sage: Word(itertools.cycle("abbabaab")) word: abbabaababbabaababbabaabab... | the_stack_v2_python_sparse | sage/src/sage/combinat/words/word_infinite_datatypes.py | bopopescu/geosci | train | 0 | |
f7a4bd31000e4c995d2415150b8d91bdf003ce28 | [
"logger.info('Executing Filter: Crop')\n_ = self.instance(**params)\nparams = param.ParamOverrides(self, params)\ncropped_array = self._crop(params.arrays, params.crop_limit, params.border_pix, params.expand_ratio, params.rel_intensity_threshold_air_or_slit, params.rel_intensity_threshold_fov, params.rel_intensity_... | <|body_start_0|>
logger.info('Executing Filter: Crop')
_ = self.instance(**params)
params = param.ParamOverrides(self, params)
cropped_array = self._crop(params.arrays, params.crop_limit, params.border_pix, params.expand_ratio, params.rel_intensity_threshold_air_or_slit, params.rel_inten... | Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigger the automatic bounds detection. border_pix: int the width of border r... | crop | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class crop:
"""Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigger the automatic bounds detection. borde... | stack_v2_sparse_classes_36k_train_006524 | 8,751 | permissive | [
{
"docstring": "Call the function.",
"name": "__call__",
"signature": "def __call__(self, **params)"
},
{
"docstring": "Private function to crop the image stack.",
"name": "_crop",
"signature": "def _crop(self, arrays, crop_limit, border_pix, expand_ratio, rel_intensity_threshold_air_or_... | 2 | stack_v2_sparse_classes_30k_train_000066 | Implement the Python class `crop` described below.
Class description:
Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigge... | Implement the Python class `crop` described below.
Class description:
Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigge... | 7c9dea7a3a7877af1bafdfb71da8fb018d5d828f | <|skeleton|>
class crop:
"""Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigger the automatic bounds detection. borde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class crop:
"""Crop the image stack to provided limits or auto detected bound box. Parameters ---------- arrays: ndarray The image stack to crop. Can also be a 2D image. crop_limit: tuple The four limits for cropping. Default is (-1, -1, -1, -1), which will trigger the automatic bounds detection. border_pix: int th... | the_stack_v2_python_sparse | src/imars3d/backend/morph/crop.py | ornlneutronimaging/iMars3D | train | 3 |
978e8091633c56578b439f9c6f2b293766e6db8a | [
"if not head:\n return None\nif not head.next:\n return head\nnxt = head.next\nhead.next = self.swapPairs(head.next.next)\nnxt.next = head\nreturn nxt",
"if not head:\n return None\nif not head.next:\n return head\ndummy = ListNode(-1)\ndummy.next = head\ncurr = dummy\nwhile curr.next and curr.next.ne... | <|body_start_0|>
if not head:
return None
if not head.next:
return head
nxt = head.next
head.next = self.swapPairs(head.next.next)
nxt.next = head
return nxt
<|end_body_0|>
<|body_start_1|>
if not head:
return None
if n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_dummy(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return Non... | stack_v2_sparse_classes_36k_train_006525 | 1,522 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_dummy",
"signature": "def swapPairs_dummy(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020439 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_dummy(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_dummy(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def s... | f2c4f727689567e00ee06560132fca55a6fd9286 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_dummy(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return None
if not head.next:
return head
nxt = head.next
head.next = self.swapPairs(head.next.next)
nxt.next = head
return nxt
def... | the_stack_v2_python_sparse | leetcode/24_Swap_Nodes_in_Pairs.py | JianxiangWang/python-journey | train | 1 | |
0c9d3b202e065b18475a060706c950b1b397b5a1 | [
"destination = validate_branch_exists_in_city(data.get('destination'))\nbooking_station = validate_branch_exists_in_city(data.get('booking_station'))\nif not destination:\n raise serializers.ValidationError({'errors': {'destination': \"We don't have a branch in that city.\"}})\nelif not booking_station:\n rai... | <|body_start_0|>
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))
if not destination:
raise serializers.ValidationError({'errors': {'destination': "We don't have a branch in that city."... | Serializer to handle the Cargo serialization. | CargoSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_006526 | 2,171 | permissive | [
{
"docstring": "Ensure all passed data is valid.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Ensure that we create the Cargo using the correct method.",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014809 | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method. | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method.
<... | 60d034681da66771412fc73402d690a9fcaa5920 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))... | the_stack_v2_python_sparse | cargotracker/cargo/serializers.py | MandelaK/CargoTracker | train | 0 |
302486e74ceafbb2d150000fe34e65a3f95e3e78 | [
"obj = Project(name='test')\nobj.save()\nself.assertEquals('test', obj.name)\nself.assertNotEquals(obj.id, None)\nobj.delete()",
"project = Project(name='test')\nproject.save()\nstatus = TaskStatus(name='test')\nstatus.save()\nobj = Task(name='test', project=project, status=status, priority=3)\nobj.save()\nself.a... | <|body_start_0|>
obj = Project(name='test')
obj.save()
self.assertEquals('test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
<|end_body_0|>
<|body_start_1|>
project = Project(name='test')
project.save()
status = TaskStatus(name='test')
... | Documents models tests | ProjectsModelsTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsModelsTest:
"""Documents models tests"""
def test_model_project(self):
"""Test project"""
<|body_0|>
def test_model_task(self):
"""Test task"""
<|body_1|>
def test_model_task_status(self):
"""Test task status"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k_train_006527 | 25,070 | permissive | [
{
"docstring": "Test project",
"name": "test_model_project",
"signature": "def test_model_project(self)"
},
{
"docstring": "Test task",
"name": "test_model_task",
"signature": "def test_model_task(self)"
},
{
"docstring": "Test task status",
"name": "test_model_task_status",
... | 3 | stack_v2_sparse_classes_30k_train_006582 | Implement the Python class `ProjectsModelsTest` described below.
Class description:
Documents models tests
Method signatures and docstrings:
- def test_model_project(self): Test project
- def test_model_task(self): Test task
- def test_model_task_status(self): Test task status | Implement the Python class `ProjectsModelsTest` described below.
Class description:
Documents models tests
Method signatures and docstrings:
- def test_model_project(self): Test project
- def test_model_task(self): Test task
- def test_model_task_status(self): Test task status
<|skeleton|>
class ProjectsModelsTest:
... | 001e85eaf489c93b565efe679eb159cfcfef4c67 | <|skeleton|>
class ProjectsModelsTest:
"""Documents models tests"""
def test_model_project(self):
"""Test project"""
<|body_0|>
def test_model_task(self):
"""Test task"""
<|body_1|>
def test_model_task_status(self):
"""Test task status"""
<|body_2|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectsModelsTest:
"""Documents models tests"""
def test_model_project(self):
"""Test project"""
obj = Project(name='test')
obj.save()
self.assertEquals('test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
def test_model_task(self):
... | the_stack_v2_python_sparse | projects/tests.py | alejo8591/maker | train | 0 |
54c4f3520d5d633aec41806b924b17ff1faf61a8 | [
"QtWidgets.QDialog.__init__(self)\nself.findText = QtWidgets.QLineEdit()\nself.replaceText = QtWidgets.QLineEdit()\nself.layout = QtWidgets.QGridLayout(self)\nself.layout.addWidget(self.findText, 0, 1)\nself.layout.addWidget(QtWidgets.QLabel('Text to Find:'), 0, 0)\nself.layout.addWidget(self.replaceText, 1, 1)\nse... | <|body_start_0|>
QtWidgets.QDialog.__init__(self)
self.findText = QtWidgets.QLineEdit()
self.replaceText = QtWidgets.QLineEdit()
self.layout = QtWidgets.QGridLayout(self)
self.layout.addWidget(self.findText, 0, 1)
self.layout.addWidget(QtWidgets.QLabel('Text to Find:'), 0... | A dialog box to retrieve the two text values required by the findAndReplace function. | FindAndReplaceDialogBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindAndReplaceDialogBox:
"""A dialog box to retrieve the two text values required by the findAndReplace function."""
def __init__(self, parent):
"""Initializes the UI and sets the properties."""
<|body_0|>
def getResults(self, parent=None):
"""Returns the user's ... | stack_v2_sparse_classes_36k_train_006528 | 29,548 | no_license | [
{
"docstring": "Initializes the UI and sets the properties.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Returns the user's input",
"name": "getResults",
"signature": "def getResults(self, parent=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007247 | Implement the Python class `FindAndReplaceDialogBox` described below.
Class description:
A dialog box to retrieve the two text values required by the findAndReplace function.
Method signatures and docstrings:
- def __init__(self, parent): Initializes the UI and sets the properties.
- def getResults(self, parent=None)... | Implement the Python class `FindAndReplaceDialogBox` described below.
Class description:
A dialog box to retrieve the two text values required by the findAndReplace function.
Method signatures and docstrings:
- def __init__(self, parent): Initializes the UI and sets the properties.
- def getResults(self, parent=None)... | 1a3c5ad967472faf66236a311cc07a5128f5f911 | <|skeleton|>
class FindAndReplaceDialogBox:
"""A dialog box to retrieve the two text values required by the findAndReplace function."""
def __init__(self, parent):
"""Initializes the UI and sets the properties."""
<|body_0|>
def getResults(self, parent=None):
"""Returns the user's ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindAndReplaceDialogBox:
"""A dialog box to retrieve the two text values required by the findAndReplace function."""
def __init__(self, parent):
"""Initializes the UI and sets the properties."""
QtWidgets.QDialog.__init__(self)
self.findText = QtWidgets.QLineEdit()
self.re... | the_stack_v2_python_sparse | datatool/gui/Model.py | scottawalton/datatool | train | 0 |
f0cc5f6a96e9e7d5a5eabfb7d64af4cb2410ff5c | [
"self.head = head\nnode, i = (head, 0)\nwhile node:\n i += 1\n node = node.next\nself.len = i",
"node = self.head\ni = random.randint(1, self.len)\nwhile i > 1:\n node = node.next\n i -= 1\nreturn node.val"
] | <|body_start_0|>
self.head = head
node, i = (head, 0)
while node:
i += 1
node = node.next
self.len = i
<|end_body_0|>
<|body_start_1|>
node = self.head
i = random.randint(1, self.len)
while i > 1:
node = node.next
i... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k_train_006529 | 1,805 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | stack_v2_sparse_classes_30k_train_014558 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | 4ed2d3d7a05890e1d39621465e57bc429ccde19b | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
node, i = (head, 0)
while node:
i += 1
node = node.nex... | the_stack_v2_python_sparse | python/leetcode/p382.py | aloklal99/naukari | train | 0 | |
72538b8a72e12395b10a7f2a0b36901eefdbbe0a | [
"try:\n label = await get_data_from_req(self.request).labels.get(label_id)\nexcept ResourceNotFoundError:\n raise NotFound()\nreturn json_response(label)",
"if not data:\n raise EmptyRequest()\ntry:\n label = await get_data_from_req(self.request).labels.update(label_id=label_id, data=data)\nexcept Res... | <|body_start_0|>
try:
label = await get_data_from_req(self.request).labels.get(label_id)
except ResourceNotFoundError:
raise NotFound()
return json_response(label)
<|end_body_0|>
<|body_start_1|>
if not data:
raise EmptyRequest()
try:
... | LabelView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
<|body_0|>
async def patch(self, label_id: int, /, data: UpdateLabelRequest... | stack_v2_sparse_classes_36k_train_006530 | 3,972 | permissive | [
{
"docstring": "Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found",
"name": "get",
"signature": "async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]"
},
{
"docstring": "Update a label. Updates an existing sample labe... | 3 | stack_v2_sparse_classes_30k_test_001043 | Implement the Python class `LabelView` described below.
Class description:
Implement the LabelView class.
Method signatures and docstrings:
- async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]: Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not... | Implement the Python class `LabelView` described below.
Class description:
Implement the LabelView class.
Method signatures and docstrings:
- async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]: Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
<|body_0|>
async def patch(self, label_id: int, /, data: UpdateLabelRequest... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelView:
async def get(self, label_id: int, /) -> Union[r200[LabelResponse], r404]:
"""Get a label. Fetches the details for a sample label. Status Codes: 200: Successful operation 404: Not found"""
try:
label = await get_data_from_req(self.request).labels.get(label_id)
ex... | the_stack_v2_python_sparse | virtool/labels/api.py | virtool/virtool | train | 45 | |
e705fd6deb0bb882f039165ea01c4362b6dae418 | [
"self.optional = optional\nself.initialised = False\nif cfg_dir:\n config_file = f\"{cfg_dir.rstrip('/')}/{config_file_name}\"\nelse:\n cwd = os.path.dirname(os.path.realpath(sys.argv[0]))\n current = os.path.expanduser(f\"/{cwd.lstrip('/')}/{config_file_name}\")\n if os.path.exists(current) and os.path... | <|body_start_0|>
self.optional = optional
self.initialised = False
if cfg_dir:
config_file = f"{cfg_dir.rstrip('/')}/{config_file_name}"
else:
cwd = os.path.dirname(os.path.realpath(sys.argv[0]))
current = os.path.expanduser(f"/{cwd.lstrip('/')}/{confi... | Encapsulates application configuration. One can use it for retrieving various section form the configuration. | CfgEngine | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CfgEngine:
"""Encapsulates application configuration. One can use it for retrieving various section form the configuration."""
def __init__(self, cfg_dir, config_file_name='cfg.yml', optional=False):
""":param cfg_dir: the directory which holds the configuration files; :param config_... | stack_v2_sparse_classes_36k_train_006531 | 3,226 | permissive | [
{
"docstring": ":param cfg_dir: the directory which holds the configuration files; :param config_file_name: the file name which contains the configuration (cfg.yml by default); :param optional: if True it will initialise even if config resource is not found (defaults to False);",
"name": "__init__",
"si... | 3 | stack_v2_sparse_classes_30k_train_012409 | Implement the Python class `CfgEngine` described below.
Class description:
Encapsulates application configuration. One can use it for retrieving various section form the configuration.
Method signatures and docstrings:
- def __init__(self, cfg_dir, config_file_name='cfg.yml', optional=False): :param cfg_dir: the dire... | Implement the Python class `CfgEngine` described below.
Class description:
Encapsulates application configuration. One can use it for retrieving various section form the configuration.
Method signatures and docstrings:
- def __init__(self, cfg_dir, config_file_name='cfg.yml', optional=False): :param cfg_dir: the dire... | 1be8707f535e9f8ad78ef944f2631b15ce03e8f3 | <|skeleton|>
class CfgEngine:
"""Encapsulates application configuration. One can use it for retrieving various section form the configuration."""
def __init__(self, cfg_dir, config_file_name='cfg.yml', optional=False):
""":param cfg_dir: the directory which holds the configuration files; :param config_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CfgEngine:
"""Encapsulates application configuration. One can use it for retrieving various section form the configuration."""
def __init__(self, cfg_dir, config_file_name='cfg.yml', optional=False):
""":param cfg_dir: the directory which holds the configuration files; :param config_file_name: th... | the_stack_v2_python_sparse | appkernel/infrastructure.py | arnand/appkernel | train | 0 |
b680dfffaff84fd4e873884b2b637a8d3a6f4cf0 | [
"configs = []\nweight = 0\nfor config in exam_config:\n if 'datetime' in config.keys():\n if config['datetime'] < timezone.now():\n raise ParseError('A data/hora da prova não pode ser menor que a data/hora atual.')\n if 'weight' in config.keys():\n weight += config['weight']\n else... | <|body_start_0|>
configs = []
weight = 0
for config in exam_config:
if 'datetime' in config.keys():
if config['datetime'] < timezone.now():
raise ParseError('A data/hora da prova não pode ser menor que a data/hora atual.')
if 'weight' i... | Serializado de dados dos grupos da disciplina. | SectionSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
<|body_0|>
def create(self, validated_data):
"""Cria e retorna uma nova seção."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_006532 | 3,246 | no_license | [
{
"docstring": "Cria as configurações da avaliação.",
"name": "create_exam_config",
"signature": "def create_exam_config(self, exam_config)"
},
{
"docstring": "Cria e retorna uma nova seção.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "At... | 3 | null | Implement the Python class `SectionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def create_exam_config(self, exam_config): Cria as configurações da avaliação.
- def create(self, validated_data): Cria e retorna uma nova seção.
- def ... | Implement the Python class `SectionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def create_exam_config(self, exam_config): Cria as configurações da avaliação.
- def create(self, validated_data): Cria e retorna uma nova seção.
- def ... | 3a8009b17518384c269dfee3c8fe44cbe2567cc0 | <|skeleton|>
class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
<|body_0|>
def create(self, validated_data):
"""Cria e retorna uma nova seção."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SectionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def create_exam_config(self, exam_config):
"""Cria as configurações da avaliação."""
configs = []
weight = 0
for config in exam_config:
if 'datetime' in config.keys():
if co... | the_stack_v2_python_sparse | project/alma/sections/serializers.py | VWApplications/VWAlmaAPI | train | 1 |
a6b78f70ac2c46b4ba88bde90d9142fe36882f8e | [
"self.trace_msg('Export all text strings to stdout')\ntable = self.make_table_name(langid)\nself.execute_query('SELECT xmlid, textstring FROM ' + table + '\\n where (role=\"STRING\" or role=\"MENUITEM\" or role=\"DIALOG\" or role=\"CONTROL\") and translate=1')\nstrings = self.cursor.fetchall(... | <|body_start_0|>
self.trace_msg('Export all text strings to stdout')
table = self.make_table_name(langid)
self.execute_query('SELECT xmlid, textstring FROM ' + table + '\n where (role="STRING" or role="MENUITEM" or role="DIALOG" or role="CONTROL") and translate=1')
... | LionDBOutputMixIn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LionDBOutputMixIn:
def textstrings(self, langid):
"""Export all textstrings to stdout. Exclude mnemonic and accelerator items."""
<|body_0|>
def all_strings(self, langid, start_index=0, end_index=-1):
"""Export all strings to stdout"""
<|body_1|>
def all... | stack_v2_sparse_classes_36k_train_006533 | 2,482 | no_license | [
{
"docstring": "Export all textstrings to stdout. Exclude mnemonic and accelerator items.",
"name": "textstrings",
"signature": "def textstrings(self, langid)"
},
{
"docstring": "Export all strings to stdout",
"name": "all_strings",
"signature": "def all_strings(self, langid, start_index... | 5 | null | Implement the Python class `LionDBOutputMixIn` described below.
Class description:
Implement the LionDBOutputMixIn class.
Method signatures and docstrings:
- def textstrings(self, langid): Export all textstrings to stdout. Exclude mnemonic and accelerator items.
- def all_strings(self, langid, start_index=0, end_inde... | Implement the Python class `LionDBOutputMixIn` described below.
Class description:
Implement the LionDBOutputMixIn class.
Method signatures and docstrings:
- def textstrings(self, langid): Export all textstrings to stdout. Exclude mnemonic and accelerator items.
- def all_strings(self, langid, start_index=0, end_inde... | ce51564317b213bf16827534a7dbc270a7582cb8 | <|skeleton|>
class LionDBOutputMixIn:
def textstrings(self, langid):
"""Export all textstrings to stdout. Exclude mnemonic and accelerator items."""
<|body_0|>
def all_strings(self, langid, start_index=0, end_index=-1):
"""Export all strings to stdout"""
<|body_1|>
def all... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LionDBOutputMixIn:
def textstrings(self, langid):
"""Export all textstrings to stdout. Exclude mnemonic and accelerator items."""
self.trace_msg('Export all text strings to stdout')
table = self.make_table_name(langid)
self.execute_query('SELECT xmlid, textstring FROM ' + table... | the_stack_v2_python_sparse | lionapp/trunk/lion/daisylion/db/liondb_output_mixin.py | standardgalactic/lion | train | 0 | |
296d03b0580dd8c490a1fe69ad1bca8fd23dad8d | [
"prev = None\nwhile head:\n link = head.next\n head.next = prev\n prev, head = (head, link)\nreturn prev",
"head1 = self.reverse_list(head1)\nhead2 = self.reverse_list(head2)\ncurr1, curr2 = (head1, head2)\nrem = 0\nprev = None\nwhile curr1 and curr2:\n curr_sum = curr1.val + curr2.val + rem\n curr... | <|body_start_0|>
prev = None
while head:
link = head.next
head.next = prev
prev, head = (head, link)
return prev
<|end_body_0|>
<|body_start_1|>
head1 = self.reverse_list(head1)
head2 = self.reverse_list(head2)
curr1, curr2 = (head1, h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
<|body_0|>
def addTwoNumbers(self, head1, head2):
"""Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m ar... | stack_v2_sparse_classes_36k_train_006534 | 2,113 | no_license | [
{
"docstring": "Reverses linked list and returns a link to new head pointer.",
"name": "reverse_list",
"signature": "def reverse_list(self, head)"
},
{
"docstring": "Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m are lengths of the linked... | 2 | stack_v2_sparse_classes_30k_train_018765 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head): Reverses linked list and returns a link to new head pointer.
- def addTwoNumbers(self, head1, head2): Returns head pointer to a new linked list. Tim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(self, head): Reverses linked list and returns a link to new head pointer.
- def addTwoNumbers(self, head1, head2): Returns head pointer to a new linked list. Tim... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
<|body_0|>
def addTwoNumbers(self, head1, head2):
"""Returns head pointer to a new linked list. Time complexity: O(n + m). Space complexity: O(1), where n, m ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_list(self, head):
"""Reverses linked list and returns a link to new head pointer."""
prev = None
while head:
link = head.next
head.next = prev
prev, head = (head, link)
return prev
def addTwoNumbers(self, head1, hea... | the_stack_v2_python_sparse | Linked_Lists/add_two_numbers_2.py | vladn90/Algorithms | train | 0 | |
052e7f3ce03535d0862e5865ca42ae095fed2032 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SocialIdentityProvider()",
"from .identity_provider_base import IdentityProviderBase\nfrom .identity_provider_base import IdentityProviderBase\nfields: Dict[str, Callable[[Any], None]] = {'clientId': lambda n: setattr(self, 'client_id'... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SocialIdentityProvider()
<|end_body_0|>
<|body_start_1|>
from .identity_provider_base import IdentityProviderBase
from .identity_provider_base import IdentityProviderBase
fields:... | SocialIdentityProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocialIdentityProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SocialIdentityProvider:
"""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 ... | stack_v2_sparse_classes_36k_train_006535 | 3,058 | 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: SocialIdentityProvider",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `SocialIdentityProvider` described below.
Class description:
Implement the SocialIdentityProvider class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SocialIdentityProvider: Creates a new instance of the appropriate class b... | Implement the Python class `SocialIdentityProvider` described below.
Class description:
Implement the SocialIdentityProvider class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SocialIdentityProvider: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SocialIdentityProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SocialIdentityProvider:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SocialIdentityProvider:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SocialIdentityProvider:
"""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 Ret... | the_stack_v2_python_sparse | msgraph/generated/models/social_identity_provider.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8d3c118a12c611f0920fa78ba72e8a550b9d02db | [
"cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)\nwith cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):\n request_id = int(request_id)\nif parametricjob_id is not None:\n with cherrypy.HTTPError.handle(ValueError, 400, 'Bad parametricjo... | <|body_start_0|>
cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)
with cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):
request_id = int(request_id)
if parametricjob_id is not None:
with cherrypy.HTT... | Parametric Jobs RESTful API. | ParametricJobsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
<|body_0|>
def PUT(cls, request_id, parametricjob_id, reschedule):
"""REST Put method.... | stack_v2_sparse_classes_36k_train_006536 | 14,924 | permissive | [
{
"docstring": "REST Get method. Returns all ParametricJobs for a given request id.",
"name": "GET",
"signature": "def GET(cls, request_id, parametricjob_id=None)"
},
{
"docstring": "REST Put method.",
"name": "PUT",
"signature": "def PUT(cls, request_id, parametricjob_id, reschedule)"
... | 2 | stack_v2_sparse_classes_30k_train_017484 | Implement the Python class `ParametricJobsAPI` described below.
Class description:
Parametric Jobs RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id, parametricjob_id=None): REST Get method. Returns all ParametricJobs for a given request id.
- def PUT(cls, request_id, parametricjob_id, reschedu... | Implement the Python class `ParametricJobsAPI` described below.
Class description:
Parametric Jobs RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id, parametricjob_id=None): REST Get method. Returns all ParametricJobs for a given request id.
- def PUT(cls, request_id, parametricjob_id, reschedu... | 43225a155a985a7a56402df23dd550e48e22b436 | <|skeleton|>
class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
<|body_0|>
def PUT(cls, request_id, parametricjob_id, reschedule):
"""REST Put method.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)
with cherryp... | the_stack_v2_python_sparse | productionsystem/webapp/services/RESTfulAPI.py | alexanderrichards/ProductionSystem | train | 0 |
752781b56f68e1108079275ee613dc4cc621cdfc | [
"self.user = user\nself.qbd = QuestionnaireBank.most_current_qb(user, as_of_date=as_of_date)\nself.status_by_q = qb_status_dict(user=user, qbd=self.qbd, as_of_date=as_of_date)",
"dates = [self.status_by_q[q]['completed'] for q in self.status_by_q if 'completed' in self.status_by_q[q]]\ndates.sort(reverse=True)\ni... | <|body_start_0|>
self.user = user
self.qbd = QuestionnaireBank.most_current_qb(user, as_of_date=as_of_date)
self.status_by_q = qb_status_dict(user=user, qbd=self.qbd, as_of_date=as_of_date)
<|end_body_0|>
<|body_start_1|>
dates = [self.status_by_q[q]['completed'] for q in self.status_by... | Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus. | QuestionnaireBankDetails | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionnaireBankDetails:
"""Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus."""
def __init__(self, user, as_of_date):
"""Initialize and lookup status fo... | stack_v2_sparse_classes_36k_train_006537 | 16,814 | permissive | [
{
"docstring": "Initialize and lookup status for respective questionnaires :param user: subject for details :param as_of_date: None value implies now",
"name": "__init__",
"signature": "def __init__(self, user, as_of_date)"
},
{
"docstring": "Returns timestamp from most recent completed assessme... | 3 | stack_v2_sparse_classes_30k_train_005707 | Implement the Python class `QuestionnaireBankDetails` described below.
Class description:
Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus.
Method signatures and docstrings:
- def __init__... | Implement the Python class `QuestionnaireBankDetails` described below.
Class description:
Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus.
Method signatures and docstrings:
- def __init__... | 622e90f54692c6fc9c84468f489ab6f297af0feb | <|skeleton|>
class QuestionnaireBankDetails:
"""Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus."""
def __init__(self, user, as_of_date):
"""Initialize and lookup status fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionnaireBankDetails:
"""Gather details on users most current QuestionnaireBank Houses details including questionnaire's classification, recent reports and details needed by clients like AssessmentStatus."""
def __init__(self, user, as_of_date):
"""Initialize and lookup status for respective ... | the_stack_v2_python_sparse | portal/models/assessment_status.py | pep8speaks/true_nth_usa_portal | train | 1 |
0d0a318880f46604fe0e963a30334b6d1bd19cc0 | [
"self.client.force_authenticate(user=self.user)\nurl = reverse('commerce:itemlist', kwargs={'version': 'v2'})\nnew_cart = Cart.objects.all()\nnew_cart.delete()\ndata = {'command': 'create', 'cart_name': 'tests'}\nresponse = self.client.post(url, data, format='json')\njson_response = response.json()\ncart_id = int(j... | <|body_start_0|>
self.client.force_authenticate(user=self.user)
url = reverse('commerce:itemlist', kwargs={'version': 'v2'})
new_cart = Cart.objects.all()
new_cart.delete()
data = {'command': 'create', 'cart_name': 'tests'}
response = self.client.post(url, data, format='j... | PurchaseCartTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseCartTest:
def test_create_Cart(self):
"""Ensure we can create a new account object."""
<|body_0|>
def test_update_Cart(self):
"""Ensure we can update a cart object."""
<|body_1|>
def test_update_Cart_fail(self):
"""Ensure we cant update a... | stack_v2_sparse_classes_36k_train_006538 | 10,115 | no_license | [
{
"docstring": "Ensure we can create a new account object.",
"name": "test_create_Cart",
"signature": "def test_create_Cart(self)"
},
{
"docstring": "Ensure we can update a cart object.",
"name": "test_update_Cart",
"signature": "def test_update_Cart(self)"
},
{
"docstring": "Ens... | 5 | stack_v2_sparse_classes_30k_train_016094 | Implement the Python class `PurchaseCartTest` described below.
Class description:
Implement the PurchaseCartTest class.
Method signatures and docstrings:
- def test_create_Cart(self): Ensure we can create a new account object.
- def test_update_Cart(self): Ensure we can update a cart object.
- def test_update_Cart_fa... | Implement the Python class `PurchaseCartTest` described below.
Class description:
Implement the PurchaseCartTest class.
Method signatures and docstrings:
- def test_create_Cart(self): Ensure we can create a new account object.
- def test_update_Cart(self): Ensure we can update a cart object.
- def test_update_Cart_fa... | 82f372ecae245b1affc6f7eaa15a0785146e6ca5 | <|skeleton|>
class PurchaseCartTest:
def test_create_Cart(self):
"""Ensure we can create a new account object."""
<|body_0|>
def test_update_Cart(self):
"""Ensure we can update a cart object."""
<|body_1|>
def test_update_Cart_fail(self):
"""Ensure we cant update a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PurchaseCartTest:
def test_create_Cart(self):
"""Ensure we can create a new account object."""
self.client.force_authenticate(user=self.user)
url = reverse('commerce:itemlist', kwargs={'version': 'v2'})
new_cart = Cart.objects.all()
new_cart.delete()
data = {'co... | the_stack_v2_python_sparse | commerce/tests.py | Janujan/commerce-challenge | train | 0 | |
1c7cba4b22ea00eddb9d2fdf84a85e2117aaebe0 | [
"while end > begin:\n if string[begin] != string[end]:\n return False\n begin += 1\n end -= 1\nreturn True",
"size = len(string)\nfor length in range(size, 1, -1):\n for offset in range(size - length + 1):\n if self._isPalindrome(string, offset, offset + length - 1):\n return ... | <|body_start_0|>
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
<|end_body_0|>
<|body_start_1|>
size = len(string)
for length in range(size, 1, -1):
for offset in range(size... | Naive | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while end > begin:
if st... | stack_v2_sparse_classes_36k_train_006539 | 3,988 | no_license | [
{
"docstring": "Verify if substring is a palindrome.",
"name": "_isPalindrome",
"signature": "def _isPalindrome(self, string, begin, end)"
},
{
"docstring": "Solve the problem.",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, string)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009646 | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem. | Implement the Python class `Naive` described below.
Class description:
Implement the Naive class.
Method signatures and docstrings:
- def _isPalindrome(self, string, begin, end): Verify if substring is a palindrome.
- def longestPalindrome(self, string): Solve the problem.
<|skeleton|>
class Naive:
def _isPalin... | 97246c26483637b95198ed2ef76e234d3c0194dc | <|skeleton|>
class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
<|body_0|>
def longestPalindrome(self, string):
"""Solve the problem."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Naive:
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
def longestPalindrome(self, string):
... | the_stack_v2_python_sparse | coding/leetcode/problems/longest_palindromic_substring_hashing_v3_stress.py | baites/examples | train | 4 | |
0618702a8cf656c2469e54df5f42e60ee222b728 | [
"sn = len(s)\ntn = len(t)\nlists = []\nlistt = []\nif sn != tn:\n return False\nfor i in range(0, sn):\n lists.append(s[i])\nfor j in range(0, tn):\n listt.append(t[j])\nlistt.sort()\nlists.sort()\nif lists == listt:\n return True\nelse:\n return False",
"\"\"\"\n 思路:定义一个26长度的列表,每个元素都是0,在s中进... | <|body_start_0|>
sn = len(s)
tn = len(t)
lists = []
listt = []
if sn != tn:
return False
for i in range(0, sn):
lists.append(s[i])
for j in range(0, tn):
listt.append(t[j])
listt.sort()
lists.sort()
if li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sn = len(s)
tn = len(t)
... | stack_v2_sparse_classes_36k_train_006540 | 1,833 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram",
"signature": "def isAnagram(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram2",
"signature": "def isAnagram2(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009909 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:
def isAn... | c2250f2c7365976a6767e3c12760474f7a6618eb | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
sn = len(s)
tn = len(t)
lists = []
listt = []
if sn != tn:
return False
for i in range(0, sn):
lists.append(s[i])
for j in range(0, tn):
... | the_stack_v2_python_sparse | 242. Valid Anagram/242. Valid Anagram.py | yaolinxia/leetcode_study | train | 0 | |
77083dd974c78be3daf2458088c7adc21127226c | [
"scaled = self.sun * scale + self.bbn * (1 - scale)\nif scale > 1.0:\n jj, = np.argwhere(scaled.iso == isotope.ion('He4'))\n bbn = self.sun * 0 + self.bbn\n for j in np.argwhere(scaled.abu < self.sun.abu).flat:\n scaled.abu[jj] += scaled.abu[j]\n scaled.abu[j] = self.sun.abu[j] * np.exp((scal... | <|body_start_0|>
scaled = self.sun * scale + self.bbn * (1 - scale)
if scale > 1.0:
jj, = np.argwhere(scaled.iso == isotope.ion('He4'))
bbn = self.sun * 0 + self.bbn
for j in np.argwhere(scaled.abu < self.sun.abu).flat:
scaled.abu[jj] += scaled.abu[j]
... | Special abundance set created from scaled solar abundance set. | ScaledSolar | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledSolar:
"""Special abundance set created from scaled solar abundance set."""
def _abu_massfrac_raw(self, scale):
"""Raw scaled solar abundances"""
<|body_0|>
def __init__(self, scale=1, Z=None, **kw):
"""Create abundance from set name. Use simple algorithm: ... | stack_v2_sparse_classes_36k_train_006541 | 14,741 | permissive | [
{
"docstring": "Raw scaled solar abundances",
"name": "_abu_massfrac_raw",
"signature": "def _abu_massfrac_raw(self, scale)"
},
{
"docstring": "Create abundance from set name. Use simple algorithm: X = X_sun * scale + X_BBN * (1 - scale) If Z is provided, overwrite scale by Z/Zsun. For stuff tha... | 2 | stack_v2_sparse_classes_30k_train_002929 | Implement the Python class `ScaledSolar` described below.
Class description:
Special abundance set created from scaled solar abundance set.
Method signatures and docstrings:
- def _abu_massfrac_raw(self, scale): Raw scaled solar abundances
- def __init__(self, scale=1, Z=None, **kw): Create abundance from set name. U... | Implement the Python class `ScaledSolar` described below.
Class description:
Special abundance set created from scaled solar abundance set.
Method signatures and docstrings:
- def _abu_massfrac_raw(self, scale): Raw scaled solar abundances
- def __init__(self, scale=1, Z=None, **kw): Create abundance from set name. U... | 98fc181bab054619d12ffa4173ad5c469803c2ec | <|skeleton|>
class ScaledSolar:
"""Special abundance set created from scaled solar abundance set."""
def _abu_massfrac_raw(self, scale):
"""Raw scaled solar abundances"""
<|body_0|>
def __init__(self, scale=1, Z=None, **kw):
"""Create abundance from set name. Use simple algorithm: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaledSolar:
"""Special abundance set created from scaled solar abundance set."""
def _abu_massfrac_raw(self, scale):
"""Raw scaled solar abundances"""
scaled = self.sun * scale + self.bbn * (1 - scale)
if scale > 1.0:
jj, = np.argwhere(scaled.iso == isotope.ion('He4')... | the_stack_v2_python_sparse | kepler_python_packages/python_scripts/abusets.py | adam-m-jcbs/xrb-sens-datashare | train | 1 |
d81a53d7b79c858a3aa7046e38a7c433cb916ad8 | [
"assert isinstance(input_pin, analog_pin_io), 'input_pin must be a analog_pin_io'\nself.input_pin = input_pin\nself.Imax = float(Imax)\nassert Vmax != 0, 'Vmax cannot be zéro.'\nself.Vmax = float(Vmax)\nself.V0 = float(V0)\nassert freq != 0, 'freq cannot be zéro.'\nself.freq = float(freq)\nanalog_input_device_io.__... | <|body_start_0|>
assert isinstance(input_pin, analog_pin_io), 'input_pin must be a analog_pin_io'
self.input_pin = input_pin
self.Imax = float(Imax)
assert Vmax != 0, 'Vmax cannot be zéro.'
self.Vmax = float(Vmax)
self.V0 = float(V0)
assert freq != 0, 'freq cannot... | Module SCT03 | SCT013_v_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCT013_v_io:
"""Module SCT03"""
def __init__(self, input_pin, Imax=30.0, Vmax=1.0, V0=240.0, freq=50.0, seuil=50, thread=False, on_changed=None, discard=10, pause=0.1, timeout=5):
"""Initialisation - input_pin : a analog_pin_io - Imax : Maximum intensity of the sensor - Vmax : voltag... | stack_v2_sparse_classes_36k_train_006542 | 3,420 | permissive | [
{
"docstring": "Initialisation - input_pin : a analog_pin_io - Imax : Maximum intensity of the sensor - Vmax : voltage for Imax - freq : frequency of the electric curent - seuil : seuil de déclenchement du deamon soit un tuple (seuil_bas, seuil_haut) soit une seule valeur - thread : (facultatif) True si utilisa... | 2 | stack_v2_sparse_classes_30k_test_000306 | Implement the Python class `SCT013_v_io` described below.
Class description:
Module SCT03
Method signatures and docstrings:
- def __init__(self, input_pin, Imax=30.0, Vmax=1.0, V0=240.0, freq=50.0, seuil=50, thread=False, on_changed=None, discard=10, pause=0.1, timeout=5): Initialisation - input_pin : a analog_pin_io... | Implement the Python class `SCT013_v_io` described below.
Class description:
Module SCT03
Method signatures and docstrings:
- def __init__(self, input_pin, Imax=30.0, Vmax=1.0, V0=240.0, freq=50.0, seuil=50, thread=False, on_changed=None, discard=10, pause=0.1, timeout=5): Initialisation - input_pin : a analog_pin_io... | 46c4f9369964b2f9108f2776bf74f24ccdc71e7f | <|skeleton|>
class SCT013_v_io:
"""Module SCT03"""
def __init__(self, input_pin, Imax=30.0, Vmax=1.0, V0=240.0, freq=50.0, seuil=50, thread=False, on_changed=None, discard=10, pause=0.1, timeout=5):
"""Initialisation - input_pin : a analog_pin_io - Imax : Maximum intensity of the sensor - Vmax : voltag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SCT013_v_io:
"""Module SCT03"""
def __init__(self, input_pin, Imax=30.0, Vmax=1.0, V0=240.0, freq=50.0, seuil=50, thread=False, on_changed=None, discard=10, pause=0.1, timeout=5):
"""Initialisation - input_pin : a analog_pin_io - Imax : Maximum intensity of the sensor - Vmax : voltage for Imax - ... | the_stack_v2_python_sparse | FGPIO/SCT013_v_io.py | FredThx/FGPIO | train | 0 |
1b3e26fc2c901c7142c5cb58cb3277a8ed7cc731 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing Budget resources. | BudgetServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BudgetServiceServicer:
"""A set of methods for managing Budget resources."""
def Get(self, request, context):
"""Returns the specified budget."""
<|body_0|>
def List(self, request, context):
"""Retrieves the list of budgets corresponding to the specified billing ... | stack_v2_sparse_classes_36k_train_006543 | 6,541 | permissive | [
{
"docstring": "Returns the specified budget.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of budgets corresponding to the specified billing account.",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_013712 | Implement the Python class `BudgetServiceServicer` described below.
Class description:
A set of methods for managing Budget resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified budget.
- def List(self, request, context): Retrieves the list of budgets corresponding to t... | Implement the Python class `BudgetServiceServicer` described below.
Class description:
A set of methods for managing Budget resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified budget.
- def List(self, request, context): Retrieves the list of budgets corresponding to t... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class BudgetServiceServicer:
"""A set of methods for managing Budget resources."""
def Get(self, request, context):
"""Returns the specified budget."""
<|body_0|>
def List(self, request, context):
"""Retrieves the list of budgets corresponding to the specified billing ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BudgetServiceServicer:
"""A set of methods for managing Budget resources."""
def Get(self, request, context):
"""Returns the specified budget."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Metho... | the_stack_v2_python_sparse | yandex/cloud/billing/v1/budget_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
0ffe06f0d151830fc6f3ca48dce23ce80118cd5a | [
"while not database.kill_received and (not queue.empty()):\n try:\n sleep(0.1)\n except KeyboardInterrupt:\n try:\n stats.output_stats()\n sleep(1)\n except KeyboardInterrupt:\n textutils.output_info('Keyboard Interrupt Received, cleaning up threads')\n ... | <|body_start_0|>
while not database.kill_received and (not queue.empty()):
try:
sleep(0.1)
except KeyboardInterrupt:
try:
stats.output_stats()
sleep(1)
except KeyboardInterrupt:
te... | ThreadManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadManager:
def wait_for_idle(self, workers, queue):
"""Wait until fetch queue is empty and handle user interrupt"""
<|body_0|>
def spawn_workers(self, count, worker_type, output=True):
"""Spawn a given number of workers and return a reference list to them"""
... | stack_v2_sparse_classes_36k_train_006544 | 3,226 | no_license | [
{
"docstring": "Wait until fetch queue is empty and handle user interrupt",
"name": "wait_for_idle",
"signature": "def wait_for_idle(self, workers, queue)"
},
{
"docstring": "Spawn a given number of workers and return a reference list to them",
"name": "spawn_workers",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_019084 | Implement the Python class `ThreadManager` described below.
Class description:
Implement the ThreadManager class.
Method signatures and docstrings:
- def wait_for_idle(self, workers, queue): Wait until fetch queue is empty and handle user interrupt
- def spawn_workers(self, count, worker_type, output=True): Spawn a g... | Implement the Python class `ThreadManager` described below.
Class description:
Implement the ThreadManager class.
Method signatures and docstrings:
- def wait_for_idle(self, workers, queue): Wait until fetch queue is empty and handle user interrupt
- def spawn_workers(self, count, worker_type, output=True): Spawn a g... | 01e3e3a573a2be25123da4490a2ecb234045eee3 | <|skeleton|>
class ThreadManager:
def wait_for_idle(self, workers, queue):
"""Wait until fetch queue is empty and handle user interrupt"""
<|body_0|>
def spawn_workers(self, count, worker_type, output=True):
"""Spawn a given number of workers and return a reference list to them"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadManager:
def wait_for_idle(self, workers, queue):
"""Wait until fetch queue is empty and handle user interrupt"""
while not database.kill_received and (not queue.empty()):
try:
sleep(0.1)
except KeyboardInterrupt:
try:
... | the_stack_v2_python_sparse | core/threads.py | GoSecure/tachyon | train | 2 | |
d7e08d9fe74455f70df4be5b7c4ca61f6214f580 | [
"super(DCGAN3DEncoder, self).__init__(name=name)\nif initializers_no_bias is None:\n initializers_no_bias = _DEFAULT_CONV_INITIALIZERS_NO_BIAS\nif regularizers_no_bias is None:\n regularizers_no_bias = _DEFAULT_CONV_REGULARIZERS_NO_BIAS\nif filters is None:\n filters = [64, 128, 256, 512, 512]\nself._initi... | <|body_start_0|>
super(DCGAN3DEncoder, self).__init__(name=name)
if initializers_no_bias is None:
initializers_no_bias = _DEFAULT_CONV_INITIALIZERS_NO_BIAS
if regularizers_no_bias is None:
regularizers_no_bias = _DEFAULT_CONV_REGULARIZERS_NO_BIAS
if filters is Non... | A DCGAN model for 128x128 dimensional input. | DCGAN3DEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs... | stack_v2_sparse_classes_36k_train_006545 | 31,363 | no_license | [
{
"docstring": "Constructs a spatiotemporal DCGAN Encoder. Args: latent_size: The number of channels in the output layer. Defaults to 128. filters: An optional iterable giving the number of filters at each layer of the network. If None, uses the default configuration of [64, 128, 256, 512, 512]. final_activatio... | 2 | stack_v2_sparse_classes_30k_train_002395 | Implement the Python class `DCGAN3DEncoder` described below.
Class description:
A DCGAN model for 128x128 dimensional input.
Method signatures and docstrings:
- def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, reg... | Implement the Python class `DCGAN3DEncoder` described below.
Class description:
A DCGAN model for 128x128 dimensional input.
Method signatures and docstrings:
- def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, reg... | 358a09d491aab0794df9cc7f3f8064430a78fbc3 | <|skeleton|>
class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DCGAN3DEncoder:
"""A DCGAN model for 128x128 dimensional input."""
def __init__(self, latent_size=128, filters=None, final_activation=tf.nn.tanh, use_input_batchnorm=False, data_format='NCDHW', initializers_no_bias=None, regularizers_no_bias=None, name='dcgan_encoder'):
"""Constructs a spatiotemp... | the_stack_v2_python_sparse | architectures/conv_architectures.py | zwbgood6/temporal-hierarchy | train | 0 |
a9dd0b273811d75af53603ff91a1227a4fe9f7eb | [
"self.cleaned_data['documento']\ndocumento = self.cleaned_data['documento']\nif not re.search('^\\\\w+$', documento):\n raise forms.ValidationError(u'Este campo sólo puede contener letras del alfabeto y números')\nreturn documento",
"cleaned_data = self.cleaned_data\ntipo_documento = cleaned_data.get('tipo_doc... | <|body_start_0|>
self.cleaned_data['documento']
documento = self.cleaned_data['documento']
if not re.search('^\\w+$', documento):
raise forms.ValidationError(u'Este campo sólo puede contener letras del alfabeto y números')
return documento
<|end_body_0|>
<|body_start_1|>
... | LoginForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginForm:
def clean_documento(self):
"""Chequea que el usuario exista en la base de datos"""
<|body_0|>
def clean(self):
"""Chequeos posteriores en los que puede haber varios campos involucrados"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.... | stack_v2_sparse_classes_36k_train_006546 | 1,579 | permissive | [
{
"docstring": "Chequea que el usuario exista en la base de datos",
"name": "clean_documento",
"signature": "def clean_documento(self)"
},
{
"docstring": "Chequeos posteriores en los que puede haber varios campos involucrados",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | null | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def clean_documento(self): Chequea que el usuario exista en la base de datos
- def clean(self): Chequeos posteriores en los que puede haber varios campos involucrados | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def clean_documento(self): Chequea que el usuario exista en la base de datos
- def clean(self): Chequeos posteriores en los que puede haber varios campos involucrados
<|skelet... | 6cde3cab2bd1a8e3084fa38147de377d229391e3 | <|skeleton|>
class LoginForm:
def clean_documento(self):
"""Chequea que el usuario exista en la base de datos"""
<|body_0|>
def clean(self):
"""Chequeos posteriores en los que puede haber varios campos involucrados"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginForm:
def clean_documento(self):
"""Chequea que el usuario exista en la base de datos"""
self.cleaned_data['documento']
documento = self.cleaned_data['documento']
if not re.search('^\\w+$', documento):
raise forms.ValidationError(u'Este campo sólo puede contene... | the_stack_v2_python_sparse | meregistro/apps/seguridad/forms/LoginForm.py | MERegistro/meregistro | train | 0 | |
495e39976d726bc69633ac7a16e49d0f827f46d3 | [
"pysam.Samfile.__init__(self, inputFname, openMode, **keywords)\nself.inputFname = inputFname\nself.openMode = openMode\n'\\n\\t\\tfrom pymodule import ProcessOptions\\n\\t\\tself.ad = ProcessOptions.process_function_arguments(keywords, self.option_default_dict, error_doc=self.__doc__, \\t\\t\\t\\t\\t\\t\\t\\t\\t\\... | <|body_start_0|>
pysam.Samfile.__init__(self, inputFname, openMode, **keywords)
self.inputFname = inputFname
self.openMode = openMode
'\n\t\tfrom pymodule import ProcessOptions\n\t\tself.ad = ProcessOptions.process_function_arguments(keywords, self.option_default_dict, error_doc=self.__d... | BamFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BamFile:
def __init__(self, inputFname, openMode, **keywords):
"""2011-7-11"""
<|body_0|>
def traverseBamByRead(self, processor=None):
"""2011-7-10 add samfile to param_obj 2011-2-8 a traverser used by other functions"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_006547 | 4,113 | no_license | [
{
"docstring": "2011-7-11",
"name": "__init__",
"signature": "def __init__(self, inputFname, openMode, **keywords)"
},
{
"docstring": "2011-7-10 add samfile to param_obj 2011-2-8 a traverser used by other functions",
"name": "traverseBamByRead",
"signature": "def traverseBamByRead(self, ... | 2 | stack_v2_sparse_classes_30k_train_005624 | Implement the Python class `BamFile` described below.
Class description:
Implement the BamFile class.
Method signatures and docstrings:
- def __init__(self, inputFname, openMode, **keywords): 2011-7-11
- def traverseBamByRead(self, processor=None): 2011-7-10 add samfile to param_obj 2011-2-8 a traverser used by other... | Implement the Python class `BamFile` described below.
Class description:
Implement the BamFile class.
Method signatures and docstrings:
- def __init__(self, inputFname, openMode, **keywords): 2011-7-11
- def traverseBamByRead(self, processor=None): 2011-7-10 add samfile to param_obj 2011-2-8 a traverser used by other... | b9333b85daed71032a1cba766585d0be1986ffdb | <|skeleton|>
class BamFile:
def __init__(self, inputFname, openMode, **keywords):
"""2011-7-11"""
<|body_0|>
def traverseBamByRead(self, processor=None):
"""2011-7-10 add samfile to param_obj 2011-2-8 a traverser used by other functions"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BamFile:
def __init__(self, inputFname, openMode, **keywords):
"""2011-7-11"""
pysam.Samfile.__init__(self, inputFname, openMode, **keywords)
self.inputFname = inputFname
self.openMode = openMode
'\n\t\tfrom pymodule import ProcessOptions\n\t\tself.ad = ProcessOptions.p... | the_stack_v2_python_sparse | pymodule/yhio/BamFile.py | polyactis/gwasmodules | train | 0 | |
8ac11adea760a58f8990c4b99ab400fbe1707667 | [
"extension_map = {'json': (json.dump, json.load), 'toml': (toml.dump, toml.load)}\nif ext not in extension_map:\n known_formats = ','.join(extension_map.keys())\n raise ValueError(f'Unknown config format. Supported formats: {known_formats}')\nreturn extension_map[ext]",
"extension = config_path.name.split('... | <|body_start_0|>
extension_map = {'json': (json.dump, json.load), 'toml': (toml.dump, toml.load)}
if ext not in extension_map:
known_formats = ','.join(extension_map.keys())
raise ValueError(f'Unknown config format. Supported formats: {known_formats}')
return extension_ma... | User configuration object. | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""User configuration object."""
def get_serde_by_extension(cls, ext: str) -> Iterable[Callable[..., Dict[str, Any]]]:
"""Get serializer and deserializer for the given file extension. :param ext: file extension. :raises ValueError: if unknown extension was passed. :return: se... | stack_v2_sparse_classes_36k_train_006548 | 2,564 | permissive | [
{
"docstring": "Get serializer and deserializer for the given file extension. :param ext: file extension. :raises ValueError: if unknown extension was passed. :return: serializer and deserializer.",
"name": "get_serde_by_extension",
"signature": "def get_serde_by_extension(cls, ext: str) -> Iterable[Cal... | 3 | stack_v2_sparse_classes_30k_train_003062 | Implement the Python class `Config` described below.
Class description:
User configuration object.
Method signatures and docstrings:
- def get_serde_by_extension(cls, ext: str) -> Iterable[Callable[..., Dict[str, Any]]]: Get serializer and deserializer for the given file extension. :param ext: file extension. :raises... | Implement the Python class `Config` described below.
Class description:
User configuration object.
Method signatures and docstrings:
- def get_serde_by_extension(cls, ext: str) -> Iterable[Callable[..., Dict[str, Any]]]: Get serializer and deserializer for the given file extension. :param ext: file extension. :raises... | 5b79eacb32506b6eda5861df4b5f71b611c5dfa3 | <|skeleton|>
class Config:
"""User configuration object."""
def get_serde_by_extension(cls, ext: str) -> Iterable[Callable[..., Dict[str, Any]]]:
"""Get serializer and deserializer for the given file extension. :param ext: file extension. :raises ValueError: if unknown extension was passed. :return: se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""User configuration object."""
def get_serde_by_extension(cls, ext: str) -> Iterable[Callable[..., Dict[str, Any]]]:
"""Get serializer and deserializer for the given file extension. :param ext: file extension. :raises ValueError: if unknown extension was passed. :return: serializer and ... | the_stack_v2_python_sparse | music_bg/config.py | music-bg/music_bg | train | 3 |
029e846cc4255c084116de311e7af8dc11a379d3 | [
"jwt_value = self.get_jwt_value(request)\nif jwt_value is None:\n return None\ntry:\n payload = jwt_decode_handler(jwt_value)\nexcept jwt.ExpiredSignature:\n msg = _('Signature has expired.')\n raise exceptions.AuthenticationFailed(msg)\nexcept jwt.DecodeError:\n msg = _('Error decoding signature.')\... | <|body_start_0|>
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg... | Token based authentication using the JSON Web Token standard. | BaseJSONWebTokenAuthentication | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
... | stack_v2_sparse_classes_36k_train_006549 | 4,921 | permissive | [
{
"docstring": "Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Returns an active user that matches the payload's u... | 2 | stack_v2_sparse_classes_30k_train_014242 | Implement the Python class `BaseJSONWebTokenAuthentication` described below.
Class description:
Token based authentication using the JSON Web Token standard.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-ba... | Implement the Python class `BaseJSONWebTokenAuthentication` described below.
Class description:
Token based authentication using the JSON Web Token standard.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-ba... | c62eba7fcc08b06485b845089e79b3ce236ec1ec | <|skeleton|>
class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
jwt_value = s... | the_stack_v2_python_sparse | authenticate/authentication.py | OckiFals/cloud-platform | train | 1 |
bff7b017dfa54596a7b68196d6fdf2e44896c215 | [
"super(PendingSponsorshipLevelListView, self).__init__()\nself.project = None\nself.project_slug = None",
"context = super(PendingSponsorshipLevelListView, self).get_context_data(**kwargs)\ncontext['num_sponsorshiplevels'] = self.get_queryset().count()\ncontext['unapproved'] = True\ncontext['project_slug'] = self... | <|body_start_0|>
super(PendingSponsorshipLevelListView, self).__init__()
self.project = None
self.project_slug = None
<|end_body_0|>
<|body_start_1|>
context = super(PendingSponsorshipLevelListView, self).get_context_data(**kwargs)
context['num_sponsorshiplevels'] = self.get_que... | List view for pending Sponsor. | PendingSponsorshipLevelListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PendingSponsorshipLevelListView:
"""List view for pending Sponsor."""
def __init__(self):
"""We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the valu... | stack_v2_sparse_classes_36k_train_006550 | 17,162 | no_license | [
{
"docstring": "We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the values in self.get_context_data.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_008234 | Implement the Python class `PendingSponsorshipLevelListView` described below.
Class description:
List view for pending Sponsor.
Method signatures and docstrings:
- def __init__(self): We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the f... | Implement the Python class `PendingSponsorshipLevelListView` described below.
Class description:
List view for pending Sponsor.
Method signatures and docstrings:
- def __init__(self): We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the f... | ca489c38fdfde29f75c9c1e7f4b4c55d78d91c79 | <|skeleton|>
class PendingSponsorshipLevelListView:
"""List view for pending Sponsor."""
def __init__(self):
"""We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PendingSponsorshipLevelListView:
"""List view for pending Sponsor."""
def __init__(self):
"""We overload __init__ in order to declare self.project and self.project_slug. Both are then defined in self.get_queryset which is the first method called. This means we can then reuse the values in self.ge... | the_stack_v2_python_sparse | django_project/changes/views/sponsorship_level.py | gitter-badger/projecta | train | 0 |
92c08a8be8446a972bc2a0766cf129cc85174325 | [
"cli.JobPollReportCbBase.__init__(self)\nself._abort_check_fn = abort_check_fn\nself._remote_import_fn = remote_import_fn",
"if log_type == constants.ELOG_REMOTE_IMPORT:\n logging.debug('Received remote import information')\n if not self._remote_import_fn:\n raise RuntimeError('Received unexpected re... | <|body_start_0|>
cli.JobPollReportCbBase.__init__(self)
self._abort_check_fn = abort_check_fn
self._remote_import_fn = remote_import_fn
<|end_body_0|>
<|body_start_1|>
if log_type == constants.ELOG_REMOTE_IMPORT:
logging.debug('Received remote import information')
... | MoveJobPollReportCb | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoveJobPollReportCb:
def __init__(self, abort_check_fn, remote_import_fn):
"""Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whether move is aborted @type remote_import_fn: callable or None @param remote_import_fn: Callback for reporting r... | stack_v2_sparse_classes_36k_train_006551 | 40,615 | permissive | [
{
"docstring": "Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whether move is aborted @type remote_import_fn: callable or None @param remote_import_fn: Callback for reporting received remote import information",
"name": "__init__",
"signature": "def __in... | 3 | null | Implement the Python class `MoveJobPollReportCb` described below.
Class description:
Implement the MoveJobPollReportCb class.
Method signatures and docstrings:
- def __init__(self, abort_check_fn, remote_import_fn): Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whethe... | Implement the Python class `MoveJobPollReportCb` described below.
Class description:
Implement the MoveJobPollReportCb class.
Method signatures and docstrings:
- def __init__(self, abort_check_fn, remote_import_fn): Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whethe... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class MoveJobPollReportCb:
def __init__(self, abort_check_fn, remote_import_fn):
"""Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whether move is aborted @type remote_import_fn: callable or None @param remote_import_fn: Callback for reporting r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MoveJobPollReportCb:
def __init__(self, abort_check_fn, remote_import_fn):
"""Initializes this class. @type abort_check_fn: callable @param abort_check_fn: Function to check whether move is aborted @type remote_import_fn: callable or None @param remote_import_fn: Callback for reporting received remote... | the_stack_v2_python_sparse | tools/move-instance | ganeti/ganeti | train | 465 | |
815ff1b1e1f956c3e1e5ded8e459839098b229b8 | [
"self.indices_entrenamiento = None\nself.obt_indices_entrenamiento(coleccion, porcentaje_coleccion)\nmat_entrenamiento = coleccion.obt_subconjunto(self.indices_entrenamiento)\nself.muestra_promedio = np.mean(mat_entrenamiento, axis=1, dtype='float64')\nmat_entrenamiento -= self.muestra_promedio\nmat_covarianza = ma... | <|body_start_0|>
self.indices_entrenamiento = None
self.obt_indices_entrenamiento(coleccion, porcentaje_coleccion)
mat_entrenamiento = coleccion.obt_subconjunto(self.indices_entrenamiento)
self.muestra_promedio = np.mean(mat_entrenamiento, axis=1, dtype='float64')
mat_entrenamien... | Entrenamiento | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Entrenamiento:
def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores):
"""Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entrenamiento es encontrar los autovectores/caras que componen el autoespacio, además de sus respectivas p... | stack_v2_sparse_classes_36k_train_006552 | 3,896 | no_license | [
{
"docstring": "Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entrenamiento es encontrar los autovectores/caras que componen el autoespacio, además de sus respectivas proyecciones (o pesos) Además se guarda la muestra promedio para centrar las imagenes al origen cuan... | 2 | stack_v2_sparse_classes_30k_train_007453 | Implement the Python class `Entrenamiento` described below.
Class description:
Implement the Entrenamiento class.
Method signatures and docstrings:
- def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores): Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entr... | Implement the Python class `Entrenamiento` described below.
Class description:
Implement the Entrenamiento class.
Method signatures and docstrings:
- def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores): Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entr... | 30513a8b81cbb97ee475855c75628419a207c0e0 | <|skeleton|>
class Entrenamiento:
def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores):
"""Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entrenamiento es encontrar los autovectores/caras que componen el autoespacio, además de sus respectivas p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Entrenamiento:
def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores):
"""Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entrenamiento es encontrar los autovectores/caras que componen el autoespacio, además de sus respectivas proyecciones (o... | the_stack_v2_python_sparse | Codigo/modelo/entrenamiento.py | JulianSalinas/eigenfaces-qa | train | 0 | |
dff6cc678da2a5c9879d2ecc49e367c7ef91744a | [
"if scale <= 0.0:\n raise ValueError('<scale> must be positive float.')\nmode = mode.lower()\nif mode not in {'fan_in', 'fan_out', 'fan_avg'}:\n raise ValueError('Invalid <mode> argument: ' + mode)\ndistribution = distribution.lower()\nif distribution not in {'normal', 'uniform'}:\n raise ValueError('Inval... | <|body_start_0|>
if scale <= 0.0:
raise ValueError('<scale> must be positive float.')
mode = mode.lower()
if mode not in {'fan_in', 'fan_out', 'fan_avg'}:
raise ValueError('Invalid <mode> argument: ' + mode)
distribution = distribution.lower()
if distribut... | Fill tensor from a scaled random distribution. | VarianceScaling | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VarianceScaling:
"""Fill tensor from a scaled random distribution."""
def __init__(self, scale=1.0, mode='fan_out', distribution='normal', dtype='float32'):
"""Create a ``RandomNormal`` initializer. Parameters ---------- scale : float, optional, default=1 The scale factor to distribu... | stack_v2_sparse_classes_36k_train_006553 | 11,858 | permissive | [
{
"docstring": "Create a ``RandomNormal`` initializer. Parameters ---------- scale : float, optional, default=1 The scale factor to distribution. mode : {'fan_in', 'fan_out', 'fan_avg'}, optional The mode for adapting to shape. distribution : {'normal', 'uniform'}, optional The optional distribution to generate... | 2 | null | Implement the Python class `VarianceScaling` described below.
Class description:
Fill tensor from a scaled random distribution.
Method signatures and docstrings:
- def __init__(self, scale=1.0, mode='fan_out', distribution='normal', dtype='float32'): Create a ``RandomNormal`` initializer. Parameters ---------- scale ... | Implement the Python class `VarianceScaling` described below.
Class description:
Fill tensor from a scaled random distribution.
Method signatures and docstrings:
- def __init__(self, scale=1.0, mode='fan_out', distribution='normal', dtype='float32'): Create a ``RandomNormal`` initializer. Parameters ---------- scale ... | 3dfb6ea55d90d2fb2da9b1b471f5e1e7d7667810 | <|skeleton|>
class VarianceScaling:
"""Fill tensor from a scaled random distribution."""
def __init__(self, scale=1.0, mode='fan_out', distribution='normal', dtype='float32'):
"""Create a ``RandomNormal`` initializer. Parameters ---------- scale : float, optional, default=1 The scale factor to distribu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VarianceScaling:
"""Fill tensor from a scaled random distribution."""
def __init__(self, scale=1.0, mode='fan_out', distribution='normal', dtype='float32'):
"""Create a ``RandomNormal`` initializer. Parameters ---------- scale : float, optional, default=1 The scale factor to distribution. mode : ... | the_stack_v2_python_sparse | tensorflow/core/ops/init_ops.py | zhengruiguo/dragon | train | 0 |
9dd649ea9d7f22706db7ea61ddfd5651dd30b3bb | [
"host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession)\nrounded_time_shift = host._FTPHost__rounded_time_shift\ntest_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), (-1500, 0), (1800, 3600), (-1800, -3600), (2000, 3600), (-2000, -3600), (5 * 3600 - 100, 5 * 3600), (-5 * 3600 + 100, -5 * 3600)]\nf... | <|body_start_0|>
host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession)
rounded_time_shift = host._FTPHost__rounded_time_shift
test_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), (-1500, 0), (1800, 3600), (-1800, -3600), (2000, 3600), (-2000, -3600), (5 * 3600 - 100, 5 * 3600)... | TestTimeShift | [
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTimeShift:
def test_rounded_time_shift(self):
"""Test if time shift is rounded correctly."""
<|body_0|>
def test_assert_valid_time_shift(self):
"""Test time shift sanity checks."""
<|body_1|>
def test_synchronize_times(self):
"""Test time syn... | stack_v2_sparse_classes_36k_train_006554 | 21,191 | permissive | [
{
"docstring": "Test if time shift is rounded correctly.",
"name": "test_rounded_time_shift",
"signature": "def test_rounded_time_shift(self)"
},
{
"docstring": "Test time shift sanity checks.",
"name": "test_assert_valid_time_shift",
"signature": "def test_assert_valid_time_shift(self)"... | 3 | stack_v2_sparse_classes_30k_train_010346 | Implement the Python class `TestTimeShift` described below.
Class description:
Implement the TestTimeShift class.
Method signatures and docstrings:
- def test_rounded_time_shift(self): Test if time shift is rounded correctly.
- def test_assert_valid_time_shift(self): Test time shift sanity checks.
- def test_synchron... | Implement the Python class `TestTimeShift` described below.
Class description:
Implement the TestTimeShift class.
Method signatures and docstrings:
- def test_rounded_time_shift(self): Test if time shift is rounded correctly.
- def test_assert_valid_time_shift(self): Test time shift sanity checks.
- def test_synchron... | c1164ba7c5a35ce5aef43fdffbebaab6ccc21597 | <|skeleton|>
class TestTimeShift:
def test_rounded_time_shift(self):
"""Test if time shift is rounded correctly."""
<|body_0|>
def test_assert_valid_time_shift(self):
"""Test time shift sanity checks."""
<|body_1|>
def test_synchronize_times(self):
"""Test time syn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTimeShift:
def test_rounded_time_shift(self):
"""Test if time shift is rounded correctly."""
host = _test_base.ftp_host_factory(session_factory=TimeShiftMockSession)
rounded_time_shift = host._FTPHost__rounded_time_shift
test_data = [(0, 0), (0.1, 0), (-0.1, 0), (1500, 0), ... | the_stack_v2_python_sparse | python examples/software/ftputil-2.2.3/_test_ftputil.py | gansell/python | train | 0 | |
84efe49c9c908c131952f8070c2d00f556ce3776 | [
"self.url = api_reverse('authentication:email_password')\nself.register_url = api_reverse('authentication:user-registration')\nself.user = {'user': {'username': 'kevin', 'email': 'koechkevin92@gmail.com', 'password': 'Kevin12345'}}\nself.client.post(self.register_url, self.user, format='json')\nUser.is_active = Tru... | <|body_start_0|>
self.url = api_reverse('authentication:email_password')
self.register_url = api_reverse('authentication:user-registration')
self.user = {'user': {'username': 'kevin', 'email': 'koechkevin92@gmail.com', 'password': 'Kevin12345'}}
self.client.post(self.register_url, self.u... | test for class to send password reset link to email | TestEmailSent | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEmailSent:
"""test for class to send password reset link to email"""
def setUp(self):
"""set up method to test email to be sent endpoint"""
<|body_0|>
def test_unregistered_email(self):
"""case where unregistered user tries to request a password"""
<|... | stack_v2_sparse_classes_36k_train_006555 | 7,001 | permissive | [
{
"docstring": "set up method to test email to be sent endpoint",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "case where unregistered user tries to request a password",
"name": "test_unregistered_email",
"signature": "def test_unregistered_email(self)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_015224 | Implement the Python class `TestEmailSent` described below.
Class description:
test for class to send password reset link to email
Method signatures and docstrings:
- def setUp(self): set up method to test email to be sent endpoint
- def test_unregistered_email(self): case where unregistered user tries to request a p... | Implement the Python class `TestEmailSent` described below.
Class description:
test for class to send password reset link to email
Method signatures and docstrings:
- def setUp(self): set up method to test email to be sent endpoint
- def test_unregistered_email(self): case where unregistered user tries to request a p... | a14ffcac494053ff338aa7f0a5524062964a49cc | <|skeleton|>
class TestEmailSent:
"""test for class to send password reset link to email"""
def setUp(self):
"""set up method to test email to be sent endpoint"""
<|body_0|>
def test_unregistered_email(self):
"""case where unregistered user tries to request a password"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestEmailSent:
"""test for class to send password reset link to email"""
def setUp(self):
"""set up method to test email to be sent endpoint"""
self.url = api_reverse('authentication:email_password')
self.register_url = api_reverse('authentication:user-registration')
self.... | the_stack_v2_python_sparse | authors/apps/authentication/test_password_reset.py | andela/ah-shakas | train | 1 |
7eb78aee2de88b59e155ffc98ed669cb0bdcce36 | [
"acc = 0\nfor num in nums:\n acc ^= num\nreturn acc",
"from functools import reduce\nfrom operator import xor\nreturn reduce(xor, nums)"
] | <|body_start_0|>
acc = 0
for num in nums:
acc ^= num
return acc
<|end_body_0|>
<|body_start_1|>
from functools import reduce
from operator import xor
return reduce(xor, nums)
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4"""
<|body_0|>
def singleNumber_(self, nums):
"""functional (folding)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_006556 | 735 | no_license | [
{
"docstring": "O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": "functional (folding)",
"name": "singleNumber_",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4
- def singleNumber_(self, nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4
- def singleNumber_(self, nu... | 5a401250e88926235f581e6c004d1a4acb44230d | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4"""
<|body_0|>
def singleNumber_(self, nums):
"""functional (folding)"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
"""O(N) time and O(1) space. (iterate all num, and do not use extra space) 0 ^ 1 ^ 2 ^ 1 ^ 2 = 0 0 ^ 1 ^ 2 ^ 4 ^ 1 ^ 2 = 4"""
acc = 0
for num in nums:
acc ^= num
return acc
def singleNumber_(self, nums):
"""functi... | the_stack_v2_python_sparse | leetcode/p0136/solve.py | b1ueskydragon/PythonGround | train | 3 | |
9a15a4d264120adf4719a4d85c7c8081971b7d22 | [
"super(Encoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, self.dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.dropout = tf.keras.layers.Dropout(drop_rate)\nself.blocks = []\nfor iter in range(self.N):\n encoder_block = Enc... | <|body_start_0|>
super(Encoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, self.dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.dropout = tf.keras.layers.Dropout(drop_rate)
self.bl... | Transformer Encoder | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Transformer Encoder"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the number of heads - hidden: the number of hidden units in the f... | stack_v2_sparse_classes_36k_train_006557 | 2,668 | no_license | [
{
"docstring": "Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the number of heads - hidden: the number of hidden units in the fully connected layer - input_vocab: the size of the input vocabulary - max_seq_len: the maximum sequence length possible - drop_r... | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Transformer Encoder
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the numb... | Implement the Python class `Encoder` described below.
Class description:
Transformer Encoder
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the numb... | 4a7a8ff0c4f785656a395d0abf4f182ce1fef5bc | <|skeleton|>
class Encoder:
"""Transformer Encoder"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the number of heads - hidden: the number of hidden units in the f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Transformer Encoder"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor - N: the number of blocks in the encoder - dm: the dimensionality of the model - h: the number of heads - hidden: the number of hidden units in the fully connecte... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/9-transformer_encoder.py | xica369/holbertonschool-machine_learning | train | 0 |
8d6a9f254f5f172d59c528d8e8f6dd584e13f435 | [
"tk.Frame.__init__(self, container)\nf = Figure(figsize=(10, 10), dpi=100)\nself.subp_1 = f.add_subplot(211)\nself.subp_2 = f.add_subplot(212)\ngraph_genotype_GUI(genotype, self.subp_2)\nnorm_in = getNormalizedInputs(num_x, num_y)\noutputs = []\nfor ins in norm_in:\n outputs.append(genotype.getOutput(ins)[0])\no... | <|body_start_0|>
tk.Frame.__init__(self, container)
f = Figure(figsize=(10, 10), dpi=100)
self.subp_1 = f.add_subplot(211)
self.subp_2 = f.add_subplot(212)
graph_genotype_GUI(genotype, self.subp_2)
norm_in = getNormalizedInputs(num_x, num_y)
outputs = []
f... | Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN | SliderPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SliderPage:
"""Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN"""
def __init__(self, container, master, genotype):
"""Constructor for slider frame"""
<|body_0|>
def add_sliders(self):
"""Adds all needed sl... | stack_v2_sparse_classes_36k_train_006558 | 11,786 | no_license | [
{
"docstring": "Constructor for slider frame",
"name": "__init__",
"signature": "def __init__(self, container, master, genotype)"
},
{
"docstring": "Adds all needed slider items to the slider page of the GUI",
"name": "add_sliders",
"signature": "def add_sliders(self)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_016593 | Implement the Python class `SliderPage` described below.
Class description:
Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN
Method signatures and docstrings:
- def __init__(self, container, master, genotype): Constructor for slider frame
- def add_sliders(self... | Implement the Python class `SliderPage` described below.
Class description:
Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN
Method signatures and docstrings:
- def __init__(self, container, master, genotype): Constructor for slider frame
- def add_sliders(self... | 317b615e39df5999f2fd3d5e7dd0af7d54aee6c8 | <|skeleton|>
class SliderPage:
"""Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN"""
def __init__(self, container, master, genotype):
"""Constructor for slider frame"""
<|body_0|>
def add_sliders(self):
"""Adds all needed sl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SliderPage:
"""Class containing frame for GUI widget that allows users to move sliders to change weights within the CPPN"""
def __init__(self, container, master, genotype):
"""Constructor for slider frame"""
tk.Frame.__init__(self, container)
f = Figure(figsize=(10, 10), dpi=100)
... | the_stack_v2_python_sparse | FULL_CPPN_playground.py | wolfecameron/CPPN_springopt | train | 4 |
d764cb7bd2c69d7ee18c303fd60e86d5d5b505af | [
"super().__init__(**kwargs)\nself.conv1d_transpose = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(kernel_size, 1), strides=(strides, 1), padding='same', kernel_initializer=get_initializer(initializer_seed))\nif is_weight_norm:\n self.conv1d_transpose = WeightNormalization(self.conv1d_transpose)"... | <|body_start_0|>
super().__init__(**kwargs)
self.conv1d_transpose = tf.keras.layers.Conv2DTranspose(filters=filters, kernel_size=(kernel_size, 1), strides=(strides, 1), padding='same', kernel_initializer=get_initializer(initializer_seed))
if is_weight_norm:
self.conv1d_transpose = We... | Tensorflow ConvTranspose1d module. | TFConvTranspose1d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFConvTranspose1d:
"""Tensorflow ConvTranspose1d module."""
def __init__(self, filters, kernel_size, strides, padding, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFConvTranspose1d( module. Args: filters (int): Number of filters. kernel_size (int): kernel size. strides... | stack_v2_sparse_classes_36k_train_006559 | 17,807 | permissive | [
{
"docstring": "Initialize TFConvTranspose1d( module. Args: filters (int): Number of filters. kernel_size (int): kernel size. strides (int): Stride width. padding (str): Padding type (\"same\" or \"valid\").",
"name": "__init__",
"signature": "def __init__(self, filters, kernel_size, strides, padding, i... | 2 | stack_v2_sparse_classes_30k_train_020976 | Implement the Python class `TFConvTranspose1d` described below.
Class description:
Tensorflow ConvTranspose1d module.
Method signatures and docstrings:
- def __init__(self, filters, kernel_size, strides, padding, is_weight_norm, initializer_seed, **kwargs): Initialize TFConvTranspose1d( module. Args: filters (int): N... | Implement the Python class `TFConvTranspose1d` described below.
Class description:
Tensorflow ConvTranspose1d module.
Method signatures and docstrings:
- def __init__(self, filters, kernel_size, strides, padding, is_weight_norm, initializer_seed, **kwargs): Initialize TFConvTranspose1d( module. Args: filters (int): N... | 136877136355c82d7ba474ceb7a8f133bd84767e | <|skeleton|>
class TFConvTranspose1d:
"""Tensorflow ConvTranspose1d module."""
def __init__(self, filters, kernel_size, strides, padding, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFConvTranspose1d( module. Args: filters (int): Number of filters. kernel_size (int): kernel size. strides... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFConvTranspose1d:
"""Tensorflow ConvTranspose1d module."""
def __init__(self, filters, kernel_size, strides, padding, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFConvTranspose1d( module. Args: filters (int): Number of filters. kernel_size (int): kernel size. strides (int): Strid... | the_stack_v2_python_sparse | tensorflow_tts/models/melgan.py | TensorSpeech/TensorFlowTTS | train | 2,889 |
d6cf8fb5d419fd7a396076d106ef68f2f577b651 | [
"self.header.append(CDF_LABEL)\nkey_list = []\nfor cube in self.cube_list:\n scenario = self.vocab.get_collection_term_label(InputType.SCENARIO, cube.attributes['scenario'])\n var = self.input_data.get_value_label(InputType.VARIABLE)[0]\n self.header.append('{var}({scenario})'.format(scenario=scenario, var... | <|body_start_0|>
self.header.append(CDF_LABEL)
key_list = []
for cube in self.cube_list:
scenario = self.vocab.get_collection_term_label(InputType.SCENARIO, cube.attributes['scenario'])
var = self.input_data.get_value_label(InputType.VARIABLE)[0]
self.header.a... | The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self). | CdfCsvWriter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
<|body_0|>
def _read_percentile_cube(self, cube, key_list):
"""Slice... | stack_v2_sparse_classes_36k_train_006560 | 1,895 | permissive | [
{
"docstring": "Write out the data, in CSV format, associated with a CDF plot.",
"name": "_write_csv",
"signature": "def _write_csv(self)"
},
{
"docstring": "Slice the cube over 'percentile' and update data_dict",
"name": "_read_percentile_cube",
"signature": "def _read_percentile_cube(s... | 2 | stack_v2_sparse_classes_30k_train_021415 | Implement the Python class `CdfCsvWriter` described below.
Class description:
The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self).
Method signatures and docstrings:
- def _write_csv(self): Write out the data, in CSV format, associated with a CDF plot.
- def _read_percentile_cube(self, c... | Implement the Python class `CdfCsvWriter` described below.
Class description:
The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self).
Method signatures and docstrings:
- def _write_csv(self): Write out the data, in CSV format, associated with a CDF plot.
- def _read_percentile_cube(self, c... | 2d9d6e9158458503c1bf9641d106402e18dc681f | <|skeleton|>
class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
<|body_0|>
def _read_percentile_cube(self, cube, key_list):
"""Slice... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CdfCsvWriter:
"""The CDF CSV writer class. This class extends BaseCsvWriter with a _write_csv(self)."""
def _write_csv(self):
"""Write out the data, in CSV format, associated with a CDF plot."""
self.header.append(CDF_LABEL)
key_list = []
for cube in self.cube_list:
... | the_stack_v2_python_sparse | ukcp_dp/file_writers/_write_csv_cdf.py | ukcp-data/ukcp-data-processor | train | 4 |
4c68e2db8cd9d4275f5d41752c4477c18c92fcb6 | [
"for i in xrange(len(digits) - 1, -1, -1):\n digits[i] += 1\n if digits[i] < 10:\n return digits\n else:\n digits[i] -= 10\ndigits.insert(0, 1)\nreturn digits",
"digits.reverse()\ndigits[0] += 1\ncarry = 0\nfor i in xrange(len(digits)):\n digits[i] += carry\n if digits[i] > 9:\n ... | <|body_start_0|>
for i in xrange(len(digits) - 1, -1, -1):
digits[i] += 1
if digits[i] < 10:
return digits
else:
digits[i] -= 10
digits.insert(0, 1)
return digits
<|end_body_0|>
<|body_start_1|>
digits.reverse()
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
"""Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits"""
<|body_0|>
def plusOne(self, digits):
"""Good habit to reverse it first :param digits: :r... | stack_v2_sparse_classes_36k_train_006561 | 1,414 | permissive | [
{
"docstring": "Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": "Good habit to reverse it first :param digits: :return:",
"na... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits
- def plusOne(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits
- def plusOne(se... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def plusOne(self, digits):
"""Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits"""
<|body_0|>
def plusOne(self, digits):
"""Good habit to reverse it first :param digits: :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits):
"""Math Basics of all other questions like adding, multiplying. :param digits: a list of integer digits :return: a list of integer digits"""
for i in xrange(len(digits) - 1, -1, -1):
digits[i] += 1
if digits[i] < 10:
... | the_stack_v2_python_sparse | 065 Plus One.py | Aminaba123/LeetCode | train | 1 | |
68f103121e26adb536b71f8abe698682ec4a691a | [
"self.event_type = event_type\nself.sources = sources\nif not isinstance(mc_info, list):\n mc_info = [mc_info]\nself.mc_info = mc_info",
"if isinstance(other, MCRecord):\n new_ev_type = self.event_type + other.event_type\n new_src = self.sources + other.sources\n new_mcinfo = self.mc_info + other.mc_i... | <|body_start_0|>
self.event_type = event_type
self.sources = sources
if not isinstance(mc_info, list):
mc_info = [mc_info]
self.mc_info = mc_info
<|end_body_0|>
<|body_start_1|>
if isinstance(other, MCRecord):
new_ev_type = self.event_type + other.event_t... | Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information. | MCRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCRecord:
"""Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information."""
def __init__(self, event_type, sources, mc_info):
"""Initialize MCRecord."""... | stack_v2_sparse_classes_36k_train_006562 | 972 | no_license | [
{
"docstring": "Initialize MCRecord.",
"name": "__init__",
"signature": "def __init__(self, event_type, sources, mc_info)"
},
{
"docstring": "Combine two MCRecords.",
"name": "__add__",
"signature": "def __add__(self, other)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016865 | Implement the Python class `MCRecord` described below.
Class description:
Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `MCRecord` described below.
Class description:
Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information.
Method signatures and docstrings:
- def __init__(sel... | 24f847a1ab9bfe3b1bafe1a19569f13fede7f2f6 | <|skeleton|>
class MCRecord:
"""Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information."""
def __init__(self, event_type, sources, mc_info):
"""Initialize MCRecord."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MCRecord:
"""Stores MC Truth information. Properties: event_type: str sources: List[PhotonSource_] List of photon sources mc_info: List[Dict[str, Any]] List of dictionaries containing MCTruth information."""
def __init__(self, event_type, sources, mc_info):
"""Initialize MCRecord."""
self... | the_stack_v2_python_sparse | gnn_testbed/event_generation/mc_record.py | chrhck/gnn_testbed | train | 0 |
c2dad5c69981fc815e3c0878c4b852f0c3da5a04 | [
"assert da.getDim() == 2\nself.da = da\nself.prob = prob\nself.factor = factor\nself.localX = da.createLocalVec()",
"self.da.globalToLocal(X, self.localX)\nx = self.da.getVecArray(self.localX)\nf = self.da.getVecArray(F)\n(xs, xe), (ys, ye) = self.da.getRanges()\nfor j in range(ys, ye):\n for i in range(xs, xe... | <|body_start_0|>
assert da.getDim() == 2
self.da = da
self.prob = prob
self.factor = factor
self.localX = da.createLocalVec()
<|end_body_0|>
<|body_start_1|>
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVecArra... | Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES | GS_reaction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
<|body_0|>
def formF... | stack_v2_sparse_classes_36k_train_006563 | 20,605 | permissive | [
{
"docstring": "Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)",
"name": "__init__",
"signature": "def __init__(self, da, prob, factor)"
},
{
"docstring": "Function to evaluate the residual for the Newton solver This function should be equal t... | 3 | null | Implement the Python class `GS_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor: tem... | Implement the Python class `GS_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, prob, factor): Initialization routine Args: da: DMDA object prob: problem instance factor: tem... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
<|body_0|>
def formF... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GS_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, prob, factor):
"""Initialization routine Args: da: DMDA object prob: problem instance factor: temporal factor (dt*Qd)"""
assert da.getDim() == 2
self.d... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/GrayScott_2D_PETSc_periodic.py | Parallel-in-Time/pySDC | train | 30 |
a5d7de3a132d7119ee8682384c55f22ad4f90792 | [
"size, res, path = (len(candidates), [], [])\ncandidates.sort()\n\ndef dfs(candidates, begin, target, res, path):\n if target == 0:\n res.append(path[:])\n return\n for i in range(begin, size):\n if candidates[i] > target:\n break\n if i > begin and candidates[i] == cand... | <|body_start_0|>
size, res, path = (len(candidates), [], [])
candidates.sort()
def dfs(candidates, begin, target, res, path):
if target == 0:
res.append(path[:])
return
for i in range(begin, size):
if candidates[i] > target... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
"""减法思维"""
<|body_0|>
def combinationSum2_1(self, candidates: List[int], target: int) -> List[List[int]]:
"""加法思维"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_006564 | 2,215 | no_license | [
{
"docstring": "减法思维",
"name": "combinationSum2",
"signature": "def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]"
},
{
"docstring": "加法思维",
"name": "combinationSum2_1",
"signature": "def combinationSum2_1(self, candidates: List[int], target: int) -> List[L... | 2 | stack_v2_sparse_classes_30k_train_008127 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 减法思维
- def combinationSum2_1(self, candidates: List[int], target: int) -> List[List[int]]: 加法思维 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 减法思维
- def combinationSum2_1(self, candidates: List[int], target: int) -> List[List[int]]: 加法思维
... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
"""减法思维"""
<|body_0|>
def combinationSum2_1(self, candidates: List[int], target: int) -> List[List[int]]:
"""加法思维"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
"""减法思维"""
size, res, path = (len(candidates), [], [])
candidates.sort()
def dfs(candidates, begin, target, res, path):
if target == 0:
res.append(path[:])
... | the_stack_v2_python_sparse | algorithm/leetcode/backtracking/07-组合总和Ⅱ.py | lxconfig/UbuntuCode_bak | train | 0 | |
e997c1f2b04618bc041ea64344df7098fce80640 | [
"self.name = name\nself.args = []\nfor arg in args:\n self.args.append(arg)",
"s = self.name\nfor arg in self.args:\n s += ' '\n s += str(arg)\nreturn s",
"s = self.name.encode()\nfor arg in self.args:\n s += ESCAPE_CHARACTER + arg.encode()\ns += b'\\n'\ntry:\n verbose('Internal: Sending [', s.de... | <|body_start_0|>
self.name = name
self.args = []
for arg in args:
self.args.append(arg)
<|end_body_0|>
<|body_start_1|>
s = self.name
for arg in self.args:
s += ' '
s += str(arg)
return s
<|end_body_1|>
<|body_start_2|>
s = se... | Message | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
def __init__(self, name, *args):
"""Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command."""
<|body_0|>
def __str__(self) -> str:
"""Converts this object to a String object. :return: This object as a St... | stack_v2_sparse_classes_36k_train_006565 | 1,167 | permissive | [
{
"docstring": "Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command.",
"name": "__init__",
"signature": "def __init__(self, name, *args)"
},
{
"docstring": "Converts this object to a String object. :return: This object as a String.",
"... | 3 | stack_v2_sparse_classes_30k_train_001873 | Implement the Python class `Message` described below.
Class description:
Implement the Message class.
Method signatures and docstrings:
- def __init__(self, name, *args): Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command.
- def __str__(self) -> str: Converts ... | Implement the Python class `Message` described below.
Class description:
Implement the Message class.
Method signatures and docstrings:
- def __init__(self, name, *args): Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command.
- def __str__(self) -> str: Converts ... | 57660ec8ed3b431779524bd40540acf1cb212f6f | <|skeleton|>
class Message:
def __init__(self, name, *args):
"""Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command."""
<|body_0|>
def __str__(self) -> str:
"""Converts this object to a String object. :return: This object as a St... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
def __init__(self, name, *args):
"""Instantiates a new Message. :param name: The name of the command. :param args: The parameters of the command."""
self.name = name
self.args = []
for arg in args:
self.args.append(arg)
def __str__(self) -> str:
... | the_stack_v2_python_sparse | server/src/network/message.py | CLOVIS-AI/ccg2lambda-qa-assistant | train | 2 | |
f4c8ed94c27fb052e83f7b7cb944889273dced13 | [
"if root is None:\n return True\nself.__findNode(root, 1)\nreturn self.__balanced",
"if node.left is None and node.right is None:\n return depth\nleftDepth = depth\nrightDepth = depth\nif node.left is not None:\n leftDepth = self.__findNode(node.left, depth + 1)\nif node.right is not None:\n rightDept... | <|body_start_0|>
if root is None:
return True
self.__findNode(root, 1)
return self.__balanced
<|end_body_0|>
<|body_start_1|>
if node.left is None and node.right is None:
return depth
leftDepth = depth
rightDepth = depth
if node.left is no... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_36k_train_006566 | 2,462 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": ":type node: TreeNode :type depth: int :rtype: int",
"name": "__findNode",
"signature": "def __findNode(self, node, depth)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014678 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def __findNode(self, node, depth): :type node: TreeNode :type depth: int :rtype: int
<|skeleton|>
class Solution:... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
self.__findNode(root, 1)
return self.__balanced
def __findNode(self, node, depth):
""":type node: TreeNode :type depth: int :rtype: int"""
... | the_stack_v2_python_sparse | leetcode/easy/tree/test_balanced_binary_tree.py | yenbohuang/online-contest-python | train | 0 | |
39d06fdee411c634ee53e07a1ceda24cefca13b4 | [
"super().__init__()\nlayers = nn.ModuleDict()\nlayers['input_padding'] = nn.ReflectionPad1d(padding=7)\nlayers['conv_layer_0'] = nn.Sequential(nn.utils.weight_norm(nn.Conv1d(in_channels=1, out_channels=features, kernel_size=15)), nn.LeakyReLU(0.2, inplace=True))\nkernel_size = downsampling_factor * 10 + 1\ncurrent_... | <|body_start_0|>
super().__init__()
layers = nn.ModuleDict()
layers['input_padding'] = nn.ReflectionPad1d(padding=7)
layers['conv_layer_0'] = nn.Sequential(nn.utils.weight_norm(nn.Conv1d(in_channels=1, out_channels=features, kernel_size=15)), nn.LeakyReLU(0.2, inplace=True))
kern... | DiscriminatorBlock for Discriminator | DiscriminatorBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscriminatorBlock:
"""DiscriminatorBlock for Discriminator"""
def __init__(self, downsampling_layers_num: int=4, features: int=16, downsampling_factor: int=1):
"""DiscriminatorBlock for Discriminator Args: downsampling_layers_num: number of downsampling layers features: features num... | stack_v2_sparse_classes_36k_train_006567 | 4,148 | no_license | [
{
"docstring": "DiscriminatorBlock for Discriminator Args: downsampling_layers_num: number of downsampling layers features: features number after first conv layer downsampling_factor: downsampling factor",
"name": "__init__",
"signature": "def __init__(self, downsampling_layers_num: int=4, features: int... | 2 | stack_v2_sparse_classes_30k_train_020285 | Implement the Python class `DiscriminatorBlock` described below.
Class description:
DiscriminatorBlock for Discriminator
Method signatures and docstrings:
- def __init__(self, downsampling_layers_num: int=4, features: int=16, downsampling_factor: int=1): DiscriminatorBlock for Discriminator Args: downsampling_layers_... | Implement the Python class `DiscriminatorBlock` described below.
Class description:
DiscriminatorBlock for Discriminator
Method signatures and docstrings:
- def __init__(self, downsampling_layers_num: int=4, features: int=16, downsampling_factor: int=1): DiscriminatorBlock for Discriminator Args: downsampling_layers_... | d5eac1cfb7d382c26d9e1961e443941410e1c1ba | <|skeleton|>
class DiscriminatorBlock:
"""DiscriminatorBlock for Discriminator"""
def __init__(self, downsampling_layers_num: int=4, features: int=16, downsampling_factor: int=1):
"""DiscriminatorBlock for Discriminator Args: downsampling_layers_num: number of downsampling layers features: features num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscriminatorBlock:
"""DiscriminatorBlock for Discriminator"""
def __init__(self, downsampling_layers_num: int=4, features: int=16, downsampling_factor: int=1):
"""DiscriminatorBlock for Discriminator Args: downsampling_layers_num: number of downsampling layers features: features number after fir... | the_stack_v2_python_sparse | src/models/discriminator.py | elephantmipt/MelGAN | train | 6 |
36cc085bf7cedd69fdcaa95672280d09e300c128 | [
"if m == 1 or n == 1:\n return 1\nm -= 1\nn -= 1\nif m < n:\n m = m + n\n n = m - n\n m = m - n\nres = 1\nj = 1\nfor i in range(m + 1, m + n + 1):\n res *= i\n res /= j\n j += 1\nreturn res",
"if m == 1 or n == 1:\n return 1\nelse:\n ret = 0\n for i in range(1, n):\n ret += se... | <|body_start_0|>
if m == 1 or n == 1:
return 1
m -= 1
n -= 1
if m < n:
m = m + n
n = m - n
m = m - n
res = 1
j = 1
for i in range(m + 1, m + n + 1):
res *= i
res /= j
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if m == 1 or n == 1:
ret... | stack_v2_sparse_classes_36k_train_006568 | 992 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths1",
"signature": "def uniquePaths1(self, m, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths1(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths1(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:
def un... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
if m == 1 or n == 1:
return 1
m -= 1
n -= 1
if m < n:
m = m + n
n = m - n
m = m - n
res = 1
j = 1
for i in range(m ... | the_stack_v2_python_sparse | python/leetcode/62_Unique_Paths.py | bobcaoge/my-code | train | 0 | |
513ea499400c794ef129c0c55c0ae56be6f90b5c | [
"self.login.login(username, password)\nsleep(5)\nself.driver.assert_in(u'人员调度1111', u'人员调度')",
"self.login.login(username, password)\nsleep(2)\nself.driver.assert_true(self.login.login_errorinfo_text(wrong_msg))",
"self.login.input_login_username(username)\nsleep(1)\nself.login.input_login_password(password)\ns... | <|body_start_0|>
self.login.login(username, password)
sleep(5)
self.driver.assert_in(u'人员调度1111', u'人员调度')
<|end_body_0|>
<|body_start_1|>
self.login.login(username, password)
sleep(2)
self.driver.assert_true(self.login.login_errorinfo_text(wrong_msg))
<|end_body_1|>
<|... | PoliceVP登录测试 | WTestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WTestLogin:
"""PoliceVP登录测试"""
def test_login01(self, username, password):
"""正确登录,弹出首页"""
<|body_0|>
def test_login02(self, username, password, wrong_msg):
"""错误登录,有提示信息"""
<|body_1|>
def test_login03(self, username, password, button_attribute, butt... | stack_v2_sparse_classes_36k_train_006569 | 5,242 | no_license | [
{
"docstring": "正确登录,弹出首页",
"name": "test_login01",
"signature": "def test_login01(self, username, password)"
},
{
"docstring": "错误登录,有提示信息",
"name": "test_login02",
"signature": "def test_login02(self, username, password, wrong_msg)"
},
{
"docstring": "用户名或密码小于6位,登录按钮置灰",
"n... | 5 | stack_v2_sparse_classes_30k_train_007577 | Implement the Python class `WTestLogin` described below.
Class description:
PoliceVP登录测试
Method signatures and docstrings:
- def test_login01(self, username, password): 正确登录,弹出首页
- def test_login02(self, username, password, wrong_msg): 错误登录,有提示信息
- def test_login03(self, username, password, button_attribute, button_a... | Implement the Python class `WTestLogin` described below.
Class description:
PoliceVP登录测试
Method signatures and docstrings:
- def test_login01(self, username, password): 正确登录,弹出首页
- def test_login02(self, username, password, wrong_msg): 错误登录,有提示信息
- def test_login03(self, username, password, button_attribute, button_a... | d0b0f5d59f5d94e12ed138456a927047b7e55d96 | <|skeleton|>
class WTestLogin:
"""PoliceVP登录测试"""
def test_login01(self, username, password):
"""正确登录,弹出首页"""
<|body_0|>
def test_login02(self, username, password, wrong_msg):
"""错误登录,有提示信息"""
<|body_1|>
def test_login03(self, username, password, button_attribute, butt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WTestLogin:
"""PoliceVP登录测试"""
def test_login01(self, username, password):
"""正确登录,弹出首页"""
self.login.login(username, password)
sleep(5)
self.driver.assert_in(u'人员调度1111', u'人员调度')
def test_login02(self, username, password, wrong_msg):
"""错误登录,有提示信息"""
... | the_stack_v2_python_sparse | project/web_project/login_test.py | zyt19910214/Studys | train | 0 |
cb99ce9785be6b55976bdabafeed533031801767 | [
"p1 = Store.Product('889', 'Rodent of unusual size', \"when a rodent of the usual size just won't do\", 33.45, 8)\nc1 = Store.Customer('Yinsheng', 'QWF', True)\nmyStore = Store.Store()\nmyStore.add_product(p1)\nmyStore.add_member(c1)\nmyStore.add_product_to_member_cart('889', 'QWF')\nresult = myStore.check_out_memb... | <|body_start_0|>
p1 = Store.Product('889', 'Rodent of unusual size', "when a rodent of the usual size just won't do", 33.45, 8)
c1 = Store.Customer('Yinsheng', 'QWF', True)
myStore = Store.Store()
myStore.add_product(p1)
myStore.add_member(c1)
myStore.add_product_to_membe... | Tests our store for functionality | TestStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStore:
"""Tests our store for functionality"""
def test_1(self):
"""This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member"""
<|body_0|>
def test_2(self):
"""This test is checking to make sure the program is c... | stack_v2_sparse_classes_36k_train_006570 | 4,135 | no_license | [
{
"docstring": "This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "This test is checking to make sure the program is charging the extra 7% shipping cost for non-premium me... | 5 | stack_v2_sparse_classes_30k_train_017953 | Implement the Python class `TestStore` described below.
Class description:
Tests our store for functionality
Method signatures and docstrings:
- def test_1(self): This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member
- def test_2(self): This test is checking to make ... | Implement the Python class `TestStore` described below.
Class description:
Tests our store for functionality
Method signatures and docstrings:
- def test_1(self): This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member
- def test_2(self): This test is checking to make ... | 5a6a3a94ae3ffac76d6fb1d311e007611bd95e3c | <|skeleton|>
class TestStore:
"""Tests our store for functionality"""
def test_1(self):
"""This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member"""
<|body_0|>
def test_2(self):
"""This test is checking to make sure the program is c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestStore:
"""Tests our store for functionality"""
def test_1(self):
"""This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member"""
p1 = Store.Product('889', 'Rodent of unusual size', "when a rodent of the usual size just won't do", 33.45, 8... | the_stack_v2_python_sparse | CS_162/Project 2- Store/StoreTester.py | TVareka/School-Projects | train | 0 |
0e5694e355ae1dff3f960a093ff3daec430fb5fa | [
"super().__init__(*args, **kwargs)\nself.model_dir: str = model_dir\nself.config = Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION))\nself.device = 'cuda' if ('device' not in kwargs or kwargs['device'] == 'gpu') and torch.cuda.is_available() else 'cpu'\nself.processor = None\nself.table_path =... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
self.config = Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION))
self.device = 'cuda' if ('device' not in kwargs or kwargs['device'] == 'gpu') and torch.cuda.is_available() else 'cpu'
... | ConversationalTextToSqlPreprocessor | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversationalTextToSqlPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""process the raw input data Args: data (dict... | stack_v2_sparse_classes_36k_train_006571 | 4,902 | permissive | [
{
"docstring": "preprocess the data Args: model_dir (str): model path",
"name": "__init__",
"signature": "def __init__(self, model_dir: str, *args, **kwargs)"
},
{
"docstring": "process the raw input data Args: data (dict): utterance: a sentence last_sql: predicted sql of last utterance Example:... | 2 | stack_v2_sparse_classes_30k_train_008376 | Implement the Python class `ConversationalTextToSqlPreprocessor` described below.
Class description:
Implement the ConversationalTextToSqlPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(se... | Implement the Python class `ConversationalTextToSqlPreprocessor` described below.
Class description:
Implement the ConversationalTextToSqlPreprocessor class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): preprocess the data Args: model_dir (str): model path
- def __call__(se... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ConversationalTextToSqlPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
<|body_0|>
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""process the raw input data Args: data (dict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConversationalTextToSqlPreprocessor:
def __init__(self, model_dir: str, *args, **kwargs):
"""preprocess the data Args: model_dir (str): model path"""
super().__init__(*args, **kwargs)
self.model_dir: str = model_dir
self.config = Config.from_file(os.path.join(self.model_dir, Mo... | the_stack_v2_python_sparse | ai/modelscope/modelscope/preprocessors/nlp/space_T_en/conversational_text_to_sql_preprocessor.py | alldatacenter/alldata | train | 774 | |
2bf10beb2e3ea5228b5ac529778c43649013185f | [
"EasyFrame.__init__(self, 'File Dialog Demo')\nself.outputArea = self.addTextArea('', row=0, column=0, columnspan=2, width=80, height=15)\nself.addButton(text='Open', row=1, column=0, command=self.openFile)\nself.addButton(text='Save As...', row=1, column=1, command=self.saveFileAs)",
"filetypes = [('Python files... | <|body_start_0|>
EasyFrame.__init__(self, 'File Dialog Demo')
self.outputArea = self.addTextArea('', row=0, column=0, columnspan=2, width=80, height=15)
self.addButton(text='Open', row=1, column=0, command=self.openFile)
self.addButton(text='Save As...', row=1, column=1, command=self.sav... | Demonstrates a file dialog. | FileDialogDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileDialogDemo:
"""Demonstrates a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def openFile(self):
"""Pops up an open file dialog, and if a file is selected, displays its text in the text area."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_006572 | 1,816 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Pops up an open file dialog, and if a file is selected, displays its text in the text area.",
"name": "openFile",
"signature": "def openFile(self)"
},
{
"doc... | 3 | null | Implement the Python class `FileDialogDemo` described below.
Class description:
Demonstrates a file dialog.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def openFile(self): Pops up an open file dialog, and if a file is selected, displays its text in the text area.
- def sa... | Implement the Python class `FileDialogDemo` described below.
Class description:
Demonstrates a file dialog.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def openFile(self): Pops up an open file dialog, and if a file is selected, displays its text in the text area.
- def sa... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class FileDialogDemo:
"""Demonstrates a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def openFile(self):
"""Pops up an open file dialog, and if a file is selected, displays its text in the text area."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileDialogDemo:
"""Demonstrates a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, 'File Dialog Demo')
self.outputArea = self.addTextArea('', row=0, column=0, columnspan=2, width=80, height=15)
self.addButton(text='Open', r... | the_stack_v2_python_sparse | gui/breezy/filedialogdemo.py | lforet/robomow | train | 11 |
0d0a318880f46604fe0e963a30334b6d1bd19cc0 | [
"self.client.force_authenticate(user=self.user)\nresponse = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))\nexpected = Item.objects.all()\nserialized = ItemSerializer(expected, many=True)\nself.assertEqual(response.json(), serialized.data)\nself.assertEqual(response.status_code, status.HTTP... | <|body_start_0|>
self.client.force_authenticate(user=self.user)
response = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))
expected = Item.objects.all()
serialized = ItemSerializer(expected, many=True)
self.assertEqual(response.json(), serialized.data)
... | GetItemsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
<|body_0|>
def test_get_avail_items(self):
"""Test getting all items through api call"""
<|body_1|>
def test_get_detail_item(self):
"""Test getting detail i... | stack_v2_sparse_classes_36k_train_006573 | 10,115 | no_license | [
{
"docstring": "Test getting all items through api call",
"name": "test_get_all_items",
"signature": "def test_get_all_items(self)"
},
{
"docstring": "Test getting all items through api call",
"name": "test_get_avail_items",
"signature": "def test_get_avail_items(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_val_000808 | Implement the Python class `GetItemsTest` described below.
Class description:
Implement the GetItemsTest class.
Method signatures and docstrings:
- def test_get_all_items(self): Test getting all items through api call
- def test_get_avail_items(self): Test getting all items through api call
- def test_get_detail_item... | Implement the Python class `GetItemsTest` described below.
Class description:
Implement the GetItemsTest class.
Method signatures and docstrings:
- def test_get_all_items(self): Test getting all items through api call
- def test_get_avail_items(self): Test getting all items through api call
- def test_get_detail_item... | 82f372ecae245b1affc6f7eaa15a0785146e6ca5 | <|skeleton|>
class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
<|body_0|>
def test_get_avail_items(self):
"""Test getting all items through api call"""
<|body_1|>
def test_get_detail_item(self):
"""Test getting detail i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
self.client.force_authenticate(user=self.user)
response = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))
expected = Item.objects.all()
serialized = ItemSer... | the_stack_v2_python_sparse | commerce/tests.py | Janujan/commerce-challenge | train | 0 | |
44d160bd335180af752386c8ffa6662bacf81c5c | [
"self._dbg = debug\nself._log = get_logger(self.__class__.__name__, self._dbg)\nself._paper_tape_file = paper_tape_file\nself._dst = dst\nself._parser = PaperTape(debug=self._dbg)",
"self._log.debug('')\nmusic_data = self._parser.parse(self._paper_tape_file)\nfor dst in self._dst:\n print()\n if ':/' in dst... | <|body_start_0|>
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._paper_tape_file = paper_tape_file
self._dst = dst
self._parser = PaperTape(debug=self._dbg)
<|end_body_0|>
<|body_start_1|>
self._log.debug('')
music_data = self._... | PaperTapeApp | PaperTapeApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaperTapeApp:
"""PaperTapeApp"""
def __init__(self, paper_tape_file, dst=(), debug=False) -> None:
"""Constructor Parameters ---------- paper_tape_file: str dst: str"""
<|body_0|>
def main(self):
"""main"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_006574 | 25,197 | no_license | [
{
"docstring": "Constructor Parameters ---------- paper_tape_file: str dst: str",
"name": "__init__",
"signature": "def __init__(self, paper_tape_file, dst=(), debug=False) -> None"
},
{
"docstring": "main",
"name": "main",
"signature": "def main(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000161 | Implement the Python class `PaperTapeApp` described below.
Class description:
PaperTapeApp
Method signatures and docstrings:
- def __init__(self, paper_tape_file, dst=(), debug=False) -> None: Constructor Parameters ---------- paper_tape_file: str dst: str
- def main(self): main | Implement the Python class `PaperTapeApp` described below.
Class description:
PaperTapeApp
Method signatures and docstrings:
- def __init__(self, paper_tape_file, dst=(), debug=False) -> None: Constructor Parameters ---------- paper_tape_file: str dst: str
- def main(self): main
<|skeleton|>
class PaperTapeApp:
... | b8264118d19c7f6c6be9b11f18c890c598eb1295 | <|skeleton|>
class PaperTapeApp:
"""PaperTapeApp"""
def __init__(self, paper_tape_file, dst=(), debug=False) -> None:
"""Constructor Parameters ---------- paper_tape_file: str dst: str"""
<|body_0|>
def main(self):
"""main"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaperTapeApp:
"""PaperTapeApp"""
def __init__(self, paper_tape_file, dst=(), debug=False) -> None:
"""Constructor Parameters ---------- paper_tape_file: str dst: str"""
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._paper_tape_file = pap... | the_stack_v2_python_sparse | musicbox/__main__.py | ytani01/MusicBox | train | 1 |
ac6aff06ca5565cdc1d5a903f1fe8f745bfd71b5 | [
"m = {}\nfor n in nums:\n if n not in m:\n m[n] = 1\n else:\n del m[n]\nfor k, v in m.items():\n return k",
"for i in range(1, len(nums)):\n nums[0] ^= nums[i]\nreturn nums[0]"
] | <|body_start_0|>
m = {}
for n in nums:
if n not in m:
m[n] = 1
else:
del m[n]
for k, v in m.items():
return k
<|end_body_0|>
<|body_start_1|>
for i in range(1, len(nums)):
nums[0] ^= nums[i]
return n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums) -> int:
"""哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户"""
<|body_0|>
def singleNumber1(self, nums) -> int:
"""异或运算 执行用时 : 52 ms, 在Single Number的Pyth... | stack_v2_sparse_classes_36k_train_006575 | 2,033 | no_license | [
{
"docstring": "哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户",
"name": "singleNumber",
"signature": "def singleNumber(self, nums) -> int"
},
{
"docstring": "异或运算 执行用时 : 52 ms, 在Single Number的Python3提交中击败了95.36% 的用户 内存... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums) -> int: 哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户
- def singleNumbe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums) -> int: 哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户
- def singleNumbe... | 7bca9dc8ec211be15c12f89bffbb680d639f87bf | <|skeleton|>
class Solution:
def singleNumber(self, nums) -> int:
"""哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户"""
<|body_0|>
def singleNumber1(self, nums) -> int:
"""异或运算 执行用时 : 52 ms, 在Single Number的Pyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums) -> int:
"""哈希表,严格说不符合题目的要求 执行用时 : 48 ms, 在Single Number的Python3提交中击败了99.17% 的用户 内存消耗 : 14.8 MB, 在Single Number的Python3提交中击败了31.34% 的用户"""
m = {}
for n in nums:
if n not in m:
m[n] = 1
else:
d... | the_stack_v2_python_sparse | python/leetcode/136-single-number.py | wxnacy/study | train | 18 | |
68b7e1d666c8e12f2128e3e382243f1bafa60ee0 | [
"super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)\nself.orientations = dat.getOrientations(frame, *self.particles) % (2 * np.pi)\nself.colorbar(0, 2, cmap=plt.cm.hsv)\nself.colormap.set_label('$\\\\theta_i/\\\\pi$', label... | <|body_start_0|>
super().__init__(dat, frame, box_size, centre, arrow_width=arrow_width, arrow_head_width=arrow_head_width, arrow_head_length=arrow_head_length)
self.orientations = dat.getOrientations(frame, *self.particles) % (2 * np.pi)
self.colorbar(0, 2, cmap=plt.cm.hsv)
self.colorma... | Plotting class specific to 'orientation' mode. | Orientation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orientation:
"""Plotting class specific to 'orientation' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, label=False, **kwargs):
"""Initialises and p... | stack_v2_sparse_classes_36k_train_006576 | 24,676 | permissive | [
{
"docstring": "Initialises and plots figure. Parameters ---------- dat : active_work.read.Dat Data object. frame : int Frame to render. box_size : float Length of the square box to render. centre : 2-uple like Centre of the box to render. arrow_width : float Width of the arrows. arrow_head_width : float Width ... | 3 | stack_v2_sparse_classes_30k_train_020640 | Implement the Python class `Orientation` described below.
Class description:
Plotting class specific to 'orientation' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colo... | Implement the Python class `Orientation` described below.
Class description:
Plotting class specific to 'orientation' mode.
Method signatures and docstrings:
- def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colo... | 99107a0d4935296b673f67469c1e2bd258954b9b | <|skeleton|>
class Orientation:
"""Plotting class specific to 'orientation' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, label=False, **kwargs):
"""Initialises and p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Orientation:
"""Plotting class specific to 'orientation' mode."""
def __init__(self, dat, frame, box_size, centre, arrow_width=_arrow_width, arrow_head_width=_arrow_head_width, arrow_head_length=_arrow_head_length, pad=_colormap_label_pad, label=False, **kwargs):
"""Initialises and plots figure. ... | the_stack_v2_python_sparse | frame.py | yketa/active_work | train | 1 |
454e693ba128413c4932d0eaaa442ba159c9b180 | [
"if training_type == TrainingType.NLU:\n core_required = False\n core_target = None\nelse:\n core_required = True\n core_target = config.get('core_target')\nnlu_target = config.get('nlu_target')\nif nlu_target is None or (core_required and core_target is None):\n raise InvalidConfigException(\"Can't ... | <|body_start_0|>
if training_type == TrainingType.NLU:
core_required = False
core_target = None
else:
core_required = True
core_target = config.get('core_target')
nlu_target = config.get('nlu_target')
if nlu_target is None or (core_required... | Recipe which converts the graph model config to train and predict graph. | GraphV1Recipe | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `co... | stack_v2_sparse_classes_36k_train_006577 | 3,301 | permissive | [
{
"docstring": "Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `core_target` as fixed values of `run_RegexMessageHandler` and `select_prediction` respectively. For graph recipe, target values are customizable. These can be used in validation (default recipe doe... | 2 | stack_v2_sparse_classes_30k_train_015822 | Implement the Python class `GraphV1Recipe` described below.
Class description:
Recipe which converts the graph model config to train and predict graph.
Method signatures and docstrings:
- def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]: Return NLU and core targets from config dict... | Implement the Python class `GraphV1Recipe` described below.
Class description:
Recipe which converts the graph model config to train and predict graph.
Method signatures and docstrings:
- def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]: Return NLU and core targets from config dict... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `core_target` as... | the_stack_v2_python_sparse | rasa/engine/recipes/graph_recipe.py | RasaHQ/rasa | train | 13,167 |
41893e1f044a550b76de4ea6ca5cf7ef24441cda | [
"super(Predictor, self).__init__()\nself.hidden_size = hidden_size\nself.embedding = embedding\nself._rule_embed_inv = EmbeddingInverse(self.embedding.previous_actions_embed.rule_embed.num_embeddings)\nself._token_embed_inv = EmbeddingInverse(self.embedding.previous_actions_embed.token_embed.num_embeddings)\nself._... | <|body_start_0|>
super(Predictor, self).__init__()
self.hidden_size = hidden_size
self.embedding = embedding
self._rule_embed_inv = EmbeddingInverse(self.embedding.previous_actions_embed.rule_embed.num_embeddings)
self._token_embed_inv = EmbeddingInverse(self.embedding.previous_a... | Predictor | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
def __init__(self, embedding: ActionsEmbedding, embedding_size: int, query_size: int, hidden_size: int, att_hidden_size: int):
"""Constructor Parameters ---------- embedding: embedding_size: int Size of each embedding vector query_size: int Size of each query vector hidden_siz... | stack_v2_sparse_classes_36k_train_006578 | 5,255 | permissive | [
{
"docstring": "Constructor Parameters ---------- embedding: embedding_size: int Size of each embedding vector query_size: int Size of each query vector hidden_size: int Size of each hidden state att_hidden_size: int The number of features in the hidden state for attention",
"name": "__init__",
"signatu... | 2 | null | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, embedding: ActionsEmbedding, embedding_size: int, query_size: int, hidden_size: int, att_hidden_size: int): Constructor Parameters ---------- embedding: embe... | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, embedding: ActionsEmbedding, embedding_size: int, query_size: int, hidden_size: int, att_hidden_size: int): Constructor Parameters ---------- embedding: embe... | 573e94c567064705fa65267dd83946bf183197de | <|skeleton|>
class Predictor:
def __init__(self, embedding: ActionsEmbedding, embedding_size: int, query_size: int, hidden_size: int, att_hidden_size: int):
"""Constructor Parameters ---------- embedding: embedding_size: int Size of each embedding vector query_size: int Size of each query vector hidden_siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predictor:
def __init__(self, embedding: ActionsEmbedding, embedding_size: int, query_size: int, hidden_size: int, att_hidden_size: int):
"""Constructor Parameters ---------- embedding: embedding_size: int Size of each embedding vector query_size: int Size of each query vector hidden_size: int Size of... | the_stack_v2_python_sparse | mlprogram/nn/nl2code/predictor.py | brando90/mlprogram | train | 0 | |
4531a61139d938b5ef9f11edcf5bc53055b571cc | [
"self.queue = nums\nself.size = len(self.queue)\nself.k = k\nheapq.heapify(self.queue)\nwhile self.size > k:\n heapq.heappop(self.queue)\n self.size -= 1",
"if self.size < self.k:\n heapq.heappush(self.queue, val)\n self.size += 1\nelif val > self.queue[0]:\n heapq.heapreplace(self.queue, val)\nret... | <|body_start_0|>
self.queue = nums
self.size = len(self.queue)
self.k = k
heapq.heapify(self.queue)
while self.size > k:
heapq.heappop(self.queue)
self.size -= 1
<|end_body_0|>
<|body_start_1|>
if self.size < self.k:
heapq.heappush(sel... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.queue = nums
self.size = len(self.queue)
... | stack_v2_sparse_classes_36k_train_006579 | 867 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010155 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 47d4456216781d746eca69389df379324afe2ff1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.queue = nums
self.size = len(self.queue)
self.k = k
heapq.heapify(self.queue)
while self.size > k:
heapq.heappop(self.queue)
self.size -= 1
def ad... | the_stack_v2_python_sparse | queue/703.py | jianengli/leetcode_practice | train | 0 | |
8c1340a521351c7ff9c0bdfdd326635bc138ce45 | [
"if not l1:\n return l2\nif not l2:\n return l1\n\ndef l_to_s(l):\n s = []\n while l:\n s.insert(0, l)\n l = l.next\n return s\nl1_stack, l2_stack = (l_to_s(l1), l_to_s(l2))\ncurrent = None\nnew_val = 0\nwhile l1_stack or l2_stack:\n if l1_stack:\n l1_top = l1_stack.pop(0)\n ... | <|body_start_0|>
if not l1:
return l2
if not l2:
return l1
def l_to_s(l):
s = []
while l:
s.insert(0, l)
l = l.next
return s
l1_stack, l2_stack = (l_to_s(l1), l_to_s(l2))
current = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbersSlow(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_006580 | 1,899 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbersSlow",
"signature": "def addTwoNumbersSlow(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbersSlow(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbersSlow(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListN... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def addTwoNumbersSlow(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbersSlow(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
if not l1:
return l2
if not l2:
return l1
def l_to_s(l):
s = []
while l:
s.insert(0, l)
l... | the_stack_v2_python_sparse | cs_notes/data_structure/linked_list/add_two_numbers_ii.py | hwc1824/LeetCodeSolution | train | 0 | |
645f9556e6c714b5358f18c54e8724ed5fa2a2e1 | [
"super(AuthenticationForm, self).__init__(*args, **kwargs)\nself.fields['remember_me'].label = _(u'Remember Me') % {'days': _(account_settings.ACCOUNT_REMEMBER_ME_DAYS[0])}\nself.fields['identification'] = identification_field_factory(_(u'Username'), _(u'Please enter username'))",
"identification = self.cleaned_d... | <|body_start_0|>
super(AuthenticationForm, self).__init__(*args, **kwargs)
self.fields['remember_me'].label = _(u'Remember Me') % {'days': _(account_settings.ACCOUNT_REMEMBER_ME_DAYS[0])}
self.fields['identification'] = identification_field_factory(_(u'Username'), _(u'Please enter username'))
<|... | A custom form where the identification can be a e-mail address or username. | AuthenticationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationForm:
"""A custom form where the identification can be a e-mail address or username."""
def __init__(self, *args, **kwargs):
"""A custom init because we need to change the label if no usernames is used"""
<|body_0|>
def clean(self):
"""Checks for th... | stack_v2_sparse_classes_36k_train_006581 | 10,524 | no_license | [
{
"docstring": "A custom init because we need to change the label if no usernames is used",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Checks for the identification and password. If the combination can't be found will raise an invalid sign in error.... | 2 | null | Implement the Python class `AuthenticationForm` described below.
Class description:
A custom form where the identification can be a e-mail address or username.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): A custom init because we need to change the label if no usernames is used
- def clean... | Implement the Python class `AuthenticationForm` described below.
Class description:
A custom form where the identification can be a e-mail address or username.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): A custom init because we need to change the label if no usernames is used
- def clean... | 47d6691bb1d13ea0084dafae434de6b871d3d1be | <|skeleton|>
class AuthenticationForm:
"""A custom form where the identification can be a e-mail address or username."""
def __init__(self, *args, **kwargs):
"""A custom init because we need to change the label if no usernames is used"""
<|body_0|>
def clean(self):
"""Checks for th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticationForm:
"""A custom form where the identification can be a e-mail address or username."""
def __init__(self, *args, **kwargs):
"""A custom init because we need to change the label if no usernames is used"""
super(AuthenticationForm, self).__init__(*args, **kwargs)
self... | the_stack_v2_python_sparse | shopping_project/shopping/accounts/forms.py | yong5219/zayn_couture | train | 0 |
5099e8ed38dda145d7a7cd83b0c60c88e6b0388c | [
"unpack = pktt.unpack\nulist = unpack.unpack(14, '!6s6sH')\nself.dst = MacAddr(ulist[0].encode('hex'))\nself.src = MacAddr(ulist[1].encode('hex'))\nself.type = ulist[2]\npktt.pkt.ethernet = self\nif self.type == 2048:\n IPv4(pktt)\nelif self.type == 34525:\n IPv6(pktt)\nelse:\n self.data = unpack.getbytes(... | <|body_start_0|>
unpack = pktt.unpack
ulist = unpack.unpack(14, '!6s6sH')
self.dst = MacAddr(ulist[0].encode('hex'))
self.src = MacAddr(ulist[1].encode('hex'))
self.type = ulist[2]
pktt.pkt.ethernet = self
if self.type == 2048:
IPv4(pktt)
elif ... | Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported ) | ETHERNET | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )... | stack_v2_sparse_classes_36k_train_006582 | 3,367 | no_license | [
{
"docstring": "Constructor Initialize object's private data. pktt: Packet trace object (packet.pktt.Pktt) so this layer has access to the parent layers.",
"name": "__init__",
"signature": "def __init__(self, pktt)"
},
{
"docstring": "String representation of object The representation depends on... | 2 | null | Implement the Python class `ETHERNET` described below.
Class description:
Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw dat... | Implement the Python class `ETHERNET` described below.
Class description:
Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw dat... | 1f06ae8c73d253141a3434fb9d2c36be3fe768ea | <|skeleton|>
class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )"""
def ... | the_stack_v2_python_sparse | packet/link/ethernet.py | MihailRusetskiy/nfs | train | 0 |
e60754498df04496954c3dfff8a7c5ff46d55e4d | [
"if n < 1:\n return 0\nself.result = []\nself.cols = set()\nself.pie = set()\nself.na = set()\nself._dfs(n, 0, [])\nreturn len(self.result)",
"if row >= n:\n self.result.append(cur_state)\n return\nfor col in range(n):\n if col in self.cols or row + col in self.pie or row - col in self.na:\n co... | <|body_start_0|>
if n < 1:
return 0
self.result = []
self.cols = set()
self.pie = set()
self.na = set()
self._dfs(n, 0, [])
return len(self.result)
<|end_body_0|>
<|body_start_1|>
if row >= n:
self.result.append(cur_state)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def _dfs(self, n, row, cur_state):
"""迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 1:
... | stack_v2_sparse_classes_36k_train_006583 | 1,346 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "totalNQueens",
"signature": "def totalNQueens(self, n)"
},
{
"docstring": "迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置",
"name": "_dfs",
"signature": "def _dfs(self, n, row, cur_state)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalNQueens(self, n): :type n: int :rtype: int
- def _dfs(self, n, row, cur_state): 迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalNQueens(self, n): :type n: int :rtype: int
- def _dfs(self, n, row, cur_state): 迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置
<|skeleton|>
class Solut... | a58e53715493688db0108611761946f7c4481ddd | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def _dfs(self, n, row, cur_state):
"""迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def totalNQueens(self, n):
""":type n: int :rtype: int"""
if n < 1:
return 0
self.result = []
self.cols = set()
self.pie = set()
self.na = set()
self._dfs(n, 0, [])
return len(self.result)
def _dfs(self, n, row, cur_sta... | the_stack_v2_python_sparse | 52.py | yourSprite/LeetCodeExcercise | train | 0 | |
59978cfa0309fc7502029c8c73b9a9963e0ca9e6 | [
"import heapq\n\ndef gcd(A, B):\n if B == 0:\n return A\n return gcd(B, A % B)\nif A < B:\n A, B = (B, A)\nc = gcd(A, B)\nmaxmin = A * B // c\nt1 = maxmin // A + maxmin // B - 1\nd = N // t1\nr = N % t1\ns = d * maxmin\nprint(d, r, maxmin, s)\nif r == 0:\n return s % (10 ** 9 + 7)\nh = [s + B, s ... | <|body_start_0|>
import heapq
def gcd(A, B):
if B == 0:
return A
return gcd(B, A % B)
if A < B:
A, B = (B, A)
c = gcd(A, B)
maxmin = A * B // c
t1 = maxmin // A + maxmin // B - 1
d = N // t1
r = N % t1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthMagicalNumber(self, N, A, B):
""":type N: int :type A: int :type B: int :rtype: int 144 ms"""
<|body_0|>
def nthMagicalNumber_1(self, N, A, B):
"""28MS :param N: :param A: :param B: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_006584 | 2,205 | no_license | [
{
"docstring": ":type N: int :type A: int :type B: int :rtype: int 144 ms",
"name": "nthMagicalNumber",
"signature": "def nthMagicalNumber(self, N, A, B)"
},
{
"docstring": "28MS :param N: :param A: :param B: :return:",
"name": "nthMagicalNumber_1",
"signature": "def nthMagicalNumber_1(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthMagicalNumber(self, N, A, B): :type N: int :type A: int :type B: int :rtype: int 144 ms
- def nthMagicalNumber_1(self, N, A, B): 28MS :param N: :param A: :param B: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthMagicalNumber(self, N, A, B): :type N: int :type A: int :type B: int :rtype: int 144 ms
- def nthMagicalNumber_1(self, N, A, B): 28MS :param N: :param A: :param B: :return... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def nthMagicalNumber(self, N, A, B):
""":type N: int :type A: int :type B: int :rtype: int 144 ms"""
<|body_0|>
def nthMagicalNumber_1(self, N, A, B):
"""28MS :param N: :param A: :param B: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthMagicalNumber(self, N, A, B):
""":type N: int :type A: int :type B: int :rtype: int 144 ms"""
import heapq
def gcd(A, B):
if B == 0:
return A
return gcd(B, A % B)
if A < B:
A, B = (B, A)
c = gcd(A, B)... | the_stack_v2_python_sparse | NthMagicalNumber_HARD_878.py | 953250587/leetcode-python | train | 2 | |
a54c4ba79b1eeb552781a310185759e1c9111bc6 | [
"self.sums = list()\nself.matrix = matrix\nfor row in matrix:\n self.sums.append(StupidSum(row))",
"delta = val - self.matrix[row][col]\nself.matrix[row][col] = val\nself.sums[row].update(col, delta)",
"s = 0\nfor i in xrange(row1, row2 + 1):\n s += self.sums[i].query(col2) - self.sums[i].query(col1 - 1)\... | <|body_start_0|>
self.sums = list()
self.matrix = matrix
for row in matrix:
self.sums.append(StupidSum(row))
<|end_body_0|>
<|body_start_1|>
delta = val - self.matrix[row][col]
self.matrix[row][col] = val
self.sums[row].update(col, delta)
<|end_body_1|>
<|bo... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_36k_train_006585 | 1,919 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void",
"name": "update",
... | 3 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def update(self, row, col, val): update the element at matrix[row,col] to val. ... | 490c38a9478838ff23c9f910cc950633b1e3f994 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
self.sums = list()
self.matrix = matrix
for row in matrix:
self.sums.append(StupidSum(row))
def update(self, row, col, val):
"""update the el... | the_stack_v2_python_sparse | Range Sum Query 2D - Mutable/solution.py | normanyahq/LeetCodeSolution | train | 0 | |
aee47da3a17df39128e1060c7d96903e985b32c5 | [
"self.track = segment.track\nself.samplerate = segment.track.samplerate\nself.comp_location = segment.comp_location\nself.duration = segment.duration\nself.volume_frames = volume_frames\nif self.duration != len(volume_frames):\n raise Exception('Duration must be same as volume frame length')",
"if channels == ... | <|body_start_0|>
self.track = segment.track
self.samplerate = segment.track.samplerate
self.comp_location = segment.comp_location
self.duration = segment.duration
self.volume_frames = volume_frames
if self.duration != len(volume_frames):
raise Exception('Durat... | Dynamic with manually-specified volume multiplier array | RawVolume | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.compos... | stack_v2_sparse_classes_36k_train_006586 | 1,251 | permissive | [
{
"docstring": "Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.composer.Segment` :param volume_frames: Raw volume multiplier frames :type volume_frames: numpy array",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_015829 | Implement the Python class `RawVolume` described below.
Class description:
Dynamic with manually-specified volume multiplier array
Method signatures and docstrings:
- def __init__(self, segment, volume_frames): Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to ... | Implement the Python class `RawVolume` described below.
Class description:
Dynamic with manually-specified volume multiplier array
Method signatures and docstrings:
- def __init__(self, segment, volume_frames): Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to ... | 7535a5aa02e45eab6355f4d37086690e4b254387 | <|skeleton|>
class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.compos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawVolume:
"""Dynamic with manually-specified volume multiplier array"""
def __init__(self, segment, volume_frames):
"""Create a dynamic that manually specifies the volume multiplier array. :param segment: Segment for which to create dynamic :type segment: :py:class:`radiotool.composer.Segment` :... | the_stack_v2_python_sparse | radiotool/radiotool/composer/rawvolume.py | Morphinity/retarget_modified | train | 0 |
adfdf40f5f35d7c895e4da962c4d19b9a4ccf4fc | [
"self.base_lr = base_lr\nself.warmup_steps = warmup_steps\nself.num_train_steps = num_train_steps\nself.decay_steps = decay_steps\nself.end_lr = end_lr\nself.power = power\nself.cycle = cycle\nLRScheduler.__init__(self, learning_rate=base_lr, last_epoch=-1, verbose=verbose)",
"if self.last_epoch < self.warmup_ste... | <|body_start_0|>
self.base_lr = base_lr
self.warmup_steps = warmup_steps
self.num_train_steps = num_train_steps
self.decay_steps = decay_steps
self.end_lr = end_lr
self.power = power
self.cycle = cycle
LRScheduler.__init__(self, learning_rate=base_lr, last... | LinearWarmupDecay | LinearWarmupDecay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearWarmupDecay:
"""LinearWarmupDecay"""
def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, num_train_steps, power=1.0, verbose=False, cycle=False):
"""先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_lr: :param end_lr: :param warmup_steps: :param decay_steps... | stack_v2_sparse_classes_36k_train_006587 | 4,873 | permissive | [
{
"docstring": "先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_lr: :param end_lr: :param warmup_steps: :param decay_steps: :param num_train_steps: :param power: :param verbose: :param cycle:",
"name": "__init__",
"signature": "def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, n... | 3 | null | Implement the Python class `LinearWarmupDecay` described below.
Class description:
LinearWarmupDecay
Method signatures and docstrings:
- def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, num_train_steps, power=1.0, verbose=False, cycle=False): 先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_l... | Implement the Python class `LinearWarmupDecay` described below.
Class description:
LinearWarmupDecay
Method signatures and docstrings:
- def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, num_train_steps, power=1.0, verbose=False, cycle=False): 先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_l... | 610f759a8488c94134bf77cff30fa1190e8df414 | <|skeleton|>
class LinearWarmupDecay:
"""LinearWarmupDecay"""
def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, num_train_steps, power=1.0, verbose=False, cycle=False):
"""先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_lr: :param end_lr: :param warmup_steps: :param decay_steps... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearWarmupDecay:
"""LinearWarmupDecay"""
def __init__(self, base_lr, end_lr, warmup_steps, decay_steps, num_train_steps, power=1.0, verbose=False, cycle=False):
"""先使用warmup线性衰减,由小变大到base_lr, 再使用多项式衰减由大变小到end_lr :param base_lr: :param end_lr: :param warmup_steps: :param decay_steps: :param num_... | the_stack_v2_python_sparse | erniekit/modules/ernie_lr.py | Kennycao123/ERNIE | train | 0 |
cd36b10f73e74d82c3b5a7486b1da0353763443a | [
"if self.extra_reason_visible:\n tmp_reason = self.extra_reason\nelse:\n tmp_reason = self.reason.reason\nself.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_train': self.cur_train.id, 'start_date': self.start_date, 'end_date': self.end_date, 'type': 'detain'})",
"extra_reason... | <|body_start_0|>
if self.extra_reason_visible:
tmp_reason = self.extra_reason
else:
tmp_reason = self.reason.reason
self.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_train': self.cur_train.id, 'start_date': self.start_date, 'end_date': sel... | 扣车向导 | DetainWizard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
<|body_0|>
def on_change_reason(self):
"""改变扣车原因,如果是其它的话则显示extra_reason :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.extra_reason_visible:
tmp_reason... | stack_v2_sparse_classes_36k_train_006588 | 1,700 | no_license | [
{
"docstring": "点击确定按扭 :return:",
"name": "on_ok",
"signature": "def on_ok(self)"
},
{
"docstring": "改变扣车原因,如果是其它的话则显示extra_reason :return:",
"name": "on_change_reason",
"signature": "def on_change_reason(self)"
}
] | 2 | null | Implement the Python class `DetainWizard` described below.
Class description:
扣车向导
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭 :return:
- def on_change_reason(self): 改变扣车原因,如果是其它的话则显示extra_reason :return: | Implement the Python class `DetainWizard` described below.
Class description:
扣车向导
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭 :return:
- def on_change_reason(self): 改变扣车原因,如果是其它的话则显示extra_reason :return:
<|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
<|body_0|>
def on_change_reason(self):
"""改变扣车原因,如果是其它的话则显示extra_reason :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DetainWizard:
"""扣车向导"""
def on_ok(self):
"""点击确定按扭 :return:"""
if self.extra_reason_visible:
tmp_reason = self.extra_reason
else:
tmp_reason = self.reason.reason
self.env['metro_park_dispatch.detain_his_info'].create({'reason': tmp_reason, 'cur_tra... | the_stack_v2_python_sparse | mdias_addons/metro_park_dispatch/models/detain_wizard.py | rezaghanimi/main_mdias | train | 0 |
17e687ecd76601cb44d77bc8a36681eb9e327c97 | [
"super().__init__()\nself.queue = QUEUE_TYPE()\nself.template_vcf = template_vcf\nself.output_name = vcf_output_name\nself.df_name = df_output_name\nself.out_vcf = None\nself.sample = sample\nself.sample_column = None\nself.annotations = annotations\nself.new_headers = []\nself.new_tags = []\nself.format_defaults =... | <|body_start_0|>
super().__init__()
self.queue = QUEUE_TYPE()
self.template_vcf = template_vcf
self.output_name = vcf_output_name
self.df_name = df_output_name
self.out_vcf = None
self.sample = sample
self.sample_column = None
self.annotations = an... | Thread dedicated to writing the output | PCMPWriter | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCMPWriter:
"""Thread dedicated to writing the output"""
def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False):
"""Using a template_vcf, edit the header appropriately and create the output_name annotations are objects with"""
... | stack_v2_sparse_classes_36k_train_006589 | 35,836 | permissive | [
{
"docstring": "Using a template_vcf, edit the header appropriately and create the output_name annotations are objects with",
"name": "__init__",
"signature": "def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False)"
},
{
"docstring": "Puts in the ... | 4 | null | Implement the Python class `PCMPWriter` described below.
Class description:
Thread dedicated to writing the output
Method signatures and docstrings:
- def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False): Using a template_vcf, edit the header appropriately and create... | Implement the Python class `PCMPWriter` described below.
Class description:
Thread dedicated to writing the output
Method signatures and docstrings:
- def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False): Using a template_vcf, edit the header appropriately and create... | 5f40198e95b0626ae143e021ec97884de634e61d | <|skeleton|>
class PCMPWriter:
"""Thread dedicated to writing the output"""
def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False):
"""Using a template_vcf, edit the header appropriately and create the output_name annotations are objects with"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCMPWriter:
"""Thread dedicated to writing the output"""
def __init__(self, vcf_output_name, df_output_name, template_vcf, sample, annotations, strip_fmt=False):
"""Using a template_vcf, edit the header appropriately and create the output_name annotations are objects with"""
super().__ini... | the_stack_v2_python_sparse | python/biograph/tools/coverage.py | spiralgenetics/biograph | train | 21 |
fbd654e514615b15ae3f125d548c7e14d16ec2d8 | [
"try:\n return json.loads(data)\nexcept UnicodeDecodeError:\n raise _errors.CharacterEncodingError\nexcept (OverflowError, TypeError, ValueError, Exception):\n raise _errors.InvalidObjectError",
"try:\n return json.dumps(data)\nexcept UnicodeDecodeError:\n raise _errors.CharacterEncodingError\nexce... | <|body_start_0|>
try:
return json.loads(data)
except UnicodeDecodeError:
raise _errors.CharacterEncodingError
except (OverflowError, TypeError, ValueError, Exception):
raise _errors.InvalidObjectError
<|end_body_0|>
<|body_start_1|>
try:
r... | Helper class for specific formatting and rendering. | Renderer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Renderer:
"""Helper class for specific formatting and rendering."""
def from_json(data):
""".. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data: str :return: dictionary translation of :code:`data` :rty... | stack_v2_sparse_classes_36k_train_006590 | 1,810 | permissive | [
{
"docstring": ".. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data: str :return: dictionary translation of :code:`data` :rtype: dict :raises CharacterEncodingError: if :code:`data` cannot be decoded :raises InvalidObjectError: i... | 2 | stack_v2_sparse_classes_30k_train_017859 | Implement the Python class `Renderer` described below.
Class description:
Helper class for specific formatting and rendering.
Method signatures and docstrings:
- def from_json(data): .. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data:... | Implement the Python class `Renderer` described below.
Class description:
Helper class for specific formatting and rendering.
Method signatures and docstrings:
- def from_json(data): .. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data:... | d485071065174b2fb4ed0c33d31e45243ff2ce20 | <|skeleton|>
class Renderer:
"""Helper class for specific formatting and rendering."""
def from_json(data):
""".. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data: str :return: dictionary translation of :code:`data` :rty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Renderer:
"""Helper class for specific formatting and rendering."""
def from_json(data):
""".. py:function:: from_json(data) Renders JSON-encoded data as a Python dictionary. :param data: JSON-encoded data to render :type data: str :return: dictionary translation of :code:`data` :rtype: dict :rai... | the_stack_v2_python_sparse | plast/framework/api/internal/renderer.py | Grukz/plast | train | 0 |
812496bf433164a1884cb31f3017717d8c94a4c6 | [
"if context is None:\n context = {}\nres = {}\nfor stock_picking in self.browse(cr, uid, ids, context=context):\n res[stock_picking.id] = False\n if stock_picking.sale_id and stock_picking.sale_id.purchase_order_id or (stock_picking.purchase_id and stock_picking.purchase_id.sale_order_id):\n res[sto... | <|body_start_0|>
if context is None:
context = {}
res = {}
for stock_picking in self.browse(cr, uid, ids, context=context):
res[stock_picking.id] = False
if stock_picking.sale_id and stock_picking.sale_id.purchase_order_id or (stock_picking.purchase_id and sto... | stock_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking:
def _get_is_edi(self, cr, uid, ids, name, args, context=None):
"""This method will return if the picking is or not an edi picking"""
<|body_0|>
def _edi_link(self, cr, uid, picking_id, context=None):
"""Method to update the related pickings"""
... | stack_v2_sparse_classes_36k_train_006591 | 19,840 | no_license | [
{
"docstring": "This method will return if the picking is or not an edi picking",
"name": "_get_is_edi",
"signature": "def _get_is_edi(self, cr, uid, ids, name, args, context=None)"
},
{
"docstring": "Method to update the related pickings",
"name": "_edi_link",
"signature": "def _edi_lin... | 4 | stack_v2_sparse_classes_30k_train_006494 | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def _get_is_edi(self, cr, uid, ids, name, args, context=None): This method will return if the picking is or not an edi picking
- def _edi_link(self, cr, uid, picking_id... | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def _get_is_edi(self, cr, uid, ids, name, args, context=None): This method will return if the picking is or not an edi picking
- def _edi_link(self, cr, uid, picking_id... | 3e35f7ba7246c54e5a5b31921b28aa5f1ab24999 | <|skeleton|>
class stock_picking:
def _get_is_edi(self, cr, uid, ids, name, args, context=None):
"""This method will return if the picking is or not an edi picking"""
<|body_0|>
def _edi_link(self, cr, uid, picking_id, context=None):
"""Method to update the related pickings"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking:
def _get_is_edi(self, cr, uid, ids, name, args, context=None):
"""This method will return if the picking is or not an edi picking"""
if context is None:
context = {}
res = {}
for stock_picking in self.browse(cr, uid, ids, context=context):
... | the_stack_v2_python_sparse | intercompany_warehouse/stock.py | mgielissen/julius-openobject-addons | train | 1 | |
ff239c6f8d4328cd5cfef6b0ed4b032ae21387a5 | [
"size__xz = [None, z_size]\nself.mean = mean\nself.logvar = logvar\nself.noise = noise = tf.random_normal(tf.shape(logvar))\nself.sample = mean + tf.exp(0.5 * logvar) * noise\nmean.set_shape(size__xz)\nlogvar.set_shape(size__xz)\nself.sample.set_shape(size__xz)",
"if z is None:\n z = self.sample\nif z == self.... | <|body_start_0|>
size__xz = [None, z_size]
self.mean = mean
self.logvar = logvar
self.noise = noise = tf.random_normal(tf.shape(logvar))
self.sample = mean + tf.exp(0.5 * logvar) * noise
mean.set_shape(size__xz)
logvar.set_shape(size__xz)
self.sample.set_s... | Diagonal Gaussian with different constant mean and variances in each dimension. | DiagonalGaussian | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiagonalGaussian:
"""Diagonal Gaussian with different constant mean and variances in each dimension."""
def __init__(self, batch_size, z_size, mean, logvar):
"""Create a diagonal gaussian distribution. Args: batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples. z_s... | stack_v2_sparse_classes_36k_train_006592 | 17,394 | permissive | [
{
"docstring": "Create a diagonal gaussian distribution. Args: batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples. z_size: The dimension of the distribution, i.e. 1st dim in 2D tensor. mean: The N-D mean of the distribution. logvar: The N-D log variance of the diagonal distribution.",
"... | 2 | null | Implement the Python class `DiagonalGaussian` described below.
Class description:
Diagonal Gaussian with different constant mean and variances in each dimension.
Method signatures and docstrings:
- def __init__(self, batch_size, z_size, mean, logvar): Create a diagonal gaussian distribution. Args: batch_size: The siz... | Implement the Python class `DiagonalGaussian` described below.
Class description:
Diagonal Gaussian with different constant mean and variances in each dimension.
Method signatures and docstrings:
- def __init__(self, batch_size, z_size, mean, logvar): Create a diagonal gaussian distribution. Args: batch_size: The siz... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class DiagonalGaussian:
"""Diagonal Gaussian with different constant mean and variances in each dimension."""
def __init__(self, batch_size, z_size, mean, logvar):
"""Create a diagonal gaussian distribution. Args: batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples. z_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiagonalGaussian:
"""Diagonal Gaussian with different constant mean and variances in each dimension."""
def __init__(self, batch_size, z_size, mean, logvar):
"""Create a diagonal gaussian distribution. Args: batch_size: The size of the batch, i.e. 0th dim in 2D tensor of samples. z_size: The dime... | the_stack_v2_python_sparse | models/research/lfads/distributions.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
b32b0a4215af658ed83ab312436444e2f3ed0602 | [
"n = [x * x for x in nums]\nn.sort()\nreturn n",
"res = [0 for _ in range(len(nums))]\nl, r = (0, len(nums) - 1)\nfor idx in reversed(range(len(nums))):\n l_v = nums[l]\n r_v = nums[r]\n if abs(l_v) >= abs(r_v):\n res[idx] = l_v * l_v\n l += 1\n else:\n res[idx] = r_v * r_v\n ... | <|body_start_0|>
n = [x * x for x in nums]
n.sort()
return n
<|end_body_0|>
<|body_start_1|>
res = [0 for _ in range(len(nums))]
l, r = (0, len(nums) - 1)
for idx in reversed(range(len(nums))):
l_v = nums[l]
r_v = nums[r]
if abs(l_v) >... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedSquares(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def sortedSquares_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = [x * x for x in nums]
... | stack_v2_sparse_classes_36k_train_006593 | 931 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "sortedSquares",
"signature": "def sortedSquares(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "sortedSquares_1",
"signature": "def sortedSquares_1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015944 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedSquares(self, nums): :type nums: List[int] :rtype: List[int]
- def sortedSquares_1(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedSquares(self, nums): :type nums: List[int] :rtype: List[int]
- def sortedSquares_1(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 8cdb97bc7588b96b91b1c550afd84e976c1926e0 | <|skeleton|>
class Solution:
def sortedSquares(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def sortedSquares_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedSquares(self, nums):
""":type nums: List[int] :rtype: List[int]"""
n = [x * x for x in nums]
n.sort()
return n
def sortedSquares_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
res = [0 for _ in range(len(nums))]
l, ... | the_stack_v2_python_sparse | Array/977_SquaresofSortedArray.py | ZhengLiangliang1996/Leetcode_ML_Daily | train | 1 | |
a619f71281a498b440e4bf7c2c08604d4d5c542c | [
"dictionary = Dictionary.objects.create()\nfor i in range(100):\n Phrase.objects.create(text='phrase {0}'.format(i), syllables=7, dictionary=dictionary)\nfor i in range(200):\n Phrase.objects.create(text='phrase {0}'.format(i), syllables=5, dictionary=dictionary)\nfor i in range(5):\n User.objects.create_u... | <|body_start_0|>
dictionary = Dictionary.objects.create()
for i in range(100):
Phrase.objects.create(text='phrase {0}'.format(i), syllables=7, dictionary=dictionary)
for i in range(200):
Phrase.objects.create(text='phrase {0}'.format(i), syllables=5, dictionary=dictionary... | TestGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGame:
def setUp(self):
"""Make a dictionary and some Users"""
<|body_0|>
def test_play_game(self):
"""Make a new game, and play a few turns"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dictionary = Dictionary.objects.create()
for i in... | stack_v2_sparse_classes_36k_train_006594 | 2,638 | no_license | [
{
"docstring": "Make a dictionary and some Users",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Make a new game, and play a few turns",
"name": "test_play_game",
"signature": "def test_play_game(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011659 | Implement the Python class `TestGame` described below.
Class description:
Implement the TestGame class.
Method signatures and docstrings:
- def setUp(self): Make a dictionary and some Users
- def test_play_game(self): Make a new game, and play a few turns | Implement the Python class `TestGame` described below.
Class description:
Implement the TestGame class.
Method signatures and docstrings:
- def setUp(self): Make a dictionary and some Users
- def test_play_game(self): Make a new game, and play a few turns
<|skeleton|>
class TestGame:
def setUp(self):
""... | ed2ffd03b71b5229dcb319f7a223a353d1b8b62f | <|skeleton|>
class TestGame:
def setUp(self):
"""Make a dictionary and some Users"""
<|body_0|>
def test_play_game(self):
"""Make a new game, and play a few turns"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGame:
def setUp(self):
"""Make a dictionary and some Users"""
dictionary = Dictionary.objects.create()
for i in range(100):
Phrase.objects.create(text='phrase {0}'.format(i), syllables=7, dictionary=dictionary)
for i in range(200):
Phrase.objects.cre... | the_stack_v2_python_sparse | game/tests.py | sealgair/HaikuBattle | train | 0 | |
d5b3d57a7ca5f8a5a5466c97d2966f91430abc00 | [
"filter_kwargs = {}\nregion_name = self.request.GET.get('region')\nif region_name is not None and region_name != '':\n filter_kwargs['region__name'] = region_name\nreturn self.model.awaiting_fulfillment.filter(**filter_kwargs).prefetch_related('region')",
"context = super().get_context_data(*args, **kwargs)\nc... | <|body_start_0|>
filter_kwargs = {}
region_name = self.request.GET.get('region')
if region_name is not None and region_name != '':
filter_kwargs['region__name'] = region_name
return self.model.awaiting_fulfillment.filter(**filter_kwargs).prefetch_related('region')
<|end_body_... | Display a filterable list of orders. | Awaitingfulfillment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Awaitingfulfillment:
"""Display a filterable list of orders."""
def get_queryset(self):
"""Return a queryset of orders awaiting fulillment."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Return the template context."""
<|body_1|>
def g... | stack_v2_sparse_classes_36k_train_006595 | 25,252 | no_license | [
{
"docstring": "Return a queryset of orders awaiting fulillment.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Return the template context.",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstrin... | 3 | null | Implement the Python class `Awaitingfulfillment` described below.
Class description:
Display a filterable list of orders.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of orders awaiting fulillment.
- def get_context_data(self, *args, **kwargs): Return the template context.
- def get_p... | Implement the Python class `Awaitingfulfillment` described below.
Class description:
Display a filterable list of orders.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of orders awaiting fulillment.
- def get_context_data(self, *args, **kwargs): Return the template context.
- def get_p... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class Awaitingfulfillment:
"""Display a filterable list of orders."""
def get_queryset(self):
"""Return a queryset of orders awaiting fulillment."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Return the template context."""
<|body_1|>
def g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Awaitingfulfillment:
"""Display a filterable list of orders."""
def get_queryset(self):
"""Return a queryset of orders awaiting fulillment."""
filter_kwargs = {}
region_name = self.request.GET.get('region')
if region_name is not None and region_name != '':
filt... | the_stack_v2_python_sparse | fba/views/fba.py | stcstores/stcadmin | train | 0 |
b6f5886e709f7280402502c116ab72683f777af3 | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLNotificationsTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n print('Database characteristics')\n for key in self.db_dict:\n print('%s: %s' % key, self.db_dict[key])\nexcept Val... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLNotificationsTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
print('Database characteristics')
... | " Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized. | SQLNotificationsTable | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLNotificationsTable:
"""" Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_36k_train_006596 | 9,652 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010706 | Implement the Python class `SQLNotificationsTable` described below.
Class description:
" Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | Implement the Python class `SQLNotificationsTable` described below.
Class description:
" Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLNotificationsTable:
"""" Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLNotificationsTable:
"""" Table representing the Notifications database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verbose:
print('SQL Databa... | the_stack_v2_python_sparse | smipyping/_notificationstable.py | KSchopmeyer/smipyping | train | 0 |
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4 | [
"if nmax < 0:\n return ValueError('nmax must be >= 0')\nsuper().__init__(self._Tx, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)\nself.nmax = nmax\nreturn",
"nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif out is None:\n base_shape = X.shape[1:]\n out = np.ndarray((nd, self.nf) + base_shape, dtype=X.dty... | <|body_start_0|>
if nmax < 0:
return ValueError('nmax must be >= 0')
super().__init__(self._Tx, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)
self.nmax = nmax
return
<|end_body_0|>
<|body_start_1|>
nd, nvar = dfun.ndnvar(deriv, var, self.nx)
if out is None:
... | Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree. | ChebyshevT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChebyshevT:
"""Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree."""
def __init__(self, nmax):
"""Create Chebyshev polynomial basis. Parameters ---------- nmax : int The maximum degree."""
<|body_0|>
def _Tx(self... | stack_v2_sparse_classes_36k_train_006597 | 39,055 | permissive | [
{
"docstring": "Create Chebyshev polynomial basis. Parameters ---------- nmax : int The maximum degree.",
"name": "__init__",
"signature": "def __init__(self, nmax)"
},
{
"docstring": "basis evaluation function Use recursion relations for Chebyshev polynomials of the first kind",
"name": "_T... | 2 | stack_v2_sparse_classes_30k_train_016732 | Implement the Python class `ChebyshevT` described below.
Class description:
Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree.
Method signatures and docstrings:
- def __init__(self, nmax): Create Chebyshev polynomial basis. Parameters ---------- nmax : int Th... | Implement the Python class `ChebyshevT` described below.
Class description:
Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree.
Method signatures and docstrings:
- def __init__(self, nmax): Create Chebyshev polynomial basis. Parameters ---------- nmax : int Th... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class ChebyshevT:
"""Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree."""
def __init__(self, nmax):
"""Create Chebyshev polynomial basis. Parameters ---------- nmax : int The maximum degree."""
<|body_0|>
def _Tx(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChebyshevT:
"""Chebyshev polynomials of the first kind, :math:`T_n(x)`. Attributes ---------- nmax : int The maximum degree."""
def __init__(self, nmax):
"""Create Chebyshev polynomial basis. Parameters ---------- nmax : int The maximum degree."""
if nmax < 0:
return ValueErro... | the_stack_v2_python_sparse | nitrogen/special.py | bchangala/nitrogen | train | 11 |
94ef5105334041ba75d2083c963815bedb2a207a | [
"self.id = id\nself.entity_id = entity_id\nself.primary_entity_name = primary_entity_name\nself.status_collection_id = status_collection_id\nself.form_data = form_data\nself.status_title = status_title\nself.editable = editable\nself.status_collection_parent_id = status_collection_parent_id",
"if dictionary is No... | <|body_start_0|>
self.id = id
self.entity_id = entity_id
self.primary_entity_name = primary_entity_name
self.status_collection_id = status_collection_id
self.form_data = form_data
self.status_title = status_title
self.editable = editable
self.status_collec... | Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collection_id (string): TODO: type description here. form_data (string): TODO: ty... | Status | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Status:
"""Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collection_id (string): TODO: type description ... | stack_v2_sparse_classes_36k_train_006598 | 3,374 | permissive | [
{
"docstring": "Constructor for the Status class",
"name": "__init__",
"signature": "def __init__(self, id=None, entity_id=None, primary_entity_name=None, status_collection_id=None, editable=None, form_data=None, status_title=None, status_collection_parent_id=None)"
},
{
"docstring": "Creates an... | 2 | stack_v2_sparse_classes_30k_test_000469 | Implement the Python class `Status` described below.
Class description:
Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collecti... | Implement the Python class `Status` described below.
Class description:
Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collecti... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class Status:
"""Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collection_id (string): TODO: type description ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Status:
"""Implementation of the 'Status' model. TODO: type model description here. Attributes: id (string): TODO: type description here. entity_id (string): TODO: type description here. primary_entity_name (int): TODO: type description here. status_collection_id (string): TODO: type description here. form_da... | the_stack_v2_python_sparse | easybimehlanding/models/status.py | kmelodi/EasyBimehLanding_Python | train | 0 |
669ba5d3ddcb833f1e01465ccec198b7daee4b80 | [
"super(Reader_Downstream, self).__init__()\nself.add = P.Add()\nself.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)\nself.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), bert_layer_norm_weight_shape=(8192,), bert_... | <|body_start_0|>
super(Reader_Downstream, self).__init__()
self.add = P.Add()
self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)
self.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), be... | Downstream model for reader | Reader_Downstream | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
<|body_0|>
def construct(self, para_state, sent_state, state, context_mask):
"""construct function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_006599 | 9,011 | permissive | [
{
"docstring": "init function",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "construct function",
"name": "construct",
"signature": "def construct(self, para_state, sent_state, state, context_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000774 | Implement the Python class `Reader_Downstream` described below.
Class description:
Downstream model for reader
Method signatures and docstrings:
- def __init__(self): init function
- def construct(self, para_state, sent_state, state, context_mask): construct function | Implement the Python class `Reader_Downstream` described below.
Class description:
Downstream model for reader
Method signatures and docstrings:
- def __init__(self): init function
- def construct(self, para_state, sent_state, state, context_mask): construct function
<|skeleton|>
class Reader_Downstream:
"""Down... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
<|body_0|>
def construct(self, para_state, sent_state, state, context_mask):
"""construct function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reader_Downstream:
"""Downstream model for reader"""
def __init__(self):
"""init function"""
super(Reader_Downstream, self).__init__()
self.add = P.Add()
self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)
self.para_outpu... | the_stack_v2_python_sparse | research/nlp/tprr/src/reader_downstream.py | mindspore-ai/models | train | 301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.