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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a5f18d9776b4d2f5ad4db84ef0f98200d8305024 | [
"ulist = struct.unpack(pktt.header_rec, data)\nself.frame = pktt.frame\nself.index = pktt.index\nself.seconds = ulist[0]\nself.usecs = ulist[1]\nself.length_inc = ulist[2]\nself.length_orig = ulist[3]\npktt.pkt.record = self\nself.secs = float(self.seconds) + float(self.usecs) / 1000000.0\nif pktt.tstart is None:\n... | <|body_start_0|>
ulist = struct.unpack(pktt.header_rec, data)
self.frame = pktt.frame
self.index = pktt.index
self.seconds = ulist[0]
self.usecs = ulist[1]
self.length_inc = ulist[2]
self.length_orig = ulist[3]
pktt.pkt.record = self
self.secs = fl... | Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int, # Number of bytes in packet secs ... | Record | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Record:
"""Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int,... | stack_v2_sparse_classes_36k_train_005600 | 4,513 | 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. data: Raw packet data for this layer.",
"name": "__init__",
"signature": "def __init__(self, pktt, data)"
},
{
"docstring": "String representa... | 2 | null | Implement the Python class `Record` described below.
Class description:
Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of byt... | Implement the Python class `Record` described below.
Class description:
Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of byt... | 1f06ae8c73d253141a3434fb9d2c36be3fe768ea | <|skeleton|>
class Record:
"""Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Record:
"""Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int, # Number of ... | the_stack_v2_python_sparse | packet/record.py | MihailRusetskiy/nfs | train | 0 |
de6cc09b3fb872fbee34d0016a7e3c3d79fe9940 | [
"self.head = Block()\nself.tail = Block()\nself.head.after = self.tail\nself.tail.before = self.head\nself.dict = {}",
"if key in self.dict:\n cur_block = self.dict[key]\n cur_block.keys.remove(key)\nelse:\n cur_block = self.head\nif cur_block.val + 1 != cur_block.after.val:\n new_block = Block(cur_bl... | <|body_start_0|>
self.head = Block()
self.tail = Block()
self.head.after = self.tail
self.tail.before = self.head
self.dict = {}
<|end_body_0|>
<|body_start_1|>
if key in self.dict:
cur_block = self.dict[key]
cur_block.keys.remove(key)
els... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k_train_005601 | 2,804 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.",
"name": "inc",
"signature": "def inc(self, key: str) -> None"
},
{
"docstrin... | 5 | null | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | 22c76118bb46fadd2b137fd1a3d40e20fd7538e5 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.head = Block()
self.tail = Block()
self.head.after = self.tail
self.tail.before = self.head
self.dict = {}
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with v... | the_stack_v2_python_sparse | design/432.py | MengSunS/daily-leetcode | train | 0 | |
045502406b37d45cda9fe2299a0c64c3e688a1e9 | [
"is_np = isinstance(inputs, np.ndarray)\nif is_np:\n inputs = torch.tensor(inputs, dtype=torch.float32)\noutputs = torch.nn.functional.relu(inputs)\nif is_np:\n return outputs.numpy()\nreturn outputs",
"serialized = transformer_pb.Layer()\nserialized.relu_data.SetInParent()\nreturn serialized",
"if serial... | <|body_start_0|>
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
outputs = torch.nn.functional.relu(inputs)
if is_np:
return outputs.numpy()
return outputs
<|end_body_0|>
<|body_start_1|>
seriali... | Represents a rectified-linear layer in a network. | ReluLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReluLayer:
"""Represents a rectified-linear layer in a network."""
def compute(self, inputs):
"""Computes ReLU(@inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for use with the transformer server."""
<|body_1|>
def deserialize(cls... | stack_v2_sparse_classes_36k_train_005602 | 1,067 | permissive | [
{
"docstring": "Computes ReLU(@inputs).",
"name": "compute",
"signature": "def compute(self, inputs)"
},
{
"docstring": "Serializes the layer for use with the transformer server.",
"name": "serialize",
"signature": "def serialize(self)"
},
{
"docstring": "Deserializes the layer f... | 3 | stack_v2_sparse_classes_30k_train_015038 | Implement the Python class `ReluLayer` described below.
Class description:
Represents a rectified-linear layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Computes ReLU(@inputs).
- def serialize(self): Serializes the layer for use with the transformer server.
- def deserialize(cls, se... | Implement the Python class `ReluLayer` described below.
Class description:
Represents a rectified-linear layer in a network.
Method signatures and docstrings:
- def compute(self, inputs): Computes ReLU(@inputs).
- def serialize(self): Serializes the layer for use with the transformer server.
- def deserialize(cls, se... | 19abf589e84ee67317134573054c648bb25c244d | <|skeleton|>
class ReluLayer:
"""Represents a rectified-linear layer in a network."""
def compute(self, inputs):
"""Computes ReLU(@inputs)."""
<|body_0|>
def serialize(self):
"""Serializes the layer for use with the transformer server."""
<|body_1|>
def deserialize(cls... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReluLayer:
"""Represents a rectified-linear layer in a network."""
def compute(self, inputs):
"""Computes ReLU(@inputs)."""
is_np = isinstance(inputs, np.ndarray)
if is_np:
inputs = torch.tensor(inputs, dtype=torch.float32)
outputs = torch.nn.functional.relu(in... | the_stack_v2_python_sparse | pysyrenn/frontend/relu_layer.py | 95616ARG/SyReNN | train | 38 |
e7af02f54442c2ace3de8226595d5e687809f7e6 | [
"if class_name not in cls.__mai_class_names.keys():\n text = 'Invalid class name: %s \\n' % class_name\n text += '\\t- Available class names:\\n'\n text += '\\n;'.join(['\\t\\t-%s' % name for name in cls.__mai_class_names.keys()])\n raise Exception(text)\nreturn cls.__mai_class_names[class_name]",
"if... | <|body_start_0|>
if class_name not in cls.__mai_class_names.keys():
text = 'Invalid class name: %s \n' % class_name
text += '\t- Available class names:\n'
text += '\n;'.join(['\t\t-%s' % name for name in cls.__mai_class_names.keys()])
raise Exception(text)
... | :Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names. | ClassNames | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassNames:
""":Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names."""
def get_class_name_from_mai(cls, class_name):
""":Description: This is a class method used to retrieve the class name on MAI class names convention. :param cls... | stack_v2_sparse_classes_36k_train_005603 | 9,714 | permissive | [
{
"docstring": ":Description: This is a class method used to retrieve the class name on MAI class names convention. :param cls: Default class method parameter, part of the signature. :param class_name: the class name from MAI annotation. :return: the class name. :raise: An exception will be raised if *mai_occlu... | 3 | stack_v2_sparse_classes_30k_train_004884 | Implement the Python class `ClassNames` described below.
Class description:
:Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names.
Method signatures and docstrings:
- def get_class_name_from_mai(cls, class_name): :Description: This is a class method used to retrieve... | Implement the Python class `ClassNames` described below.
Class description:
:Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names.
Method signatures and docstrings:
- def get_class_name_from_mai(cls, class_name): :Description: This is a class method used to retrieve... | 597d9dda472c09bafea58ea69853948d63197eca | <|skeleton|>
class ClassNames:
""":Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names."""
def get_class_name_from_mai(cls, class_name):
""":Description: This is a class method used to retrieve the class name on MAI class names convention. :param cls... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassNames:
""":Description: The **ClassNames** class is a container mapping class names from MAI with Valeo class names."""
def get_class_name_from_mai(cls, class_name):
""":Description: This is a class method used to retrieve the class name on MAI class names convention. :param cls: Default cla... | the_stack_v2_python_sparse | scripts/parsers/detection/class_names.py | valeoai/WoodScape | train | 530 |
11de44ea3610d5822b17c150fc766336eb61c8db | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingStaffMember()",
"from .booking_staff_member_base import BookingStaffMemberBase\nfrom .booking_staff_role import BookingStaffRole\nfrom .booking_work_hours import BookingWorkHours\nfrom .booking_staff_member_base import BookingSt... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingStaffMember()
<|end_body_0|>
<|body_start_1|>
from .booking_staff_member_base import BookingStaffMemberBase
from .booking_staff_role import BookingStaffRole
from .booking_... | Represents a staff member who provides services in a business. | BookingStaffMember | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ... | stack_v2_sparse_classes_36k_train_005604 | 5,421 | 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: BookingStaffMember",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_003297 | Implement the Python class `BookingStaffMember` described below.
Class description:
Represents a staff member who provides services in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember: Creates a new instance of the appropri... | Implement the Python class `BookingStaffMember` described below.
Class description:
Represents a staff member who provides services in a business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember: Creates a new instance of the appropri... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookingStaffMember:
"""Represents a staff member who provides services in a business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingStaffMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse nod... | the_stack_v2_python_sparse | msgraph/generated/models/booking_staff_member.py | microsoftgraph/msgraph-sdk-python | train | 135 |
bc859db674b009fefa42df2fcb021019a958e21e | [
"self.enclaveName = enclaveName\nself.enclaveId = enclaveId\nself.isBootstrapNode = isBootstrapNode\nself.enableAutoDiscovery = enableAutoDiscovery\nself.predecessorLocation = None\nself.bootstrapNodeLocations = []\nself.successorList = None\nself.nodeIndex = 0",
"if not bootstrapNodeList:\n return\nelse:\n ... | <|body_start_0|>
self.enclaveName = enclaveName
self.enclaveId = enclaveId
self.isBootstrapNode = isBootstrapNode
self.enableAutoDiscovery = enableAutoDiscovery
self.predecessorLocation = None
self.bootstrapNodeLocations = []
self.successorList = None
self... | This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings | RingInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RingInfo:
"""This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings"""
def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery):
"""Constructor"""
<|body_0|>
def addBootstrapLocations(... | stack_v2_sparse_classes_36k_train_005605 | 1,784 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery)"
},
{
"docstring": "Take the incoming (Node IP, Node Ports) and build a list of node locations.",
"name": "addBootstrapLocations",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_018380 | Implement the Python class `RingInfo` described below.
Class description:
This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings
Method signatures and docstrings:
- def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery): Construc... | Implement the Python class `RingInfo` described below.
Class description:
This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings
Method signatures and docstrings:
- def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery): Construc... | 00d53a43e524d5202afd72b9205f3dcf8169c775 | <|skeleton|>
class RingInfo:
"""This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings"""
def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery):
"""Constructor"""
<|body_0|>
def addBootstrapLocations(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RingInfo:
"""This class holds specific information about a Chord ring. It allows a Chord node to actually be part of several rings"""
def __init__(self, enclaveId, enclaveName, isBootstrapNode, enableAutoDiscovery):
"""Constructor"""
self.enclaveName = enclaveName
self.enclaveId =... | the_stack_v2_python_sparse | network-client/src/gmu/chord/RingInfo.py | danfleck/Class-Chord | train | 1 |
7497a71613116c038a2e3004612e178c77fd05c2 | [
"if not root:\n return '[]'\nres, node_list = ([], collections.deque([root]))\nwhile node_list:\n node = node_list.popleft()\n if node:\n res.append(str(node.val))\n node_list.append(node.left)\n node_list.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join... | <|body_start_0|>
if not root:
return '[]'
res, node_list = ([], collections.deque([root]))
while node_list:
node = node_list.popleft()
if node:
res.append(str(node.val))
node_list.append(node.left)
node_list.appe... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005606 | 3,625 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002052 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d00ca813e657cdd384a342983a1357561e246bac | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
res, node_list = ([], collections.deque([root]))
while node_list:
node = node_list.popleft()
if node:
... | the_stack_v2_python_sparse | JZ/JZ37-serialize-and-deserialize-binary-tree.py | GeekDream-x/LeecodeStory | train | 0 | |
932e11cf3b35b32200010351392ab9bad87617c2 | [
"n_hidden = config['encoder_xy_z_hidden_units']\nn_z = config['ndim_z']\nwith tf.variable_scope('encoder_xy_z', reuse=reuse):\n net_x = tf.layers.dense(input_x, n_hidden, activation=tf.nn.softplus, name='hidden1')\n net_y = tf.layers.dense(input_y, n_hidden, activation=tf.nn.softplus, name='hidden2')\n mer... | <|body_start_0|>
n_hidden = config['encoder_xy_z_hidden_units']
n_z = config['ndim_z']
with tf.variable_scope('encoder_xy_z', reuse=reuse):
net_x = tf.layers.dense(input_x, n_hidden, activation=tf.nn.softplus, name='hidden1')
net_y = tf.layers.dense(input_y, n_hidden, act... | Gaussian M2 VAE network models | GaussianM2VAE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianM2VAE:
"""Gaussian M2 VAE network models"""
def _encoder_xy_z(self, config, input_x, input_y, reuse=False):
"""compute q(z|y,x) = func(theta,...)"""
<|body_0|>
def _encoder_x_y(self, config, inputs, reuse=False):
"""compute q(y|x) using softmax function""... | stack_v2_sparse_classes_36k_train_005607 | 16,118 | no_license | [
{
"docstring": "compute q(z|y,x) = func(theta,...)",
"name": "_encoder_xy_z",
"signature": "def _encoder_xy_z(self, config, input_x, input_y, reuse=False)"
},
{
"docstring": "compute q(y|x) using softmax function",
"name": "_encoder_x_y",
"signature": "def _encoder_x_y(self, config, inpu... | 3 | stack_v2_sparse_classes_30k_train_008713 | Implement the Python class `GaussianM2VAE` described below.
Class description:
Gaussian M2 VAE network models
Method signatures and docstrings:
- def _encoder_xy_z(self, config, input_x, input_y, reuse=False): compute q(z|y,x) = func(theta,...)
- def _encoder_x_y(self, config, inputs, reuse=False): compute q(y|x) usi... | Implement the Python class `GaussianM2VAE` described below.
Class description:
Gaussian M2 VAE network models
Method signatures and docstrings:
- def _encoder_xy_z(self, config, input_x, input_y, reuse=False): compute q(z|y,x) = func(theta,...)
- def _encoder_x_y(self, config, inputs, reuse=False): compute q(y|x) usi... | bfa7ecd595bb761d8b1a8a9c5c4bcaa3dcb81b3c | <|skeleton|>
class GaussianM2VAE:
"""Gaussian M2 VAE network models"""
def _encoder_xy_z(self, config, input_x, input_y, reuse=False):
"""compute q(z|y,x) = func(theta,...)"""
<|body_0|>
def _encoder_x_y(self, config, inputs, reuse=False):
"""compute q(y|x) using softmax function""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianM2VAE:
"""Gaussian M2 VAE network models"""
def _encoder_xy_z(self, config, input_x, input_y, reuse=False):
"""compute q(z|y,x) = func(theta,...)"""
n_hidden = config['encoder_xy_z_hidden_units']
n_z = config['ndim_z']
with tf.variable_scope('encoder_xy_z', reuse=r... | the_stack_v2_python_sparse | VAE_dgm/code/vae_M2.py | tomokishii/Generative-TF | train | 0 |
4cb837bc3744c0c085b0cee3f7cbb1dcc5ff9942 | [
"need = collections.defaultdict(int)\nfor c in t:\n need[c] += 1\nneed_length = len(t)\nl = 0\nres = (0, len(s) + 1)\nfor r, c in enumerate(s):\n if need[c] > 0:\n need_length -= 1\n need[c] -= 1\n if need_length == 0:\n while True:\n c = s[l]\n if need[c] == 0:\n ... | <|body_start_0|>
need = collections.defaultdict(int)
for c in t:
need[c] += 1
need_length = len(t)
l = 0
res = (0, len(s) + 1)
for r, c in enumerate(s):
if need[c] > 0:
need_length -= 1
need[c] -= 1
if need_l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minWindow1(self, s: str, t: str) -> str:
"""执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户"""
<|body_0|>
def minWindow(self, s: str, t: str) -> str:
"""执行用时: 104 ms , 在所有 Python3 提交中击败了 68.17% 的用户 内存消耗: 15.1 MB... | stack_v2_sparse_classes_36k_train_005608 | 4,035 | no_license | [
{
"docstring": "执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户",
"name": "minWindow1",
"signature": "def minWindow1(self, s: str, t: str) -> str"
},
{
"docstring": "执行用时: 104 ms , 在所有 Python3 提交中击败了 68.17% 的用户 内存消耗: 15.1 MB , 在所有 Python3 提交中击败了 56.11% 的... | 2 | stack_v2_sparse_classes_30k_train_005083 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow1(self, s: str, t: str) -> str: 执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户
- def minWindow(self, s: str, t: str) -> st... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minWindow1(self, s: str, t: str) -> str: 执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户
- def minWindow(self, s: str, t: str) -> st... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def minWindow1(self, s: str, t: str) -> str:
"""执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户"""
<|body_0|>
def minWindow(self, s: str, t: str) -> str:
"""执行用时: 104 ms , 在所有 Python3 提交中击败了 68.17% 的用户 内存消耗: 15.1 MB... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minWindow1(self, s: str, t: str) -> str:
"""执行用时: 68 ms , 在所有 Python3 提交中击败了 99.48% 的用户 内存消耗: 14.8 MB , 在所有 Python3 提交中击败了 98.89% 的用户"""
need = collections.defaultdict(int)
for c in t:
need[c] += 1
need_length = len(t)
l = 0
res = (0, l... | the_stack_v2_python_sparse | 最小覆盖子串.py | nomboy/leetcode | train | 0 | |
60d16f481e801278c6e7c2dface2085d10815b8a | [
"QDialog.__init__(self, parent)\nself.setupUi(self)\nself.xlsFile = ''\nself.db_path = ''",
"print('on_pushButton_select_xls_clicked')\nself.xlsFile = QFileDialog.getOpenFileName(self, u'选取文件', './', 'Excel Files (*.xls;*.xlsx)')[0]\nprint(self.xlsFile)",
"if self.xlsFile == '':\n QMessageBox.warning(self, u... | <|body_start_0|>
QDialog.__init__(self, parent)
self.setupUi(self)
self.xlsFile = ''
self.db_path = ''
<|end_body_0|>
<|body_start_1|>
print('on_pushButton_select_xls_clicked')
self.xlsFile = QFileDialog.getOpenFileName(self, u'选取文件', './', 'Excel Files (*.xls;*.xlsx)')[... | Class documentation goes here. | Dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_select_xls_clicked(self):
"""Slot documentation goes here."""
<|body_1|>
def on_pushButton_create_db_clicked(self):
"... | stack_v2_sparse_classes_36k_train_005609 | 1,965 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Slot documentation goes here.",
"name": "on_pushButton_select_xls_clicked",
"signature": "def on_pushButton_select_xls_clicked(self)"
},
{
"docstring": "Slot docume... | 3 | stack_v2_sparse_classes_30k_train_015824 | Implement the Python class `Dialog` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def on_pushButton_select_xls_clicked(self): Slot documentation goes here.
- def on_pushButton_create_db_clicked(self): Slot document... | Implement the Python class `Dialog` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def on_pushButton_select_xls_clicked(self): Slot documentation goes here.
- def on_pushButton_create_db_clicked(self): Slot document... | 6ec9027b679bbb707436b9a4095d995265b266c8 | <|skeleton|>
class Dialog:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_select_xls_clicked(self):
"""Slot documentation goes here."""
<|body_1|>
def on_pushButton_create_db_clicked(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dialog:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
QDialog.__init__(self, parent)
self.setupUi(self)
self.xlsFile = ''
self.db_path = ''
def on_pushButton_select_xls_clicked(self):
"""Slot documentation goes... | the_stack_v2_python_sparse | src/utils/Create_DB.py | fzero17/college_wish | train | 0 |
62386ebc8b047e999fc824228178cfa5c6203114 | [
"self.size = 0\nself.head, self.tail = (Node(0), Node(0))\nself.head.next = self.tail\nself.tail.prev = self.head",
"if index < 0 or index >= self.size:\n return -1\nif index + 1 < self.size - index:\n ptr = self.head\n for _ in range(index + 1):\n ptr = ptr.next\nelse:\n ptr = self.tail\n f... | <|body_start_0|>
self.size = 0
self.head, self.tail = (Node(0), Node(0))
self.head.next = self.tail
self.tail.prev = self.head
<|end_body_0|>
<|body_start_1|>
if index < 0 or index >= self.size:
return -1
if index + 1 < self.size - index:
ptr = se... | MyLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1."""
<|body_1|>
def addAtHead(self, val:... | stack_v2_sparse_classes_36k_train_005610 | 3,992 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1.",
"name": "get",
"signature": "def get(self, index: int) -> int"
},... | 6 | stack_v2_sparse_classes_30k_train_013725 | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali... | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali... | 30198097904994e34f8321926ad2a2cadc8b5940 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1."""
<|body_1|>
def addAtHead(self, val:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
self.size = 0
self.head, self.tail = (Node(0), Node(0))
self.head.next = self.tail
self.tail.prev = self.head
def get(self, index: int) -> int:
"""Get the value of the index-th nod... | the_stack_v2_python_sparse | coding/leetcode/707-design-linked-list/solution.py | teckoo/interview_public | train | 2 | |
de6220be4044b22a681712b18ee242d493a00ff0 | [
"parameters_key = registry_key.GetSubkeyByName('Parameters')\nif not parameters_key:\n return None\nreturn self._GetValueFromKey(parameters_key, 'ServiceDll')",
"service_type = self._GetValueFromKey(registry_key, 'Type')\nstart_type = self._GetValueFromKey(registry_key, 'Start')\nif None in (service_type, star... | <|body_start_0|>
parameters_key = registry_key.GetSubkeyByName('Parameters')
if not parameters_key:
return None
return self._GetValueFromKey(parameters_key, 'ServiceDll')
<|end_body_0|>
<|body_start_1|>
service_type = self._GetValueFromKey(registry_key, 'Type')
start... | Plug-in to format the Services and Drivers keys having Type and Start. | ServicesPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinre... | stack_v2_sparse_classes_36k_train_005611 | 4,192 | permissive | [
{
"docstring": "Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: str: path of the service DLL or None.",
"name": "_GetServiceDll",
"signature": "def _GetSe... | 2 | stack_v2_sparse_classes_30k_train_010451 | Implement the Python class `ServicesPlugin` described below.
Class description:
Plug-in to format the Services and Drivers keys having Type and Start.
Method signatures and docstrings:
- def _GetServiceDll(self, registry_key): Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a ... | Implement the Python class `ServicesPlugin` described below.
Class description:
Plug-in to format the Services and Drivers keys having Type and Start.
Method signatures and docstrings:
- def _GetServiceDll(self, registry_key): Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinreg.WinRegistry... | the_stack_v2_python_sparse | plaso/parsers/winreg_plugins/services.py | log2timeline/plaso | train | 1,506 |
1f4d47c84e44ae70d4a2cb87a6e3db858d545bc6 | [
"super(RMinimumSeeker, self).__init__()\nself._callback = callback\nself._accuracy = accuracy",
"start_value = self._callback(start)\nend_value = self._callback(end)\nmiddle_value = self._callback(middle)\nreturn middle_value < start_value and middle_value < end_value",
"start = -2\nend = -1\nprint()\nfor i in ... | <|body_start_0|>
super(RMinimumSeeker, self).__init__()
self._callback = callback
self._accuracy = accuracy
<|end_body_0|>
<|body_start_1|>
start_value = self._callback(start)
end_value = self._callback(end)
middle_value = self._callback(middle)
return middle_val... | Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции. | RMinimumSeeker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум... | stack_v2_sparse_classes_36k_train_005612 | 5,946 | no_license | [
{
"docstring": "Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум. Значение точности по умолчанию 0.01",
"name": "__init__",
"signature": "def __init__(self, callback, accuracy=0.01)"
},
{
"docstring": "Вспомогательный метод, определяюща... | 5 | stack_v2_sparse_classes_30k_test_000100 | Implement the Python class `RMinimumSeeker` described below.
Class description:
Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции.
Method signatures and docstrings:
- def __init__(self, callback, accuracy=0.01): Конструктор класса, входными аргументами которого я... | Implement the Python class `RMinimumSeeker` described below.
Class description:
Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции.
Method signatures and docstrings:
- def __init__(self, callback, accuracy=0.01): Конструктор класса, входными аргументами которого я... | 8c05e15417e99d7236744fe9f960f4d6b09e4e31 | <|skeleton|>
class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RMinimumSeeker:
"""Класс, реализующий функции для поиска минимума на отрезке, и поиска отрезка, содержащего минимум функции."""
def __init__(self, callback, accuracy=0.01):
"""Конструктор класса, входными аргументами которого являются функция и точность, с которой вычисляется минимум. Значение то... | the_stack_v2_python_sparse | educational/optimization-methods/one-dimentional-optimization/lab1.py | montreal91/workshop | train | 3 |
e8aab57f7e5c4bc33db56a6e9f4c246e2ef3ca34 | [
"self.name = name\nself.reuse = False\nself.ngf = ngf\nself.norm = norm\nself.is_training = is_training\nself.image_size = image_size\nself.rgb = rgb",
"with tf.variable_scope(self.name):\n c7s1_32 = ops.c7s1_k(input, self.ngf, is_training=self.is_training, norm=self.norm, reuse=self.reuse, name='c7s1_32')\n ... | <|body_start_0|>
self.name = name
self.reuse = False
self.ngf = ngf
self.norm = norm
self.is_training = is_training
self.image_size = image_size
self.rgb = rgb
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(self.name):
c7s1_32 = ops.c7... | Generator for FP-GAN | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generator for FP-GAN"""
def __init__(self, name, is_training, ngf=64, norm='instance', image_size=None, rgb=True):
"""Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer norm: instance or batch image_size: (width, height) rgb: co... | stack_v2_sparse_classes_36k_train_005613 | 3,644 | no_license | [
{
"docstring": "Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer norm: instance or batch image_size: (width, height) rgb: color or gray-scale images",
"name": "__init__",
"signature": "def __init__(self, name, is_training, ngf=64, norm='instance', image_size=N... | 3 | stack_v2_sparse_classes_30k_train_006758 | Implement the Python class `Generator` described below.
Class description:
Generator for FP-GAN
Method signatures and docstrings:
- def __init__(self, name, is_training, ngf=64, norm='instance', image_size=None, rgb=True): Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer no... | Implement the Python class `Generator` described below.
Class description:
Generator for FP-GAN
Method signatures and docstrings:
- def __init__(self, name, is_training, ngf=64, norm='instance', image_size=None, rgb=True): Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer no... | dfb046f3e752dc71aa2c20d63aa75f80edc3f560 | <|skeleton|>
class Generator:
"""Generator for FP-GAN"""
def __init__(self, name, is_training, ngf=64, norm='instance', image_size=None, rgb=True):
"""Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer norm: instance or batch image_size: (width, height) rgb: co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Generator for FP-GAN"""
def __init__(self, name, is_training, ngf=64, norm='instance', image_size=None, rgb=True):
"""Args: name: will be used as scope is_training: boolean ngf: number of filters in first layer norm: instance or batch image_size: (width, height) rgb: color or gray-s... | the_stack_v2_python_sparse | src/models/generator.py | mcbuehler/FP-GAN | train | 1 |
b6092eaa5309f1b8468e71d863691f59f8d98fc1 | [
"res = []\nfor ele in nums:\n if ele != 0:\n res.append(ele)\nfor i in range(len(nums)):\n if i < len(res):\n nums[i] = res[i]\n else:\n nums[i] = 0\nreturn nums",
"j = 0\nfor i in range(len(nums)):\n if nums[i] != 0:\n nums[j] = nums[i]\n j += 1\nwhile j < len(nums)... | <|body_start_0|>
res = []
for ele in nums:
if ele != 0:
res.append(ele)
for i in range(len(nums)):
if i < len(res):
nums[i] = res[i]
else:
nums[i] = 0
return nums
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums):
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def moveZeroes3(self, nums):
"""Do no... | stack_v2_sparse_classes_36k_train_005614 | 1,252 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums)"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self, nums)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_011981 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums): Do not return anything, modify nums in-place instead.
- def moveZ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums): Do not return anything, modify nums in-place instead.
- def moveZ... | 0ac672a1582707fcaa6b6ad1f2a1d927034447df | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums):
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
def moveZeroes3(self, nums):
"""Do no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums):
"""Do not return anything, modify nums in-place instead."""
res = []
for ele in nums:
if ele != 0:
res.append(ele)
for i in range(len(nums)):
if i < len(res):
nums[i] = res[i]
... | the_stack_v2_python_sparse | Chapter01_ArrayProblem/leetcode283.py | HuichuanLI/alogritme-interview | train | 1 | |
3c2ae1718db51e2625f9bb18367957de2df00787 | [
"super(ReparametrisedGaussianEncoder, self).__init__(data_dim=data_dim, noise_dim=noise_dim, latent_dim=latent_dim, network_architecture=network_architecture, name=name or 'Reparametrised Gaussian Encoder')\nlatent_mean, latent_log_var = get_network_by_name['reparametrised_encoder'][network_architecture](self.data_... | <|body_start_0|>
super(ReparametrisedGaussianEncoder, self).__init__(data_dim=data_dim, noise_dim=noise_dim, latent_dim=latent_dim, network_architecture=network_architecture, name=name or 'Reparametrised Gaussian Encoder')
latent_mean, latent_log_var = get_network_by_name['reparametrised_encoder'][netwo... | A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space | ReparametrisedGaussianEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReparametrisedGaussianEncoder:
"""A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space"""
def __init__(self, data_dim, noise_dim, latent_dim, netw... | stack_v2_sparse_classes_36k_train_005615 | 23,104 | permissive | [
{
"docstring": "Args: data_dim: int, flattened data space dimensionality noise_dim: int, flattened noise space dimensionality latent_dim: int, flattened latent space dimensionality network_architecture: str, the architecture name for the body of the reparametrised Gaussian Encoder model name: str, optional iden... | 2 | stack_v2_sparse_classes_30k_train_006042 | Implement the Python class `ReparametrisedGaussianEncoder` described below.
Class description:
A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space
Method signatures and do... | Implement the Python class `ReparametrisedGaussianEncoder` described below.
Class description:
A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space
Method signatures and do... | 545e4993c90622f05b5b7ba0183bc07d5972371e | <|skeleton|>
class ReparametrisedGaussianEncoder:
"""A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space"""
def __init__(self, data_dim, noise_dim, latent_dim, netw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReparametrisedGaussianEncoder:
"""A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space"""
def __init__(self, data_dim, noise_dim, latent_dim, network_architect... | the_stack_v2_python_sparse | playground/models/networks/encoder.py | gdikov/vae-playground | train | 1 |
f5b67815139aa272c85da5ffe68c50e6c1f78c98 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AccessPackageSubject()",
"from .access_package_subject_type import AccessPackageSubjectType\nfrom .connected_organization import ConnectedOrganization\nfrom .entity import Entity\nfrom .access_package_subject_type import AccessPackageS... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AccessPackageSubject()
<|end_body_0|>
<|body_start_1|>
from .access_package_subject_type import AccessPackageSubjectType
from .connected_organization import ConnectedOrganization
... | AccessPackageSubject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPackageSubject:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageSubject:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k_train_005616 | 4,277 | 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: AccessPackageSubject",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `AccessPackageSubject` described below.
Class description:
Implement the AccessPackageSubject class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageSubject: Creates a new instance of the appropriate class based o... | Implement the Python class `AccessPackageSubject` described below.
Class description:
Implement the AccessPackageSubject class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageSubject: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AccessPackageSubject:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageSubject:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccessPackageSubject:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessPackageSubject:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/access_package_subject.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
cb5b1ac731e7b5872d937e03a159d4c86f78f2f1 | [
"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... | Missing associated documentation comment in .proto file. | RoleServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation comm... | stack_v2_sparse_classes_36k_train_005617 | 10,249 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "table",
"signature": "def table(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_all",
"signature": "def get_all(self, request, context)"... | 6 | stack_v2_sparse_classes_30k_train_003806 | Implement the Python class `RoleServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing associat... | Implement the Python class `RoleServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing associat... | 47d57bda959afa0b53d65e996b08e2f3b650c1a8 | <|skeleton|>
class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation comm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
rai... | the_stack_v2_python_sparse | pix/authentication_client/protos/role_pb2_grpc.py | thecodeworkers/testing-clients | train | 0 |
017b37c769daf77cd903fe6a84f8de7b5a114787 | [
"super().__init__()\nself.report_cer = report_cer\nself.report_wer = report_wer\nself.char_list = char_list\nself.space = sym_space\nself.blank = sym_blank\nself.idx_blank = self.char_list.index(self.blank)\nif self.space in self.char_list:\n self.idx_space = self.char_list.index(self.space)\nelse:\n self.idx... | <|body_start_0|>
super().__init__()
self.report_cer = report_cer
self.report_wer = report_wer
self.char_list = char_list
self.space = sym_space
self.blank = sym_blank
self.idx_blank = self.char_list.index(self.blank)
if self.space in self.char_list:
... | Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <blank> :return: | ErrorCalculator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorCalculator:
"""Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <blank> :return:"""
def __init__(sel... | stack_v2_sparse_classes_36k_train_005618 | 13,020 | permissive | [
{
"docstring": "Construct an ErrorCalculator object.",
"name": "__init__",
"signature": "def __init__(self, char_list, sym_space, sym_blank, report_cer=False, report_wer=False)"
},
{
"docstring": "Calculate sentence-level WER/CER score. :param paddle.Tensor ys_hat: prediction (batch, seqlen) :pa... | 6 | null | Implement the Python class `ErrorCalculator` described below.
Class description:
Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <b... | Implement the Python class `ErrorCalculator` described below.
Class description:
Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <b... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ErrorCalculator:
"""Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <blank> :return:"""
def __init__(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorCalculator:
"""Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: List[str] :param sym_space: <space> :param sym_blank: <blank> :return:"""
def __init__(self, char_list,... | the_stack_v2_python_sparse | paddlespeech/s2t/utils/error_rate.py | anniyanvr/DeepSpeech-1 | train | 0 |
af0bb29f4dc9d611f315eb7dc2da56779673a3f0 | [
"content_type = ContentType.objects.get_for_model(instance.__class__)\nobj_id = instance.id\nqueryset = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None)\nreturn queryset",
"content_type = ContentType.objects.get(model=instance)\nprint(content_type)\nuuid = uuid_g... | <|body_start_0|>
content_type = ContentType.objects.get_for_model(instance.__class__)
obj_id = instance.id
queryset = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None)
return queryset
<|end_body_0|>
<|body_start_1|>
content_type ... | ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim. | CommentManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentManager:
"""ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim."""
def filter_by_model(self, instance):
"""to khat e zir ma az instance.__class__ estefade kardim ke modelio migire ke to view ya to (model prop... | stack_v2_sparse_classes_36k_train_005619 | 7,695 | permissive | [
{
"docstring": "to khat e zir ma az instance.__class__ estefade kardim ke modelio migire ke to view ya to (model propert) behesh pas midim.",
"name": "filter_by_model",
"signature": "def filter_by_model(self, instance)"
},
{
"docstring": "tu inja darim modeli ke dare request midea ro migirim(fil... | 2 | stack_v2_sparse_classes_30k_train_008576 | Implement the Python class `CommentManager` described below.
Class description:
ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim.
Method signatures and docstrings:
- def filter_by_model(self, instance): to khat e zir ma az instance.__class__ estef... | Implement the Python class `CommentManager` described below.
Class description:
ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim.
Method signatures and docstrings:
- def filter_by_model(self, instance): to khat e zir ma az instance.__class__ estef... | aef47922fdd6488550881ed9d42bf30a0d33a32a | <|skeleton|>
class CommentManager:
"""ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim."""
def filter_by_model(self, instance):
"""to khat e zir ma az instance.__class__ estefade kardim ke modelio migire ke to view ya to (model prop... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentManager:
"""ye custom filter sakhtim ke to view ya (model property) rahat tar betunim content_object vase comment haro bargardoonim."""
def filter_by_model(self, instance):
"""to khat e zir ma az instance.__class__ estefade kardim ke modelio migire ke to view ya to (model propert) behesh p... | the_stack_v2_python_sparse | src/comments/models.py | m3h-D/Myinfoblog | train | 0 |
e51d63b34f5f6b620b75cfde5d90e8b669f81647 | [
"d = {}\nfor s in strs:\n k = tuple(sorted(s))\n d.setdefault(k, [])\n d[k].append(s)\nreturn [v for k, v in d.items()]",
"rets = []\nwhile strs:\n s_letters = [0] * 26\n for c in strs[0]:\n s_letters[ord(c) - ord('a')] += 1\n ret = [0]\n for i in range(1, len(strs)):\n table = ... | <|body_start_0|>
d = {}
for s in strs:
k = tuple(sorted(s))
d.setdefault(k, [])
d[k].append(s)
return [v for k, v in d.items()]
<|end_body_0|>
<|body_start_1|>
rets = []
while strs:
s_letters = [0] * 26
for c in strs[0]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagramsSlow(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {}
... | stack_v2_sparse_classes_36k_train_005620 | 1,284 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagramsSlow",
"signature": "def groupAnagramsSlow(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagramsSlow(self, strs): :type strs: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagramsSlow(self, strs): :type strs: List[str] :rtype: List[List[str]]
<|skeleton|>
clas... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagramsSlow(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
d = {}
for s in strs:
k = tuple(sorted(s))
d.setdefault(k, [])
d[k].append(s)
return [v for k, v in d.items()]
def groupAnagramsSlow(self, strs)... | the_stack_v2_python_sparse | cs_notes/string/group_anagrams.py | hwc1824/LeetCodeSolution | train | 0 | |
dcc2919a43a908b00018bfd4e7c9e0b2b75b82cc | [
"P = self.parent()\nct = P.cartan_type()\nsym = P._symmetric_form_matrix\nif ct.is_finite():\n iset = P.index_set()\nelse:\n iset = P.index_set() + ('delta',)\nreturn sum((cl * sym[iset.index(ml), iset.index(mr)] * cr for ml, cl in self for mr, cr in la))",
"L = self.parent()\nif base_ring is None:\n bas... | <|body_start_0|>
P = self.parent()
ct = P.cartan_type()
sym = P._symmetric_form_matrix
if ct.is_finite():
iset = P.index_set()
else:
iset = P.index_set() + ('delta',)
return sum((cl * sym[iset.index(ml), iset.index(mr)] * cr for ml, cl in self for ... | ElementMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElementMethods:
def symmetric_form(self, la):
"""Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dimensional Lie Algebras for more details. .. WARNING:: For affine root systems, if you are not working in ... | stack_v2_sparse_classes_36k_train_005621 | 46,194 | no_license | [
{
"docstring": "Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dimensional Lie Algebras for more details. .. WARNING:: For affine root systems, if you are not working in the extended weight lattice/space, this may return incorr... | 2 | stack_v2_sparse_classes_30k_train_011960 | Implement the Python class `ElementMethods` described below.
Class description:
Implement the ElementMethods class.
Method signatures and docstrings:
- def symmetric_form(self, la): Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dime... | Implement the Python class `ElementMethods` described below.
Class description:
Implement the ElementMethods class.
Method signatures and docstrings:
- def symmetric_form(self, la): Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dime... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class ElementMethods:
def symmetric_form(self, la):
"""Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dimensional Lie Algebras for more details. .. WARNING:: For affine root systems, if you are not working in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElementMethods:
def symmetric_form(self, la):
"""Return the symmetric form of ``self`` with ``la``. Return the pairing `( | )` on the weight lattice. See Chapter 6 in Kac, Infinite Dimensional Lie Algebras for more details. .. WARNING:: For affine root systems, if you are not working in the extended w... | the_stack_v2_python_sparse | sage/src/sage/combinat/root_system/weight_lattice_realizations.py | bopopescu/geosci | train | 0 | |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"assert isinstance(request, HttpRequest)\nqapp_id = request.GET.get('qapp_id', None)\nqapp = Qapp.objects.get(id=qapp_id)\nexisting_section_a = SectionA.objects.filter(qapp=qapp).first()\nif existing_section_a:\n form = SectionAForm(instance=existing_section_a)\nelse:\n form = SectionAForm({'qapp': qapp, 'a3'... | <|body_start_0|>
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_id)
existing_section_a = SectionA.objects.filter(qapp=qapp).first()
if existing_section_a:
form = SectionAForm(instance=existing_section... | Class for processing QAPP Section A (A.3 and later) information. | SectionAView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionAView:
"""Class for processing QAPP Section A (A.3 and later) information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section A (A.3 and later)."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post ... | stack_v2_sparse_classes_36k_train_005622 | 36,787 | no_license | [
{
"docstring": "Return the index page for QAPP Section A (A.3 and later).",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process the post request with a SectionA form filled out.",
"name": "post",
"signature": "def post(self, request, *args, **... | 2 | null | Implement the Python class `SectionAView` described below.
Class description:
Class for processing QAPP Section A (A.3 and later) information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section A (A.3 and later).
- def post(self, request, *args, **kwarg... | Implement the Python class `SectionAView` described below.
Class description:
Class for processing QAPP Section A (A.3 and later) information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section A (A.3 and later).
- def post(self, request, *args, **kwarg... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class SectionAView:
"""Class for processing QAPP Section A (A.3 and later) information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section A (A.3 and later)."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SectionAView:
"""Class for processing QAPP Section A (A.3 and later) information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section A (A.3 and later)."""
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
5cc93d9f4db40844f0211e02d154a2f25a39587b | [
"N = len(s)\nif N == 0:\n return 0\nP = [[False for _ in range(N)] for _ in range(N)]\nfor i in range(N):\n P[i][i] = True\nmaxLen = 1\nfor j in range(1, N):\n for i in range(j - 1, -1, -1):\n if P[i][j - 1]:\n P[i][j] = s[i] != s[j] and P[i][j - 1] and P[i + 1][j]\n if P[i][j]:\n ... | <|body_start_0|>
N = len(s)
if N == 0:
return 0
P = [[False for _ in range(N)] for _ in range(N)]
for i in range(N):
P[i][i] = True
maxLen = 1
for j in range(1, N):
for i in range(j - 1, -1, -1):
if P[i][j - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
"""最后一个超时 :type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
"""哈希表,滑动窗口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(s)
if N == 0:
return 0
... | stack_v2_sparse_classes_36k_train_005623 | 1,356 | no_license | [
{
"docstring": "最后一个超时 :type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": "哈希表,滑动窗口",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): 最后一个超时 :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): 哈希表,滑动窗口 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): 最后一个超时 :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): 哈希表,滑动窗口
<|skeleton|>
class Solution:
def lengthOfLongestSu... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
"""最后一个超时 :type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
"""哈希表,滑动窗口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
"""最后一个超时 :type s: str :rtype: int"""
N = len(s)
if N == 0:
return 0
P = [[False for _ in range(N)] for _ in range(N)]
for i in range(N):
P[i][i] = True
maxLen = 1
for j in range(1,... | the_stack_v2_python_sparse | 剑指/二刷/最长不含重复字符的子字符串_M.py | 2226171237/Algorithmpractice | train | 0 | |
4ab7f15d5cce58c48ce54158750da6107aba0ad0 | [
"result = []\nlevel = [root]\nwhile root and level:\n current_nodes, next_level = ([], [])\n for node in level:\n current_nodes.append(node.val)\n if node.left:\n next_level.append(node.left)\n if node.right:\n next_level.append(node.right)\n result.append(current... | <|body_start_0|>
result = []
level = [root]
while root and level:
current_nodes, next_level = ([], [])
for node in level:
current_nodes.append(node.val)
if node.left:
next_level.append(node.left)
if node.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
"""FUNNY"""
<|body_0|>
def levelOrderBottom(self, root):
"""NOT SO FUNNY"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
level = [root]
while root and level:
current... | stack_v2_sparse_classes_36k_train_005624 | 1,702 | no_license | [
{
"docstring": "FUNNY",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
},
{
"docstring": "NOT SO FUNNY",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000551 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): FUNNY
- def levelOrderBottom(self, root): NOT SO FUNNY | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root): FUNNY
- def levelOrderBottom(self, root): NOT SO FUNNY
<|skeleton|>
class Solution:
def levelOrderBottom(self, root):
"""FUNNY"""
... | 4ec4f9fbb0ef07ea13207654a619cfdb709cc78c | <|skeleton|>
class Solution:
def levelOrderBottom(self, root):
"""FUNNY"""
<|body_0|>
def levelOrderBottom(self, root):
"""NOT SO FUNNY"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom(self, root):
"""FUNNY"""
result = []
level = [root]
while root and level:
current_nodes, next_level = ([], [])
for node in level:
current_nodes.append(node.val)
if node.left:
... | the_stack_v2_python_sparse | 91_bt_level_order_traversal_bottom_up.py | gautamgitspace/leetcode_30-day_challenge | train | 0 | |
81dfe3d467f4ebd488d844ab22c7b6b1b597a601 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('Create5GInstance', params, headers=headers)\n response = json.loads(body)\n model = models.Create5GInstanceResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if i... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('Create5GInstance', params, headers=headers)
response = json.loads(body)
model = models.Create5GInstanceResponse()
model._deserialize(response['R... | CsxgClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsxgClient:
def Create5GInstance(self, request):
"""创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceRequest` :rtype: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceResponse`"""
... | stack_v2_sparse_classes_36k_train_005625 | 5,397 | permissive | [
{
"docstring": "创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceRequest` :rtype: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceResponse`",
"name": "Create5GInstance",
"signature": "def Create5GInstan... | 5 | null | Implement the Python class `CsxgClient` described below.
Class description:
Implement the CsxgClient class.
Method signatures and docstrings:
- def Create5GInstance(self, request): 创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInsta... | Implement the Python class `CsxgClient` described below.
Class description:
Implement the CsxgClient class.
Method signatures and docstrings:
- def Create5GInstance(self, request): 创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInsta... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class CsxgClient:
def Create5GInstance(self, request):
"""创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceRequest` :rtype: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceResponse`"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CsxgClient:
def Create5GInstance(self, request):
"""创建5G入云服务接口 :param request: Request instance for Create5GInstance. :type request: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceRequest` :rtype: :class:`tencentcloud.csxg.v20230303.models.Create5GInstanceResponse`"""
try:
... | the_stack_v2_python_sparse | tencentcloud/csxg/v20230303/csxg_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
de5dfcc3d1b229fd0305f526c76535afbe00d5b7 | [
"self._number = number\nname = Tiledict.get(buildtype).__name__\nself._buildfilter = make_namedclass_filter(name)\nself.active = True",
"members = game.getmembers()\nnames = [m.__class__.__name__ for m in members]\nif len(filter(self._buildfilter, names)) >= self._number:\n return True\nreturn False"
] | <|body_start_0|>
self._number = number
name = Tiledict.get(buildtype).__name__
self._buildfilter = make_namedclass_filter(name)
self.active = True
<|end_body_0|>
<|body_start_1|>
members = game.getmembers()
names = [m.__class__.__name__ for m in members]
if len(f... | Purpose is to check a number of given types are built. | CheckTypeBuilt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckTypeBuilt:
"""Purpose is to check a number of given types are built."""
def __init__(self, number, buildtype):
"""buildtype is the name of the object we need number of"""
<|body_0|>
def met(self, level, game):
"""Check there is a given number of the type we ... | stack_v2_sparse_classes_36k_train_005626 | 2,579 | no_license | [
{
"docstring": "buildtype is the name of the object we need number of",
"name": "__init__",
"signature": "def __init__(self, number, buildtype)"
},
{
"docstring": "Check there is a given number of the type we want built.",
"name": "met",
"signature": "def met(self, level, game)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020743 | Implement the Python class `CheckTypeBuilt` described below.
Class description:
Purpose is to check a number of given types are built.
Method signatures and docstrings:
- def __init__(self, number, buildtype): buildtype is the name of the object we need number of
- def met(self, level, game): Check there is a given n... | Implement the Python class `CheckTypeBuilt` described below.
Class description:
Purpose is to check a number of given types are built.
Method signatures and docstrings:
- def __init__(self, number, buildtype): buildtype is the name of the object we need number of
- def met(self, level, game): Check there is a given n... | 6005c91a690a2bbd3f2107bcc2a77ec72ac6bd51 | <|skeleton|>
class CheckTypeBuilt:
"""Purpose is to check a number of given types are built."""
def __init__(self, number, buildtype):
"""buildtype is the name of the object we need number of"""
<|body_0|>
def met(self, level, game):
"""Check there is a given number of the type we ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckTypeBuilt:
"""Purpose is to check a number of given types are built."""
def __init__(self, number, buildtype):
"""buildtype is the name of the object we need number of"""
self._number = number
name = Tiledict.get(buildtype).__name__
self._buildfilter = make_namedclass... | the_stack_v2_python_sparse | levelevents.py | jtrain/supapowa | train | 1 |
f5f41b8b1c8b4dac5e3bcf693a8b5570a8e21a35 | [
"if 'lat' in udims and 'lon' in udims and self._dim_in(['lat', 'lon'], source_coordinates, eval_coordinates) and source_coordinates['lat'].is_uniform and source_coordinates['lon'].is_uniform and eval_coordinates['lat'].is_uniform and eval_coordinates['lon'].is_uniform:\n return udims\nreturn tuple()",
"if len(... | <|body_start_0|>
if 'lat' in udims and 'lon' in udims and self._dim_in(['lat', 'lon'], source_coordinates, eval_coordinates) and source_coordinates['lat'].is_uniform and source_coordinates['lon'].is_uniform and eval_coordinates['lat'].is_uniform and eval_coordinates['lon'].is_uniform:
return udims
... | Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio | RasterioInterpolator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterioInterpolator:
"""Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio"""
def can_interpolate(self, udims, source_coordinates, eval_coordinates):
"""{interpolator_can_interpolate... | stack_v2_sparse_classes_36k_train_005627 | 4,214 | permissive | [
{
"docstring": "{interpolator_can_interpolate}",
"name": "can_interpolate",
"signature": "def can_interpolate(self, udims, source_coordinates, eval_coordinates)"
},
{
"docstring": "{interpolator_interpolate}",
"name": "interpolate",
"signature": "def interpolate(self, udims, source_coord... | 2 | stack_v2_sparse_classes_30k_train_005933 | Implement the Python class `RasterioInterpolator` described below.
Class description:
Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio
Method signatures and docstrings:
- def can_interpolate(self, udims, source_coor... | Implement the Python class `RasterioInterpolator` described below.
Class description:
Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio
Method signatures and docstrings:
- def can_interpolate(self, udims, source_coor... | 66d8ec7a9086e39347e32922e15a3f59cb055415 | <|skeleton|>
class RasterioInterpolator:
"""Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio"""
def can_interpolate(self, udims, source_coordinates, eval_coordinates):
"""{interpolator_can_interpolate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasterioInterpolator:
"""Rasterio Interpolation Attributes ---------- {interpolator_attributes} rasterio_interpolators : list of str Interpolator methods available via rasterio"""
def can_interpolate(self, udims, source_coordinates, eval_coordinates):
"""{interpolator_can_interpolate}"""
... | the_stack_v2_python_sparse | podpac/core/interpolation/rasterio_interpolator.py | creare-com/podpac | train | 48 |
e92308341c7fdc1374457ec4b6a619072cdcf45d | [
"self.log = log\nif e is not None or operation is not None:\n self.handle_exception(e, operation)\nreturn",
"result = {'error': None}\nexc_type, exc_obj, exc_tb = exc_info()\nfname = path_split(exc_tb.tb_frame.f_code.co_filename)[frame]\nresult['error'] = '%s, %s, %s' % (str(exc_type), str(fname), str(exc_tb.t... | <|body_start_0|>
self.log = log
if e is not None or operation is not None:
self.handle_exception(e, operation)
return
<|end_body_0|>
<|body_start_1|>
result = {'error': None}
exc_type, exc_obj, exc_tb = exc_info()
fname = path_split(exc_tb.tb_frame.f_code.co_... | Object for exception handling. | ExceptionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted ... | stack_v2_sparse_classes_36k_train_005628 | 3,299 | no_license | [
{
"docstring": "Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted (that failed). @return: None.",
"name": "__init__",
"signature": "def __init__(self, log, e=None, operation=Non... | 3 | stack_v2_sparse_classes_30k_train_014450 | Implement the Python class `ExceptionHandler` described below.
Class description:
Object for exception handling.
Method signatures and docstrings:
- def __init__(self, log, e=None, operation=None): Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseExc... | Implement the Python class `ExceptionHandler` described below.
Class description:
Object for exception handling.
Method signatures and docstrings:
- def __init__(self, log, e=None, operation=None): Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseExc... | cc14053da99f6671b12e03ef5dc1717c3d9e4aa5 | <|skeleton|>
class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted (that failed)... | the_stack_v2_python_sparse | exceptionhandler.py | jslatte/tartaros | train | 1 |
9c62560105cc0cce95532315a357d22d164ece7d | [
"queryset = UserCategory.objects.filter(parent=None)\nserializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})\nreturn Response(serializer.data)",
"queryset = UserCategory.objects.all()\ncategory = get_object_or_404(queryset, pk=pk)\nserializer = UserCategoryChildrenSerialize... | <|body_start_0|>
queryset = UserCategory.objects.filter(parent=None)
serializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = UserCategory.objects.all()
category = g... | UserCategoryViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of user categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_005629 | 9,571 | no_license | [
{
"docstring": "Returns the tree of all user categories via GET. Allows any.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Returns a particular branch of user categories via GET. Allows any.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk)... | 2 | stack_v2_sparse_classes_30k_test_000674 | Implement the Python class `UserCategoryViewSet` described below.
Class description:
Implement the UserCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all user categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of user... | Implement the Python class `UserCategoryViewSet` described below.
Class description:
Implement the UserCategoryViewSet class.
Method signatures and docstrings:
- def list(self, request): Returns the tree of all user categories via GET. Allows any.
- def retrieve(self, request, pk): Returns a particular branch of user... | 78ef668111d7552c98795c8aa07698b642cf09a5 | <|skeleton|>
class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
<|body_0|>
def retrieve(self, request, pk):
"""Returns a particular branch of user categories via GET. Allows any."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCategoryViewSet:
def list(self, request):
"""Returns the tree of all user categories via GET. Allows any."""
queryset = UserCategory.objects.filter(parent=None)
serializer = UserCategoryChildrenSerializer(queryset, many=True, context={'request': request})
return Response(se... | the_stack_v2_python_sparse | backend/core/views.py | lawrencejberry/bridge | train | 0 | |
30bb0fc51cb65232d6e68a25e1cf7f75f874c680 | [
"super().__init__()\nact_kwargs = act_kwargs if act_kwargs is not None else {}\nself.out_channels = in_channels if out_channels is None else out_channels\nself.hidden_channels = int(mlp_ratio * in_channels)\nself.fc1 = nn.Conv2d(in_channels, self.hidden_channels, 1, bias=bias)\nself.dwconv = nn.Conv2d(in_channels, ... | <|body_start_0|>
super().__init__()
act_kwargs = act_kwargs if act_kwargs is not None else {}
self.out_channels = in_channels if out_channels is None else out_channels
self.hidden_channels = int(mlp_ratio * in_channels)
self.fc1 = nn.Conv2d(in_channels, self.hidden_channels, 1, b... | ConvMlp | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvMlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""Mlp layer implemented with dws convolution. Input shape: (B, in_channels, H, W... | stack_v2_sparse_classes_36k_train_005630 | 6,969 | permissive | [
{
"docstring": "Mlp layer implemented with dws convolution. Input shape: (B, in_channels, H, W). Output shape: (B, out_channels, H, W). Parameters ---------- in_channels : int Number of input features. mlp_ratio : int, default=2 Scaling factor to get the number hidden features from the `in_channels`. activation... | 2 | null | Implement the Python class `ConvMlp` described below.
Class description:
Implement the ConvMlp class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, *... | Implement the Python class `ConvMlp` described below.
Class description:
Implement the ConvMlp class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, *... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class ConvMlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""Mlp layer implemented with dws convolution. Input shape: (B, in_channels, H, W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvMlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""Mlp layer implemented with dws convolution. Input shape: (B, in_channels, H, W). Output shap... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/mlp.py | okunator/cellseg_models.pytorch | train | 43 | |
4fcfea9a0fd02e8a2f0bd81d71752036d1e61103 | [
"head_list, heap_size = self.build_binary_heap(alist)\norderedList = []\nwhile len(head_list) > 1:\n orderedList.append(self.delMin(head_list))\nreturn orderedList",
"min_key = heap_list[1]\nheap_list[1] = heap_list[-1]\nheap_list.pop()\nheap_size = len(heap_list) - 2\nself.down(heap_list, heap_size, 1)\nretur... | <|body_start_0|>
head_list, heap_size = self.build_binary_heap(alist)
orderedList = []
while len(head_list) > 1:
orderedList.append(self.delMin(head_list))
return orderedList
<|end_body_0|>
<|body_start_1|>
min_key = heap_list[1]
heap_list[1] = heap_list[-1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def heapSort(self, alist):
"""不基于已实现的二叉堆结构,直接实现 :param alist: :return:"""
<|body_0|>
def delMin(self, heap_list):
"""找到二叉堆最小值,并从二叉堆中删除 :param heap_list: :return:"""
<|body_1|>
def build_binary_heap(self, alist):
"""创建一个初始二叉堆 :param alis... | stack_v2_sparse_classes_36k_train_005631 | 2,529 | no_license | [
{
"docstring": "不基于已实现的二叉堆结构,直接实现 :param alist: :return:",
"name": "heapSort",
"signature": "def heapSort(self, alist)"
},
{
"docstring": "找到二叉堆最小值,并从二叉堆中删除 :param heap_list: :return:",
"name": "delMin",
"signature": "def delMin(self, heap_list)"
},
{
"docstring": "创建一个初始二叉堆 :par... | 5 | stack_v2_sparse_classes_30k_train_018558 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def heapSort(self, alist): 不基于已实现的二叉堆结构,直接实现 :param alist: :return:
- def delMin(self, heap_list): 找到二叉堆最小值,并从二叉堆中删除 :param heap_list: :return:
- def build_binary_heap(self, alis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def heapSort(self, alist): 不基于已实现的二叉堆结构,直接实现 :param alist: :return:
- def delMin(self, heap_list): 找到二叉堆最小值,并从二叉堆中删除 :param heap_list: :return:
- def build_binary_heap(self, alis... | 97cc61fefe0bedf5161687aab92fb09b0df990e2 | <|skeleton|>
class Solution:
def heapSort(self, alist):
"""不基于已实现的二叉堆结构,直接实现 :param alist: :return:"""
<|body_0|>
def delMin(self, heap_list):
"""找到二叉堆最小值,并从二叉堆中删除 :param heap_list: :return:"""
<|body_1|>
def build_binary_heap(self, alist):
"""创建一个初始二叉堆 :param alis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def heapSort(self, alist):
"""不基于已实现的二叉堆结构,直接实现 :param alist: :return:"""
head_list, heap_size = self.build_binary_heap(alist)
orderedList = []
while len(head_list) > 1:
orderedList.append(self.delMin(head_list))
return orderedList
def delMin(... | the_stack_v2_python_sparse | code/sort/heap_sort2.py | JiaXingBinggan/For_work | train | 0 | |
b1c7feca0dbf8032cdcb575c9b199aa56ea4b327 | [
"try:\n user = get_user_model().objects.get(email=username)\n if user.check_password(password):\n return user\nexcept get_user_model().DoesNotExist:\n return None",
"try:\n return get_user_model().objects.get(pk=user_id)\nexcept get_user_model().DoesNotExist:\n return None"
] | <|body_start_0|>
try:
user = get_user_model().objects.get(email=username)
if user.check_password(password):
return user
except get_user_model().DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
try:
return get_user_model().... | Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair. | EmailAuthBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, username=None, password=None):
"""Authenticate a user based on email address as the user name."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_005632 | 824 | no_license | [
{
"docstring": "Authenticate a user based on email address as the user name.",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Get a User object from the user_id.",
"name": "get_user",
"signature": "def get_user(self, user_id... | 2 | null | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate a user based... | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair.
Method signatures and docstrings:
- def authenticate(self, username=None, password=None): Authenticate a user based... | d3223ec6306ded2374b282efa28e408e1a43b6fb | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, username=None, password=None):
"""Authenticate a user based on email address as the user name."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, username=None, password=None):
"""Authenticate a user based on email address as the user name."""
try:
user =... | the_stack_v2_python_sparse | mirskutils/backends.py | mirskytech/mirskutils | train | 2 |
31b4e5269f4bf45738094914c65fd56db1e4650e | [
"User = get_user_model()\nuser = User.objects.create_user(email='normal@user.com', password='foo')\nself.assertEqual(user.email, 'normal@user.com')\nself.assertTrue(user.is_active)\nself.assertFalse(user.is_staff)\nself.assertFalse(user.is_admin)\ntry:\n self.assertNotExist(user.username)\nexcept AttributeError:... | <|body_start_0|>
User = get_user_model()
user = User.objects.create_user(email='normal@user.com', password='foo')
self.assertEqual(user.email, 'normal@user.com')
self.assertTrue(user.is_active)
self.assertFalse(user.is_staff)
self.assertFalse(user.is_admin)
try:
... | Verifies creation of user and superuser with CustomUserManager | UsersManagersTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersManagersTests:
"""Verifies creation of user and superuser with CustomUserManager"""
def test_create_user(self):
"""Verifies creation of regular user"""
<|body_0|>
def test_create_superuser(self):
"""Verifies creation of superuser(admin)"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_005633 | 9,069 | no_license | [
{
"docstring": "Verifies creation of regular user",
"name": "test_create_user",
"signature": "def test_create_user(self)"
},
{
"docstring": "Verifies creation of superuser(admin)",
"name": "test_create_superuser",
"signature": "def test_create_superuser(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021631 | Implement the Python class `UsersManagersTests` described below.
Class description:
Verifies creation of user and superuser with CustomUserManager
Method signatures and docstrings:
- def test_create_user(self): Verifies creation of regular user
- def test_create_superuser(self): Verifies creation of superuser(admin) | Implement the Python class `UsersManagersTests` described below.
Class description:
Verifies creation of user and superuser with CustomUserManager
Method signatures and docstrings:
- def test_create_user(self): Verifies creation of regular user
- def test_create_superuser(self): Verifies creation of superuser(admin)
... | 8cb619ed9208800fffec63e7aca7f4ef97098152 | <|skeleton|>
class UsersManagersTests:
"""Verifies creation of user and superuser with CustomUserManager"""
def test_create_user(self):
"""Verifies creation of regular user"""
<|body_0|>
def test_create_superuser(self):
"""Verifies creation of superuser(admin)"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersManagersTests:
"""Verifies creation of user and superuser with CustomUserManager"""
def test_create_user(self):
"""Verifies creation of regular user"""
User = get_user_model()
user = User.objects.create_user(email='normal@user.com', password='foo')
self.assertEqual(us... | the_stack_v2_python_sparse | inkind/tests.py | Michal-Rakowski/donation-project | train | 1 |
0328717107adbad153b5f04de82d09e18b1369ad | [
"ProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')\nfor pc in ProtectedClass.objects.all():\n if pc.value == 'disability-including-temporary-or-recovery':\n pc.value = 'disability'\n pc.save()",
"ProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')\nfor pc in ProtectedClass... | <|body_start_0|>
ProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')
for pc in ProtectedClass.objects.all():
if pc.value == 'disability-including-temporary-or-recovery':
pc.value = 'disability'
pc.save()
<|end_body_0|>
<|body_start_1|>
Prot... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forward(apps, schema_editor):
"""Set Disability Class Choice to correct field."""
<|body_0|>
def reverse(apps, schema_editor):
"""Revert back to faulty value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ProtectedClass = apps.get_mo... | stack_v2_sparse_classes_36k_train_005634 | 1,033 | no_license | [
{
"docstring": "Set Disability Class Choice to correct field.",
"name": "forward",
"signature": "def forward(apps, schema_editor)"
},
{
"docstring": "Revert back to faulty value",
"name": "reverse",
"signature": "def reverse(apps, schema_editor)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011732 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forward(apps, schema_editor): Set Disability Class Choice to correct field.
- def reverse(apps, schema_editor): Revert back to faulty value | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forward(apps, schema_editor): Set Disability Class Choice to correct field.
- def reverse(apps, schema_editor): Revert back to faulty value
<|skeleton|>
class Migration:
... | d5d6338cf54a09c2f6c88cd3affa3d7f49bdf693 | <|skeleton|>
class Migration:
def forward(apps, schema_editor):
"""Set Disability Class Choice to correct field."""
<|body_0|>
def reverse(apps, schema_editor):
"""Revert back to faulty value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forward(apps, schema_editor):
"""Set Disability Class Choice to correct field."""
ProtectedClass = apps.get_model('cts_forms', 'ProtectedClass')
for pc in ProtectedClass.objects.all():
if pc.value == 'disability-including-temporary-or-recovery':
... | the_stack_v2_python_sparse | crt_portal/cts_forms/migrations/0148_update_disability_protected_class_choice.py | usdoj-crt/crt-portal | train | 18 | |
da0769d54e487fc6ae7fa93ca21729c80ed88e16 | [
"if 'pk_parent' in kwargs.keys():\n self.parent = kwargs['pk_parent']\nreturn super(ConteudoCreate, self).dispatch(request, *args, **kwargs)",
"initial = super(ConteudoCreate, self).get_initial()\nprint(kwargs)\nif hasattr(self, 'parent'):\n initial['parent'] = self.parent\nreturn initial",
"self.object =... | <|body_start_0|>
if 'pk_parent' in kwargs.keys():
self.parent = kwargs['pk_parent']
return super(ConteudoCreate, self).dispatch(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
initial = super(ConteudoCreate, self).get_initial()
print(kwargs)
if hasattr(self... | View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional | ConteudoCreate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConteudoCreate:
"""View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional"""
def dispatch(self, request, *args, **kwargs):
"""Pega valores dos args"""
<|body_0|>
def get_initial(self, *args, **kwargs):
"""Altera o valor inicial dos campos"""
... | stack_v2_sparse_classes_36k_train_005635 | 9,497 | permissive | [
{
"docstring": "Pega valores dos args",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Altera o valor inicial dos campos",
"name": "get_initial",
"signature": "def get_initial(self, *args, **kwargs)"
},
{
"docstring": "Altera o ... | 3 | stack_v2_sparse_classes_30k_train_010904 | Implement the Python class `ConteudoCreate` described below.
Class description:
View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Pega valores dos args
- def get_initial(self, *args, **kwargs): Altera o valor inici... | Implement the Python class `ConteudoCreate` described below.
Class description:
View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Pega valores dos args
- def get_initial(self, *args, **kwargs): Altera o valor inici... | 37cf33d05be8b0195b10845061ca893ba5e814dd | <|skeleton|>
class ConteudoCreate:
"""View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional"""
def dispatch(self, request, *args, **kwargs):
"""Pega valores dos args"""
<|body_0|>
def get_initial(self, *args, **kwargs):
"""Altera o valor inicial dos campos"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConteudoCreate:
"""View para criar um Conteudo. Dispatch Args: pk_parent : int - opicional"""
def dispatch(self, request, *args, **kwargs):
"""Pega valores dos args"""
if 'pk_parent' in kwargs.keys():
self.parent = kwargs['pk_parent']
return super(ConteudoCreate, self)... | the_stack_v2_python_sparse | escola/views_conteudo.py | vini84200/medusa2 | train | 1 |
c0938f07b1ab9c2e08d49e1fe41c9444a815eb9b | [
"res = 0\nwhile n > 0:\n res += n & 1\n n = n >> 1\nreturn res",
"res = 0\nwhile n > 0:\n res += n & n - 1\n n = n >> 1\nreturn res"
] | <|body_start_0|>
res = 0
while n > 0:
res += n & 1
n = n >> 1
return res
<|end_body_0|>
<|body_start_1|>
res = 0
while n > 0:
res += n & n - 1
n = n >> 1
return res
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
while n > 0:
res += n & 1
... | stack_v2_sparse_classes_36k_train_005636 | 1,531 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000439 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | 03ec8138fc1fe955a8b00c2b519f33f20cc4a435 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
res = 0
while n > 0:
res += n & 1
n = n >> 1
return res
def hammingWeight(self, n):
""":type n: int :rtype: int"""
res = 0
while n > 0:
res += n... | the_stack_v2_python_sparse | 6-12leetcode/面试题15二进制中1的个数.py | Wang663/leetcode | train | 1 | |
cdccf9ce61e3ef8700b9ec2d4199ea011ca33e3a | [
"for chunk in iterator_in:\n chunk.flags.writeable = True\n self.fake_symbol_replace(chunk)\n self.fudge_up(chunk)\n yield chunk",
"real_symbol = chunk[symbol_column][0]\nnew_fake_symbol = bytes(sample(self.ascii_bytes, len(real_symbol)))\nfake_symbol = self.symbol_map.setdefault(real_symbol, new_fake... | <|body_start_0|>
for chunk in iterator_in:
chunk.flags.writeable = True
self.fake_symbol_replace(chunk)
self.fudge_up(chunk)
yield chunk
<|end_body_0|>
<|body_start_1|>
real_symbol = chunk[symbol_column][0]
new_fake_symbol = bytes(sample(self.asci... | Take a TAQ file and make it fake while preserving structure | Sanitizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sanitizer:
"""Take a TAQ file and make it fake while preserving structure"""
def _process_chunks(self, iterator_in):
"""Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a dropped chunk."""
<|body_0|>
def fake_symbol... | stack_v2_sparse_classes_36k_train_005637 | 7,380 | no_license | [
{
"docstring": "Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a dropped chunk.",
"name": "_process_chunks",
"signature": "def _process_chunks(self, iterator_in)"
},
{
"docstring": "Make a new fake symbol if we don't have it yet, and retu... | 3 | null | Implement the Python class `Sanitizer` described below.
Class description:
Take a TAQ file and make it fake while preserving structure
Method signatures and docstrings:
- def _process_chunks(self, iterator_in): Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a ... | Implement the Python class `Sanitizer` described below.
Class description:
Take a TAQ file and make it fake while preserving structure
Method signatures and docstrings:
- def _process_chunks(self, iterator_in): Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a ... | 85969e681b9c74e24e60cc524a952f9585ea9ce9 | <|skeleton|>
class Sanitizer:
"""Take a TAQ file and make it fake while preserving structure"""
def _process_chunks(self, iterator_in):
"""Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a dropped chunk."""
<|body_0|>
def fake_symbol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sanitizer:
"""Take a TAQ file and make it fake while preserving structure"""
def _process_chunks(self, iterator_in):
"""Return chunks with changed symbols and fudged times and values. For now, successive calls will result in a dropped chunk."""
for chunk in iterator_in:
chunk.... | the_stack_v2_python_sparse | Example_of_processing_tick data/marketflow/marketflow/processing.py | alexanu/Python_Trading_Snippets | train | 18 |
a5357f0b30ea36f1f8b3ccb87307cf759de0eea5 | [
"self._selected = measurement\nself._should_stop.clear()\nself._buffer_empty.set()\nself._thread = Thread(target=self.run)\nself._thread.daemon = True\nself._thread.start()",
"self._should_stop.set()\nself._queue_not_empty.set()\nself._thread.join()",
"with self._lock:\n self._queue.append(widget)\n self.... | <|body_start_0|>
self._selected = measurement
self._should_stop.clear()
self._buffer_empty.set()
self._thread = Thread(target=self.run)
self._thread.daemon = True
self._thread.start()
<|end_body_0|>
<|body_start_1|>
self._should_stop.set()
self._queue_not... | Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus. | MeasurementTracker | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasurementTracker:
"""Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus."""
def start(self, measurement):
"""Start the working thread."""
<|body_0|>
def stop(self):
"""Stop the working thread."... | stack_v2_sparse_classes_36k_train_005638 | 4,623 | permissive | [
{
"docstring": "Start the working thread.",
"name": "start",
"signature": "def start(self, measurement)"
},
{
"docstring": "Stop the working thread.",
"name": "stop",
"signature": "def stop(self)"
},
{
"docstring": "Enqueue a newly selected widget.",
"name": "enqueue",
"s... | 6 | null | Implement the Python class `MeasurementTracker` described below.
Class description:
Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus.
Method signatures and docstrings:
- def start(self, measurement): Start the working thread.
- def stop(self): Stop... | Implement the Python class `MeasurementTracker` described below.
Class description:
Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus.
Method signatures and docstrings:
- def start(self, measurement): Start the working thread.
- def stop(self): Stop... | bb003a0ec74b622e1fb0e1dbfdd052f43531bfbd | <|skeleton|>
class MeasurementTracker:
"""Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus."""
def start(self, measurement):
"""Start the working thread."""
<|body_0|>
def stop(self):
"""Stop the working thread."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasurementTracker:
"""Object responsible for tracking the currently edited measurement. The tracking relies on the last focus that got focus."""
def start(self, measurement):
"""Start the working thread."""
self._selected = measurement
self._should_stop.clear()
self._buff... | the_stack_v2_python_sparse | exopy/measurement/workspace/measurement_tracking.py | Exopy/exopy | train | 17 |
ea95a52785afd23244349e0127b8c46ceddf84d5 | [
"floating_ip_pools = self._client.floating_ip_pools.list()\nassert floating_ip_pools\nfloating_ip = self._client.floating_ips.create(pool=floating_ip_pools[0].name)\nif check:\n self.check_floating_ip_presence(floating_ip)\nreturn floating_ip",
"self._client.floating_ips.delete(floating_ip)\nif check:\n sel... | <|body_start_0|>
floating_ip_pools = self._client.floating_ip_pools.list()
assert floating_ip_pools
floating_ip = self._client.floating_ips.create(pool=floating_ip_pools[0].name)
if check:
self.check_floating_ip_presence(floating_ip)
return floating_ip
<|end_body_0|>
... | Floating IP steps. | FloatingIpSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatingIpSteps:
"""Floating IP steps."""
def create_floating_ip(self, check=True):
"""Step to create floating IP."""
<|body_0|>
def delete_floating_ip(self, floating_ip, check=True):
"""Step to delete floating IP."""
<|body_1|>
def check_floating_ip... | stack_v2_sparse_classes_36k_train_005639 | 1,920 | no_license | [
{
"docstring": "Step to create floating IP.",
"name": "create_floating_ip",
"signature": "def create_floating_ip(self, check=True)"
},
{
"docstring": "Step to delete floating IP.",
"name": "delete_floating_ip",
"signature": "def delete_floating_ip(self, floating_ip, check=True)"
},
{... | 3 | null | Implement the Python class `FloatingIpSteps` described below.
Class description:
Floating IP steps.
Method signatures and docstrings:
- def create_floating_ip(self, check=True): Step to create floating IP.
- def delete_floating_ip(self, floating_ip, check=True): Step to delete floating IP.
- def check_floating_ip_pre... | Implement the Python class `FloatingIpSteps` described below.
Class description:
Floating IP steps.
Method signatures and docstrings:
- def create_floating_ip(self, check=True): Step to create floating IP.
- def delete_floating_ip(self, floating_ip, check=True): Step to delete floating IP.
- def check_floating_ip_pre... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class FloatingIpSteps:
"""Floating IP steps."""
def create_floating_ip(self, check=True):
"""Step to create floating IP."""
<|body_0|>
def delete_floating_ip(self, floating_ip, check=True):
"""Step to delete floating IP."""
<|body_1|>
def check_floating_ip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloatingIpSteps:
"""Floating IP steps."""
def create_floating_ip(self, check=True):
"""Step to create floating IP."""
floating_ip_pools = self._client.floating_ip_pools.list()
assert floating_ip_pools
floating_ip = self._client.floating_ips.create(pool=floating_ip_pools[0]... | the_stack_v2_python_sparse | stepler/nova/steps/floating_ips.py | Mirantis/stepler | train | 16 |
78ca9b1c8856fd09dd34f21ab787e126ca099b1e | [
"if server_ip == '' and server_port != 0 or (server_ip != '' and server_port == 0):\n raise Exception('server_ip和server_port必须同时指定')\nself._server_ip = server_ip\nself._server_port = server_port\nself._service_name = service_name\nself._host = host",
"headers = {'org': org, 'user': user}\nroute_name = ''\nserv... | <|body_start_0|>
if server_ip == '' and server_port != 0 or (server_ip != '' and server_port == 0):
raise Exception('server_ip和server_port必须同时指定')
self._server_ip = server_ip
self._server_port = server_port
self._service_name = service_name
self._host = host
<|end_bod... | GatewayClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GatewayClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和servi... | stack_v2_sparse_classes_36k_train_005640 | 4,486 | permissive | [
{
"docstring": "初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和service_name同时设置,server_ip优先级更高 :param host: 指定sdk请求服务的host名称, 如cmdb.easyops-only.com",
"name": "__ini... | 3 | null | Implement the Python class `GatewayClient` described below.
Class description:
Implement the GatewayClient class.
Method signatures and docstrings:
- def __init__(self, server_ip='', server_port=0, service_name='', host=''): 初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_p... | Implement the Python class `GatewayClient` described below.
Class description:
Implement the GatewayClient class.
Method signatures and docstrings:
- def __init__(self, server_ip='', server_port=0, service_name='', host=''): 初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_p... | adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0 | <|skeleton|>
class GatewayClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和servi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GatewayClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和service_name同时设置,se... | the_stack_v2_python_sparse | user_service_sdk/api/gateway/gateway_client.py | easyopsapis/easyops-api-python | train | 5 | |
acf4c73c79b518e78bca131c5f02448595510438 | [
"self.vec = vec2d\nself.next_index = 0\nself.list_index = 0\nself.list_len = [len(one) for one in vec2d]",
"if self.next_index == self.list_len[self.list_index] - 1:\n num = self.vec[self.list_index][self.next_index]\n self.next_index = 0\n self.list_index += 1\nelse:\n num = self.vec[self.list_index]... | <|body_start_0|>
self.vec = vec2d
self.next_index = 0
self.list_index = 0
self.list_len = [len(one) for one in vec2d]
<|end_body_0|>
<|body_start_1|>
if self.next_index == self.list_len[self.list_index] - 1:
num = self.vec[self.list_index][self.next_index]
... | Vector2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_005641 | 1,245 | permissive | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_007917 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | cb2ed3524431aea2b204fe66797f9850bbe506a9 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec = vec2d
self.next_index = 0
self.list_index = 0
self.list_len = [len(one) for one in vec2d]
def next(self):
""":rtype: int"""
if se... | the_stack_v2_python_sparse | archive/python/Python/unsorted/251.flatten-2d-vector.py | linfengzhou/LeetCode | train | 0 | |
6e18186c0091e5c140ce129f443d961adfc415bd | [
"self.__init_environment(params['random_state'])\nself.__build_model(**params['model'])\nself.__build_components(**params['hyper'])\nreturn",
"random.seed(random_state)\nnp.random.seed(random_state)\ntorch.manual_seed(random_state)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False... | <|body_start_0|>
self.__init_environment(params['random_state'])
self.__build_model(**params['model'])
self.__build_components(**params['hyper'])
return
<|end_body_0|>
<|body_start_1|>
random.seed(random_state)
np.random.seed(random_state)
torch.manual_seed(rando... | GCN模型训练与预测 | Pipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipeline:
"""GCN模型训练与预测"""
def __init__(self, **params):
"""GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_bias': True, 'dropout': 0.5 }, 'hyper': { 'lr': 1e-2, 'epo... | stack_v2_sparse_classes_36k_train_005642 | 4,906 | permissive | [
{
"docstring": "GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_bias': True, 'dropout': 0.5 }, 'hyper': { 'lr': 1e-2, 'epochs': 100, 'weight_decay': 5e-4 } }",
"name": "__init__",
"signa... | 6 | stack_v2_sparse_classes_30k_train_011534 | Implement the Python class `Pipeline` described below.
Class description:
GCN模型训练与预测
Method signatures and docstrings:
- def __init__(self, **params): GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_b... | Implement the Python class `Pipeline` described below.
Class description:
GCN模型训练与预测
Method signatures and docstrings:
- def __init__(self, **params): GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_b... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class Pipeline:
"""GCN模型训练与预测"""
def __init__(self, **params):
"""GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_bias': True, 'dropout': 0.5 }, 'hyper': { 'lr': 1e-2, 'epo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pipeline:
"""GCN模型训练与预测"""
def __init__(self, **params):
"""GCN模型训练与预测 加载GCN模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'random_state': 42, 'model': { 'input_dim': 1433, 'output_dim': 7, 'hidden_dim': 16, 'use_bias': True, 'dropout': 0.5 }, 'hyper': { 'lr': 1e-2, 'epochs': 100, 'w... | the_stack_v2_python_sparse | Node/GCN/script/pipeline.py | robbinc91/GNN-Pytorch | train | 0 |
d58a4da7cbf47ab83a5ce8df84a343e7b438624a | [
"super(DeleteGroupTest, self).setUp()\nself.create_group0_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=0)\nself.group0 = self.create_group0_response.entity\nself.assertEquals(self.create_group0_response.status_code, 201)\nself.policy_up_execute = {'change': 2}\nself.policy_webhook ... | <|body_start_0|>
super(DeleteGroupTest, self).setUp()
self.create_group0_response = self.autoscale_behaviors.create_scaling_group_given(gc_min_entities=0)
self.group0 = self.create_group0_response.entity
self.assertEquals(self.create_group0_response.status_code, 201)
self.policy_... | System tests to verify various delete scaling group scenarios | DeleteGroupTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
<|body_0|>
def test_system_delete_group_with_minent... | stack_v2_sparse_classes_36k_train_005643 | 5,662 | permissive | [
{
"docstring": "Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "A scaling group cannot be deleted when minentities > zero",
"name": "test_system_delete_group_w... | 6 | stack_v2_sparse_classes_30k_train_021289 | Implement the Python class `DeleteGroupTest` described below.
Class description:
System tests to verify various delete scaling group scenarios
Method signatures and docstrings:
- def setUp(self): Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0
- def test... | Implement the Python class `DeleteGroupTest` described below.
Class description:
System tests to verify various delete scaling group scenarios
Method signatures and docstrings:
- def setUp(self): Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0
- def test... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
<|body_0|>
def test_system_delete_group_with_minent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteGroupTest:
"""System tests to verify various delete scaling group scenarios"""
def setUp(self):
"""Create 2 scaling groups, one with minentities>0 with a scaling up policy and webhook another with minentities=0"""
super(DeleteGroupTest, self).setUp()
self.create_group0_respo... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/system/group/test_system_delete_group.py | rackerlabs/otter | train | 20 |
9ad801a0a1a8d9928fd4ff38598bd752efce7cfa | [
"self.working_directory = working_directory\nself.num_epochs = num_epochs\nself.batch_size = batch_size\nself.lr = lr\nself.wd = wd\nself.drop_prob = drop_prob\nself.debug = debug\nself.scheme = scheme\nself.warmstart_dir = warmstart_dir\nself.dataset = dataset\nself.n_workers = n_workers\nself.data_path = 'data/ti... | <|body_start_0|>
self.working_directory = working_directory
self.num_epochs = num_epochs
self.batch_size = batch_size
self.lr = lr
self.wd = wd
self.drop_prob = drop_prob
self.debug = debug
self.scheme = scheme
self.warmstart_dir = warmstart_dir
... | DARTSWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DARTSWorker:
def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=Fals... | stack_v2_sparse_classes_36k_train_005644 | 7,772 | permissive | [
{
"docstring": "Args: working_directory (str): directory where results are written num_epochs (int): number of total epochs to train the baselearner batch_size (int): mini-batch size during training scheme (str): scheme name dataset (str): dataset name warmstart_dir (str): directory where previous results are s... | 3 | stack_v2_sparse_classes_30k_test_000947 | Implement the Python class `DARTSWorker` described below.
Class description:
Implement the DARTSWorker class.
Method signatures and docstrings:
- def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr... | Implement the Python class `DARTSWorker` described below.
Class description:
Implement the DARTSWorker class.
Method signatures and docstrings:
- def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr... | 1c54786c30acd6e19eb9708204bffc86b58ea272 | <|skeleton|>
class DARTSWorker:
def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=Fals... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DARTSWorker:
def __init__(self, working_directory, num_epochs, batch_size, *args, scheme='nes_re', dataset='fmnist', warmstart_dir=None, debug=False, n_workers=4, only_predict=False, lr=0.025, wd=0.0003, drop_prob=0.3, anchor=False, anch_coeff=1, full_train=False, n_datapoints=None, oneshot=False, saved_model... | the_stack_v2_python_sparse | nes/darts/worker.py | automl/nes | train | 33 | |
c1d7048c3e5a17afbefa28324fd1b08cd7b6f825 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.CoordinateFrame = CoordinateFrame\nself.DeltaArp = DeltaArp\nself.DeltaVarp = DeltaVarp\nself.DeltaRange = DeltaRange\nsuper(ProjectionPerturbationType, self).__init__(**kw... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.CoordinateFrame = CoordinateFrame
self.DeltaArp = DeltaArp
self.DeltaVarp = DeltaVarp
self.DeltaRang... | Basic information required for SICD/SIDD projection model perturbation. | ProjectionPerturbationType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectionPerturbationType:
"""Basic information required for SICD/SIDD projection model perturbation."""
def __init__(self, CoordinateFrame=None, DeltaArp=None, DeltaVarp=None, DeltaRange=None, **kwargs):
"""Parameters ---------- CoordinateFrame : str DeltaArp : None|XYZType|numpy.n... | stack_v2_sparse_classes_36k_train_005645 | 15,226 | permissive | [
{
"docstring": "Parameters ---------- CoordinateFrame : str DeltaArp : None|XYZType|numpy.ndarray|list|tuple DeltaVarp : None|XYZType|numpy.ndarray|list|tuple DeltaRange : None|float kwargs Other keyword arguments",
"name": "__init__",
"signature": "def __init__(self, CoordinateFrame=None, DeltaArp=None... | 2 | null | Implement the Python class `ProjectionPerturbationType` described below.
Class description:
Basic information required for SICD/SIDD projection model perturbation.
Method signatures and docstrings:
- def __init__(self, CoordinateFrame=None, DeltaArp=None, DeltaVarp=None, DeltaRange=None, **kwargs): Parameters -------... | Implement the Python class `ProjectionPerturbationType` described below.
Class description:
Basic information required for SICD/SIDD projection model perturbation.
Method signatures and docstrings:
- def __init__(self, CoordinateFrame=None, DeltaArp=None, DeltaVarp=None, DeltaRange=None, **kwargs): Parameters -------... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class ProjectionPerturbationType:
"""Basic information required for SICD/SIDD projection model perturbation."""
def __init__(self, CoordinateFrame=None, DeltaArp=None, DeltaVarp=None, DeltaRange=None, **kwargs):
"""Parameters ---------- CoordinateFrame : str DeltaArp : None|XYZType|numpy.n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectionPerturbationType:
"""Basic information required for SICD/SIDD projection model perturbation."""
def __init__(self, CoordinateFrame=None, DeltaArp=None, DeltaVarp=None, DeltaRange=None, **kwargs):
"""Parameters ---------- CoordinateFrame : str DeltaArp : None|XYZType|numpy.ndarray|list|t... | the_stack_v2_python_sparse | sarpy/annotation/afrl_rde_elements/blocks.py | ngageoint/sarpy | train | 192 |
7459bf368f52e8b797d29f33a7371d6430d4c245 | [
"if x1 is None:\n return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self.input_ndim])\ndiffs = x0 - x1\nif scale_factors is not None:\n diffs *= scale_factors\nreturn jnp.sum(diffs ** 2, axis=tuple(range(-self.input_ndim, 0)))",
"if x1 is None:\n return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self... | <|body_start_0|>
if x1 is None:
return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self.input_ndim])
diffs = x0 - x1
if scale_factors is not None:
diffs *= scale_factors
return jnp.sum(diffs ** 2, axis=tuple(range(-self.input_ndim, 0)))
<|end_body_0|>
<|body_sta... | JaxIsotropicMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs... | stack_v2_sparse_classes_36k_train_005646 | 5,768 | permissive | [
{
"docstring": "Implementation of the squared (modified) Euclidean distance, which supports scalar inputs, an optional second argument, and different scale factors along all input dimensions.",
"name": "_squared_euclidean_distances_jax",
"signature": "def _squared_euclidean_distances_jax(self: JaxCovari... | 2 | stack_v2_sparse_classes_30k_train_009334 | Implement the Python class `JaxIsotropicMixin` described below.
Class description:
Implement the JaxIsotropicMixin class.
Method signatures and docstrings:
- def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None)... | Implement the Python class `JaxIsotropicMixin` described below.
Class description:
Implement the JaxIsotropicMixin class.
Method signatures and docstrings:
- def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None)... | 5036ae949f0d435395b496bbf88ebc5157b67ba9 | <|skeleton|>
class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs, an optional ... | the_stack_v2_python_sparse | src/linpde_gp/randprocs/covfuncs/_jax.py | marvinpfoertner/linpde-gp | train | 15 | |
ba762351e78afc6fa40fbc5fdf9079f1bc6cea97 | [
"dic = {}\nfor number in numbers:\n dic[number] = dic.get(number, 0) + 1\nfor number, frequency in dic.items():\n if frequency > len(numbers) // 2:\n return number\nreturn 0",
"count = 1\nnumber = numbers[0]\nfor i in numbers[1:]:\n if number == i:\n count += 1\n else:\n count -= ... | <|body_start_0|>
dic = {}
for number in numbers:
dic[number] = dic.get(number, 0) + 1
for number, frequency in dic.items():
if frequency > len(numbers) // 2:
return number
return 0
<|end_body_0|>
<|body_start_1|>
count = 1
number =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
<|body_0|>
def MoreThanHalfNum_Solution_best(self, numbers):
"""time O(n) space O(1) :param numbers: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_005647 | 1,638 | no_license | [
{
"docstring": "time O(n) space O(n) :param numbers: :return:",
"name": "MoreThanHalfNum_Solution",
"signature": "def MoreThanHalfNum_Solution(self, numbers)"
},
{
"docstring": "time O(n) space O(1) :param numbers: :return:",
"name": "MoreThanHalfNum_Solution_best",
"signature": "def Mor... | 2 | stack_v2_sparse_classes_30k_train_008320 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MoreThanHalfNum_Solution(self, numbers): time O(n) space O(n) :param numbers: :return:
- def MoreThanHalfNum_Solution_best(self, numbers): time O(n) space O(1) :param numbers... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MoreThanHalfNum_Solution(self, numbers): time O(n) space O(n) :param numbers: :return:
- def MoreThanHalfNum_Solution_best(self, numbers): time O(n) space O(1) :param numbers... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
<|body_0|>
def MoreThanHalfNum_Solution_best(self, numbers):
"""time O(n) space O(1) :param numbers: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def MoreThanHalfNum_Solution(self, numbers):
"""time O(n) space O(n) :param numbers: :return:"""
dic = {}
for number in numbers:
dic[number] = dic.get(number, 0) + 1
for number, frequency in dic.items():
if frequency > len(numbers) // 2:
... | the_stack_v2_python_sparse | LeetCode/Offer/数组中出现次数超过一半的数字.py | XyK0907/for_work | train | 0 | |
0fe37c756cd200db2ee834e9a214df84833e0b27 | [
"self.hass = hass\nself.config_entry = config_entry\nself.api = api\nself.servers: dict[str, dict] = {DEFAULT_SERVER: {}}\nsuper().__init__(self.hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=DEFAULT_SCAN_INTERVAL))",
"test_servers = self.api.get_servers()\ntest_servers_list = []\nfor servers in te... | <|body_start_0|>
self.hass = hass
self.config_entry = config_entry
self.api = api
self.servers: dict[str, dict] = {DEFAULT_SERVER: {}}
super().__init__(self.hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=DEFAULT_SCAN_INTERVAL))
<|end_body_0|>
<|body_start_1|>
... | Get the latest data from speedtest.net. | SpeedTestDataCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
<|body_0|>
def update_servers(self) -> None:
"""Update ... | stack_v2_sparse_classes_36k_train_005648 | 2,772 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None"
},
{
"docstring": "Update list of test servers.",
"name": "update_servers",
"signature": "def update_serve... | 4 | stack_v2_sparse_classes_30k_train_017082 | Implement the Python class `SpeedTestDataCoordinator` described below.
Class description:
Get the latest data from speedtest.net.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None: Initialize the data object.
- def update_servers(s... | Implement the Python class `SpeedTestDataCoordinator` described below.
Class description:
Get the latest data from speedtest.net.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None: Initialize the data object.
- def update_servers(s... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
<|body_0|>
def update_servers(self) -> None:
"""Update ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
self.hass = hass
self.config_entry = config_entry
self.api = api
... | the_stack_v2_python_sparse | homeassistant/components/speedtestdotnet/coordinator.py | home-assistant/core | train | 35,501 |
bea52c949d9410e4ab047e7b35047e5ecf21e4ec | [
"self.not_exists_au = 1\nself.not_exists_ac = 1\nself.not_big = 1\nself.rate = rate\nself.hours = hours\nself.cur = cur\nself.user = user\nself.response_ts = response_ts\nself.set_period()\nself.data_retrieval()\nif self.not_exists_au and self.not_exists_ac:\n self.align_timeseries()\n self.one_hot_encode()",... | <|body_start_0|>
self.not_exists_au = 1
self.not_exists_ac = 1
self.not_big = 1
self.rate = rate
self.hours = hours
self.cur = cur
self.user = user
self.response_ts = response_ts
self.set_period()
self.data_retrieval()
if self.not_e... | Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses | OneHotTimeSeries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of... | stack_v2_sparse_classes_36k_train_005649 | 6,866 | no_license | [
{
"docstring": ":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of uXX, XX E[00,59]. Database tables assosiacted with each user use it in their name as well plus an acronym depicting the details. E.g. u00sleep table contains sleep information for user u00. :response_ts: Unix times... | 5 | stack_v2_sparse_classes_30k_train_020442 | Implement the Python class `OneHotTimeSeries` described below.
Class description:
Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses
Method signatures and docstrings:
- def __init__(self, cur, user, response_ts, rate, hours): :cur: Cursor pointing to... | Implement the Python class `OneHotTimeSeries` described below.
Class description:
Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses
Method signatures and docstrings:
- def __init__(self, cur, user, response_ts, rate, hours): :cur: Cursor pointing to... | 27ef638e50b7b102d12d193d57442a41001c3060 | <|skeleton|>
class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OneHotTimeSeries:
"""Creates one hot encoded version of merged activity/audio timeseries in a 12 hour period around sleep quality responses"""
def __init__(self, cur, user, response_ts, rate, hours):
""":cur: Cursor pointing to PostgreSQL database schema :user: User ID in the form of uXX, XX E[00... | the_stack_v2_python_sparse | sleep/deep learning/oh2channels.py | koolboy2016/StudentLife-DataMining-ModelTraining | train | 0 |
092357f52822903bf9ce9f2a2d674eda9cec2e2d | [
"use_numba = engine == 'numba' and numba.numba_available\nif isinstance(cost, str):\n cost = self.cost_map[cost][int(use_numba)]\nif isinstance(cost, type):\n cost = cost(**cost_params)\nself.cost = cost\nself.segmentation = segmentation_numba if use_numba else segmentation\nself._min_size = max(min_size, sel... | <|body_start_0|>
use_numba = engine == 'numba' and numba.numba_available
if isinstance(cost, str):
cost = self.cost_map[cost][int(use_numba)]
if isinstance(cost, type):
cost = cost(**cost_params)
self.cost = cost
self.segmentation = segmentation_numba if u... | PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # Make some data with a changepoint at t = 10 >>> data = np.concatenate([n... | Pelt | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pelt:
"""PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # Make some data with a changepoint at t =... | stack_v2_sparse_classes_36k_train_005650 | 9,095 | permissive | [
{
"docstring": "Parameters ---------- cost : cost class or cost class instance or str, optional If \"l1\", use :py:class:`CostL1`, \"l2\", use :py:class:`CostL2`. A cost class type or instance can be passed directly. min_size : int, optional Minimum length of segments between change points. Defaults to 2. jump ... | 2 | null | Implement the Python class `Pelt` described below.
Class description:
PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # M... | Implement the Python class `Pelt` described below.
Class description:
PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # M... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class Pelt:
"""PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # Make some data with a changepoint at t =... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pelt:
"""PELT changepoint detection Implementation of the PELT algorithm [Kill2012]_. It is compatible with the implementation from `ruptures <https://github.com/deepcharles/ruptures>`_. Examples -------- >>> det = Pelt(cost="l2", min_size=1, jump=1) >>> # Make some data with a changepoint at t = 10 >>> data ... | the_stack_v2_python_sparse | sdt/changepoint/pelt.py | schuetzgroup/sdt-python | train | 31 |
ed7e8cfeea7ca484788038b2beaa3ef45b5c3736 | [
"if not head:\n return head\np = head\nwhile p:\n tmp = Node(p.val, None, None)\n tmp.next = p.next\n p.next = tmp\n p = p.next.next\np = head\nq = head.next\nwhile p:\n if p.random:\n q.random = p.random.next\n p = p.next.next\n if q.next:\n q = q.next.next\nheader = head.next... | <|body_start_0|>
if not head:
return head
p = head
while p:
tmp = Node(p.val, None, None)
tmp.next = p.next
p.next = tmp
p = p.next.next
p = head
q = head.next
while p:
if p.random:
q.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copyRandomList_outerspace(self, head):
""":type head: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return head... | stack_v2_sparse_classes_36k_train_005651 | 2,608 | no_license | [
{
"docstring": ":type head: Node :rtype: Node",
"name": "copyRandomList",
"signature": "def copyRandomList(self, head)"
},
{
"docstring": ":type head: Node :rtype: Node",
"name": "copyRandomList_outerspace",
"signature": "def copyRandomList_outerspace(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008474 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copyRandomList_outerspace(self, head): :type head: Node :rtype: Node | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def copyRandomList(self, head): :type head: Node :rtype: Node
- def copyRandomList_outerspace(self, head): :type head: Node :rtype: Node
<|skeleton|>
class Solution:
def co... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
<|body_0|>
def copyRandomList_outerspace(self, head):
""":type head: Node :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def copyRandomList(self, head):
""":type head: Node :rtype: Node"""
if not head:
return head
p = head
while p:
tmp = Node(p.val, None, None)
tmp.next = p.next
p.next = tmp
p = p.next.next
p = head
... | the_stack_v2_python_sparse | python/138.copy-list-with-random-pointer.py | tainenko/Leetcode2019 | train | 5 | |
ffa73563cefefdeadd23fa784a4e0436bddc0d1e | [
"ftp_status = {'status': -1, 'message': ''}\ncmd = 'service vsftpd status |grep running'\ncode, result_MSG = commands.getstatusoutput(cmd)\nif code == 0:\n ftp_status['status'] = 1\nelse:\n ftp_status['status'] = 0\n ftp_status['message'] = result_MSG\nreturn Response(ftp_status, status=status.HTTP_200_OK)... | <|body_start_0|>
ftp_status = {'status': -1, 'message': ''}
cmd = 'service vsftpd status |grep running'
code, result_MSG = commands.getstatusoutput(cmd)
if code == 0:
ftp_status['status'] = 1
else:
ftp_status['status'] = 0
ftp_status['message']... | VsftpdStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VsftpdStatus:
def get(self, request):
"""Query the state of the FTP."""
<|body_0|>
def put(self, request):
"""Modify the state of the FTP."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ftp_status = {'status': -1, 'message': ''}
cmd = 'serv... | stack_v2_sparse_classes_36k_train_005652 | 31,166 | no_license | [
{
"docstring": "Query the state of the FTP.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Modify the state of the FTP.",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | null | Implement the Python class `VsftpdStatus` described below.
Class description:
Implement the VsftpdStatus class.
Method signatures and docstrings:
- def get(self, request): Query the state of the FTP.
- def put(self, request): Modify the state of the FTP. | Implement the Python class `VsftpdStatus` described below.
Class description:
Implement the VsftpdStatus class.
Method signatures and docstrings:
- def get(self, request): Query the state of the FTP.
- def put(self, request): Modify the state of the FTP.
<|skeleton|>
class VsftpdStatus:
def get(self, request):
... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class VsftpdStatus:
def get(self, request):
"""Query the state of the FTP."""
<|body_0|>
def put(self, request):
"""Modify the state of the FTP."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VsftpdStatus:
def get(self, request):
"""Query the state of the FTP."""
ftp_status = {'status': -1, 'message': ''}
cmd = 'service vsftpd status |grep running'
code, result_MSG = commands.getstatusoutput(cmd)
if code == 0:
ftp_status['status'] = 1
els... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/ftp/views.py | sdtimothy8/Coding | train | 0 | |
c765f091cebabdf5b862ec6965fbc1eb5df97317 | [
"def match(word1, word2):\n map1, map2 = ({}, {})\n for c1, c2 in zip(word1, word2):\n if c1 not in map1:\n map1[c1] = c2\n if c2 not in map2:\n map2[c2] = c1\n if map1[c1] != c2 or map2[c2] != c1:\n return False\n return True\nreturn [word for word in ... | <|body_start_0|>
def match(word1, word2):
map1, map2 = ({}, {})
for c1, c2 in zip(word1, word2):
if c1 not in map1:
map1[c1] = c2
if c2 not in map2:
map2[c2] = c1
if map1[c1] != c2 or map2[c2] != c1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAndReplacePattern_1(self, words, pattern):
""":type words: List[str] :type pattern: str :rtype: List[str]"""
<|body_0|>
def findAndReplacePattern_2(self, words, pattern):
""":type words: List[str] :type pattern: str :rtype: List[str]"""
<|bo... | stack_v2_sparse_classes_36k_train_005653 | 2,542 | no_license | [
{
"docstring": ":type words: List[str] :type pattern: str :rtype: List[str]",
"name": "findAndReplacePattern_1",
"signature": "def findAndReplacePattern_1(self, words, pattern)"
},
{
"docstring": ":type words: List[str] :type pattern: str :rtype: List[str]",
"name": "findAndReplacePattern_2"... | 2 | stack_v2_sparse_classes_30k_train_006170 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAndReplacePattern_1(self, words, pattern): :type words: List[str] :type pattern: str :rtype: List[str]
- def findAndReplacePattern_2(self, words, pattern): :type words: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAndReplacePattern_1(self, words, pattern): :type words: List[str] :type pattern: str :rtype: List[str]
- def findAndReplacePattern_2(self, words, pattern): :type words: L... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def findAndReplacePattern_1(self, words, pattern):
""":type words: List[str] :type pattern: str :rtype: List[str]"""
<|body_0|>
def findAndReplacePattern_2(self, words, pattern):
""":type words: List[str] :type pattern: str :rtype: List[str]"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findAndReplacePattern_1(self, words, pattern):
""":type words: List[str] :type pattern: str :rtype: List[str]"""
def match(word1, word2):
map1, map2 = ({}, {})
for c1, c2 in zip(word1, word2):
if c1 not in map1:
map1[c1]... | the_stack_v2_python_sparse | code/890_find-and-replace-pattern.py | linhdvu14/leetcode-solutions | train | 2 | |
4ca2d075b0a0a816c40101b951f19893279d8559 | [
"seen = dict()\nfor idx, n in enumerate(nums):\n want = target - n\n if want in seen:\n return [idx, seen[want]]\n seen[n] = idx\nreturn [-1, -1]",
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]"
] | <|body_start_0|>
seen = dict()
for idx, n in enumerate(nums):
want = target - n
if want in seen:
return [idx, seen[want]]
seen[n] = idx
return [-1, -1]
<|end_body_0|>
<|body_start_1|>
for i in range(len(nums)):
for j in ran... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def twoSumBruteForce(self, nums: List[int], target: int) -> List[int]:
"""Brute force... | stack_v2_sparse_classes_36k_train_005654 | 942 | permissive | [
{
"docstring": "Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)",
"name": "twoSum",
"signature": "def twoSum(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Brute force approach Time complexity: O(n^2) Space complexity: O(1)",
... | 2 | stack_v2_sparse_classes_30k_train_011698 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: List[int], target: int) -> List[int]: Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)
- def twoSumBruteForce(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: List[int], target: int) -> List[int]: Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)
- def twoSumBruteForce(... | 32b0878f63e5edd19a1fbe13bfa4c518a4261e23 | <|skeleton|>
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def twoSumBruteForce(self, nums: List[int], target: int) -> List[int]:
"""Brute force... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Cache numbers in a dictionary to get O(1) access Time complexity: O(n) Space complexity: O(n)"""
seen = dict()
for idx, n in enumerate(nums):
want = target - n
if want in seen:
... | the_stack_v2_python_sparse | leetcode/Arrays, Strings and Hashing/1. Two Sum.py | danielfsousa/algorithms-solutions | train | 2 | |
9a9b3b6e75c5379104796177250babb3ee1953a5 | [
"self._gsg_pos_g = np.matrix(np.reshape(gsg_pos_g, (3, 1)))\nself._length = tether_params['length'] + bridle_radius\nself._weight = tether_params['length'] * tether_params['linear_density'] * g\nself._section_drag_coeff = tether_params['section_drag_coeff']\nself._outer_diameter = tether_params['outer_diameter']\ns... | <|body_start_0|>
self._gsg_pos_g = np.matrix(np.reshape(gsg_pos_g, (3, 1)))
self._length = tether_params['length'] + bridle_radius
self._weight = tether_params['length'] * tether_params['linear_density'] * g
self._section_drag_coeff = tether_params['section_drag_coeff']
self._out... | Model of tether force using catenary tension and rigid-rod drag. | CatenaryTetherForceModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatenaryTetherForceModel:
"""Model of tether force using catenary tension and rigid-rod drag."""
def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density):
"""Create a catenary tether force model. Args: tether_params: TetherParams dictionary. gsg_pos_g: Position [m]... | stack_v2_sparse_classes_36k_train_005655 | 28,331 | permissive | [
{
"docstring": "Create a catenary tether force model. Args: tether_params: TetherParams dictionary. gsg_pos_g: Position [m] of the GSG in the g-frame. bridle_radius: Bridle radius [m] of the kite. g: Gravitational acceleration [m/s^2]. air_density: Air density [kg/m^3].",
"name": "__init__",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_013891 | Implement the Python class `CatenaryTetherForceModel` described below.
Class description:
Model of tether force using catenary tension and rigid-rod drag.
Method signatures and docstrings:
- def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density): Create a catenary tether force model. Args: tether... | Implement the Python class `CatenaryTetherForceModel` described below.
Class description:
Model of tether force using catenary tension and rigid-rod drag.
Method signatures and docstrings:
- def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density): Create a catenary tether force model. Args: tether... | 818ae8b7119b200a28af6b3669a3045f30e0dc64 | <|skeleton|>
class CatenaryTetherForceModel:
"""Model of tether force using catenary tension and rigid-rod drag."""
def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density):
"""Create a catenary tether force model. Args: tether_params: TetherParams dictionary. gsg_pos_g: Position [m]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CatenaryTetherForceModel:
"""Model of tether force using catenary tension and rigid-rod drag."""
def __init__(self, tether_params, gsg_pos_g, bridle_radius, g, air_density):
"""Create a catenary tether force model. Args: tether_params: TetherParams dictionary. gsg_pos_g: Position [m] of the GSG i... | the_stack_v2_python_sparse | analysis/control/dynamics.py | ghomsy/makani | train | 0 |
658b439bd1346777f28cc306759c405b540c7cd1 | [
"record = super().prepare(record)\nrecord.stack_info = None\nreturn record",
"return_value = self.filter(record)\nif return_value:\n self.emit(record)\nreturn return_value",
"super().close()\nif not self.listener:\n return\nself.listener.stop()\nself.listener = None"
] | <|body_start_0|>
record = super().prepare(record)
record.stack_info = None
return record
<|end_body_0|>
<|body_start_1|>
return_value = self.filter(record)
if return_value:
self.emit(record)
return return_value
<|end_body_1|>
<|body_start_2|>
super()... | Process the log in another thread. | HomeAssistantQueueHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeAssistantQueueHandler:
"""Process the log in another thread."""
def prepare(self, record: logging.LogRecord) -> logging.LogRecord:
"""Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/issue46755"""
<|body_0|>
def handle(self, rec... | stack_v2_sparse_classes_36k_train_005656 | 6,615 | permissive | [
{
"docstring": "Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/issue46755",
"name": "prepare",
"signature": "def prepare(self, record: logging.LogRecord) -> logging.LogRecord"
},
{
"docstring": "Conditionally emit the specified logging record. Depending o... | 3 | null | Implement the Python class `HomeAssistantQueueHandler` described below.
Class description:
Process the log in another thread.
Method signatures and docstrings:
- def prepare(self, record: logging.LogRecord) -> logging.LogRecord: Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/i... | Implement the Python class `HomeAssistantQueueHandler` described below.
Class description:
Process the log in another thread.
Method signatures and docstrings:
- def prepare(self, record: logging.LogRecord) -> logging.LogRecord: Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/i... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HomeAssistantQueueHandler:
"""Process the log in another thread."""
def prepare(self, record: logging.LogRecord) -> logging.LogRecord:
"""Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/issue46755"""
<|body_0|>
def handle(self, rec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomeAssistantQueueHandler:
"""Process the log in another thread."""
def prepare(self, record: logging.LogRecord) -> logging.LogRecord:
"""Prepare a record for queuing. This is added as a workaround for https://bugs.python.org/issue46755"""
record = super().prepare(record)
record.s... | the_stack_v2_python_sparse | homeassistant/util/logging.py | home-assistant/core | train | 35,501 |
c5e666990cb24f458fa8b4193f5a4f6364aa8592 | [
"self.parser = xml.parsers.expat.ParserCreate()\nself.parser.buffer_text = True\nself.parser.returns_unicode = False\nself.groups = []\nself.contacts = []\nself.annotations = []\nself.group_ids = []\nself.in_group = False\nself.in_contact = False\nself.in_annotation = False\nself.in_group_ids = False\nself.group_da... | <|body_start_0|>
self.parser = xml.parsers.expat.ParserCreate()
self.parser.buffer_text = True
self.parser.returns_unicode = False
self.groups = []
self.contacts = []
self.annotations = []
self.group_ids = []
self.in_group = False
self.in_contact =... | Parse dynamic xml | DynamicParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicParser:
"""Parse dynamic xml"""
def __init__(self, xml_raw):
"""init parser and setup handlers"""
<|body_0|>
def start_element(self, name, attrs):
"""Start xml element handler"""
<|body_1|>
def end_element(self, name):
"""End xml eleme... | stack_v2_sparse_classes_36k_train_005657 | 4,878 | no_license | [
{
"docstring": "init parser and setup handlers",
"name": "__init__",
"signature": "def __init__(self, xml_raw)"
},
{
"docstring": "Start xml element handler",
"name": "start_element",
"signature": "def start_element(self, name, attrs)"
},
{
"docstring": "End xml element handler",... | 4 | null | Implement the Python class `DynamicParser` described below.
Class description:
Parse dynamic xml
Method signatures and docstrings:
- def __init__(self, xml_raw): init parser and setup handlers
- def start_element(self, name, attrs): Start xml element handler
- def end_element(self, name): End xml element handler
- de... | Implement the Python class `DynamicParser` described below.
Class description:
Parse dynamic xml
Method signatures and docstrings:
- def __init__(self, xml_raw): init parser and setup handlers
- def start_element(self, name, attrs): Start xml element handler
- def end_element(self, name): End xml element handler
- de... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class DynamicParser:
"""Parse dynamic xml"""
def __init__(self, xml_raw):
"""init parser and setup handlers"""
<|body_0|>
def start_element(self, name, attrs):
"""Start xml element handler"""
<|body_1|>
def end_element(self, name):
"""End xml eleme... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicParser:
"""Parse dynamic xml"""
def __init__(self, xml_raw):
"""init parser and setup handlers"""
self.parser = xml.parsers.expat.ParserCreate()
self.parser.buffer_text = True
self.parser.returns_unicode = False
self.groups = []
self.contacts = []
... | the_stack_v2_python_sparse | emesene/rev1286-1505/right-branch-1505/emesenelib/XmlParser.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
cfb199ba9ac1faaf97bfc88acbdc190f88174f7f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsMalwareOverview()",
"from .os_version_count import OsVersionCount\nfrom .windows_malware_category_count import WindowsMalwareCategoryCount\nfrom .windows_malware_execution_state_count import WindowsMalwareExecutionStateCount\nfr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WindowsMalwareOverview()
<|end_body_0|>
<|body_start_1|>
from .os_version_count import OsVersionCount
from .windows_malware_category_count import WindowsMalwareCategoryCount
from... | Windows device malware overview. | WindowsMalwareOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsMalwareOverview:
"""Windows device malware overview."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use ... | stack_v2_sparse_classes_36k_train_005658 | 7,019 | 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: WindowsMalwareOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_008001 | Implement the Python class `WindowsMalwareOverview` described below.
Class description:
Windows device malware overview.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareOverview: Creates a new instance of the appropriate class based on dis... | Implement the Python class `WindowsMalwareOverview` described below.
Class description:
Windows device malware overview.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareOverview: Creates a new instance of the appropriate class based on dis... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsMalwareOverview:
"""Windows device malware overview."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsMalwareOverview:
"""Windows device malware overview."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsMalwareOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the d... | the_stack_v2_python_sparse | msgraph/generated/models/windows_malware_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 |
0d21f6d9d4ad53cfd9776e38469b832bc0736875 | [
"self.estimated_monthly_base_pay = estimated_monthly_base_pay\nself.estimated_monthly_overtime_pay = estimated_monthly_overtime_pay\nself.estimated_monthly_bonus_pay = estimated_monthly_bonus_pay\nself.estimated_monthly_commission_pay = estimated_monthly_commission_pay\nself.additional_properties = additional_prope... | <|body_start_0|>
self.estimated_monthly_base_pay = estimated_monthly_base_pay
self.estimated_monthly_overtime_pay = estimated_monthly_overtime_pay
self.estimated_monthly_bonus_pay = estimated_monthly_bonus_pay
self.estimated_monthly_commission_pay = estimated_monthly_commission_pay
... | Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overtime_pay (float): The estimated monthly overtime pay am... | PaystubMonthlyIncomeRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaystubMonthlyIncomeRecord:
"""Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overt... | stack_v2_sparse_classes_36k_train_005659 | 3,514 | permissive | [
{
"docstring": "Constructor for the PaystubMonthlyIncomeRecord class",
"name": "__init__",
"signature": "def __init__(self, estimated_monthly_base_pay=None, estimated_monthly_overtime_pay=None, estimated_monthly_bonus_pay=None, estimated_monthly_commission_pay=None, additional_properties={})"
},
{
... | 2 | null | Implement the Python class `PaystubMonthlyIncomeRecord` described below.
Class description:
Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculat... | Implement the Python class `PaystubMonthlyIncomeRecord` described below.
Class description:
Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculat... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class PaystubMonthlyIncomeRecord:
"""Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaystubMonthlyIncomeRecord:
"""Implementation of the 'Paystub Monthly Income Record' model. TODO: type model description here. Attributes: estimated_monthly_base_pay (float): The estimated monthly base pay amount for the employment from the paystub, calculated by Finicity. estimated_monthly_overtime_pay (floa... | the_stack_v2_python_sparse | finicityapi/models/paystub_monthly_income_record.py | monarchmoney/finicity-python | train | 0 |
f890657798f8bd65bd49c3c26d5124905ada60fa | [
"super(GrazA, self).__init__(**kwargs)\nself.base_dir = base_dir\nself.data_id = identifier\nself.data_dir = base_dir\nself.trial_len = trail_len\nself.cue_interval = cue_interval\nself.trial_offset = trial_offset\nself.expected_freq = expected_freq\nself.matT = os.path.join(self.data_dir, '{id}T.mat'.format(id=sel... | <|body_start_0|>
super(GrazA, self).__init__(**kwargs)
self.base_dir = base_dir
self.data_id = identifier
self.data_dir = base_dir
self.trial_len = trail_len
self.cue_interval = cue_interval
self.trial_offset = trial_offset
self.expected_freq = expected_fr... | Class to hold 4class motor imagery data from Graz. | GrazA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GrazA:
"""Class to hold 4class motor imagery data from Graz."""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expected depending on suppo... | stack_v2_sparse_classes_36k_train_005660 | 6,110 | no_license | [
{
"docstring": "Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expected depending on supporting literature.",
"name": "__init__",
"signature": "def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_019571 | Implement the Python class `GrazA` described below.
Class description:
Class to hold 4class motor imagery data from Graz.
Method signatures and docstrings:
- def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs): Init Graz data specifics. trial_len, cue_interval, cue... | Implement the Python class `GrazA` described below.
Class description:
Class to hold 4class motor imagery data from Graz.
Method signatures and docstrings:
- def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs): Init Graz data specifics. trial_len, cue_interval, cue... | f3db33eb2e0f291f789aa8e4d947633623163781 | <|skeleton|>
class GrazA:
"""Class to hold 4class motor imagery data from Graz."""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expected depending on suppo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GrazA:
"""Class to hold 4class motor imagery data from Graz."""
def __init__(self, base_dir, identifier, trail_len, cue_interval, trial_offset, expected_freq, **kwargs):
"""Init Graz data specifics. trial_len, cue_interval, cue_offset and expected_freq are expected depending on supporting literat... | the_stack_v2_python_sparse | utils/graz.py | eeshakumar/bci-incremental-learning | train | 0 |
05ffbeee2eb933b53053c2f2a11218a3725a61d4 | [
"original_mesh_shape = (10, 11)\nif columns < 1 or columns > original_mesh_shape[0]:\n columns = original_mesh_shape[0]\nfinals = {(0, 1): 5, (1, 2): 80, (2, 3): 120, (3, 4): 140, (4, 4): 145, (5, 4): 150, (6, 7): 163, (7, 7): 166, (8, 9): 173, (9, 10): 175}\nfinals = dict(filter(lambda x: x[0][0] < columns, fin... | <|body_start_0|>
original_mesh_shape = (10, 11)
if columns < 1 or columns > original_mesh_shape[0]:
columns = original_mesh_shape[0]
finals = {(0, 1): 5, (1, 2): 80, (2, 3): 120, (3, 4): 140, (4, 4): 145, (5, 4): 150, (6, 7): 163, (7, 7): 166, (8, 9): 173, (9, 10): 175}
final... | PressurizedBountifulSeaTreasure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: S... | stack_v2_sparse_classes_36k_train_005661 | 4,453 | no_license | [
{
"docstring": ":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: Seed used for np.random.RandomState method.",
"name": "__init__",
"signature": "def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, colum... | 3 | stack_v2_sparse_classes_30k_train_018668 | Implement the Python class `PressurizedBountifulSeaTreasure` described below.
Class description:
Implement the PressurizedBountifulSeaTreasure class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=No... | Implement the Python class `PressurizedBountifulSeaTreasure` described below.
Class description:
Implement the PressurizedBountifulSeaTreasure class.
Method signatures and docstrings:
- def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=No... | b51c64c867e15356c9f978839fd0040182324edd | <|skeleton|>
class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PressurizedBountifulSeaTreasure:
def __init__(self, initial_state: tuple=(0, 0), default_reward: tuple=(0,), seed: int=0, columns: int=0, action_space: gym.spaces=None):
""":param initial_state: Initial state where start the agent. :param default_reward: (treasure_value, ) :param seed: Seed used for n... | the_stack_v2_python_sparse | environments/pressurized_bountiful_sea_treasure.py | Pozas91/tiadas | train | 1 | |
7b65d997d9fe99c13df1d676bb0b740915a3f024 | [
"at_group_type = 'regular'\nat_group_name = 'G1'\nat_credentials_name = f\"linux-cred-{time.strftime('%a-%d-%b-%Y-%H:%M:%S:%MS')}\"\ncontext['credentials_name'] = at_credentials_name\nat_template_name = 'Revizor_linux_Job_Template_with_Extra_Var'\nprovision.set_at_server_id(context)\nprovision.create_copy_at_invent... | <|body_start_0|>
at_group_type = 'regular'
at_group_name = 'G1'
at_credentials_name = f"linux-cred-{time.strftime('%a-%d-%b-%Y-%H:%M:%S:%MS')}"
context['credentials_name'] = at_credentials_name
at_template_name = 'Revizor_linux_Job_Template_with_Extra_Var'
provision.set_a... | Linux server provision with Ansible Tower | TestAnsibleTowerProvisionLinux | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnsibleTowerProvisionLinux:
"""Linux server provision with Ansible Tower"""
def setup_ansible_tower_configuration(self, context: dict):
"""Setup Ansible Tower bootstrap configurations"""
<|body_0|>
def test_bootstrapping_role_with_at(self, context: dict, cloud: Cloud... | stack_v2_sparse_classes_36k_train_005662 | 12,446 | no_license | [
{
"docstring": "Setup Ansible Tower bootstrap configurations",
"name": "setup_ansible_tower_configuration",
"signature": "def setup_ansible_tower_configuration(self, context: dict)"
},
{
"docstring": "Bootstrapping role with Ansible Tower",
"name": "test_bootstrapping_role_with_at",
"sig... | 5 | stack_v2_sparse_classes_30k_train_014720 | Implement the Python class `TestAnsibleTowerProvisionLinux` described below.
Class description:
Linux server provision with Ansible Tower
Method signatures and docstrings:
- def setup_ansible_tower_configuration(self, context: dict): Setup Ansible Tower bootstrap configurations
- def test_bootstrapping_role_with_at(s... | Implement the Python class `TestAnsibleTowerProvisionLinux` described below.
Class description:
Linux server provision with Ansible Tower
Method signatures and docstrings:
- def setup_ansible_tower_configuration(self, context: dict): Setup Ansible Tower bootstrap configurations
- def test_bootstrapping_role_with_at(s... | 87b212e5b35a328b0a3c4d502847989a4d4fd897 | <|skeleton|>
class TestAnsibleTowerProvisionLinux:
"""Linux server provision with Ansible Tower"""
def setup_ansible_tower_configuration(self, context: dict):
"""Setup Ansible Tower bootstrap configurations"""
<|body_0|>
def test_bootstrapping_role_with_at(self, context: dict, cloud: Cloud... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnsibleTowerProvisionLinux:
"""Linux server provision with Ansible Tower"""
def setup_ansible_tower_configuration(self, context: dict):
"""Setup Ansible Tower bootstrap configurations"""
at_group_type = 'regular'
at_group_name = 'G1'
at_credentials_name = f"linux-cred-... | the_stack_v2_python_sparse | scalarizr/lifecycle/test_provision_linux.py | Scalr/revizor-tests | train | 0 |
b4aad0f725ff3a7ee55d2d42d8a7cecb8ddd7fa8 | [
"try:\n db.session.add(self)\n db.session.commit()\nexcept Exception as save_exception:\n current_app.logger.error('DB save exception: ' + str(save_exception))\n raise DatabaseException(save_exception)",
"ltsa_description = None\nif ltsa_id:\n try:\n ltsa_description = cls.query.get(ltsa_id)... | <|body_start_0|>
try:
db.session.add(self)
db.session.commit()
except Exception as save_exception:
current_app.logger.error('DB save exception: ' + str(save_exception))
raise DatabaseException(save_exception)
<|end_body_0|>
<|body_start_1|>
ltsa_d... | This class manages all of the LTSA legal description information. | LtsaDescription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LtsaDescription:
"""This class manages all of the LTSA legal description information."""
def save(self):
"""Save the object to the database immediately."""
<|body_0|>
def find_by_id(cls, ltsa_id: int):
"""Return a ltsa description object by primary key (ID)."""
... | stack_v2_sparse_classes_36k_train_005663 | 3,919 | permissive | [
{
"docstring": "Save the object to the database immediately.",
"name": "save",
"signature": "def save(self)"
},
{
"docstring": "Return a ltsa description object by primary key (ID).",
"name": "find_by_id",
"signature": "def find_by_id(cls, ltsa_id: int)"
},
{
"docstring": "Return... | 5 | null | Implement the Python class `LtsaDescription` described below.
Class description:
This class manages all of the LTSA legal description information.
Method signatures and docstrings:
- def save(self): Save the object to the database immediately.
- def find_by_id(cls, ltsa_id: int): Return a ltsa description object by p... | Implement the Python class `LtsaDescription` described below.
Class description:
This class manages all of the LTSA legal description information.
Method signatures and docstrings:
- def save(self): Save the object to the database immediately.
- def find_by_id(cls, ltsa_id: int): Return a ltsa description object by p... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class LtsaDescription:
"""This class manages all of the LTSA legal description information."""
def save(self):
"""Save the object to the database immediately."""
<|body_0|>
def find_by_id(cls, ltsa_id: int):
"""Return a ltsa description object by primary key (ID)."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LtsaDescription:
"""This class manages all of the LTSA legal description information."""
def save(self):
"""Save the object to the database immediately."""
try:
db.session.add(self)
db.session.commit()
except Exception as save_exception:
current... | the_stack_v2_python_sparse | mhr_api/src/mhr_api/models/ltsa_description.py | bcgov/ppr | train | 4 |
43f9d5e7b889c6640bdff1cefa90ee85175817ee | [
"prediction = hypothesis.prediction\nmeasurement = hypothesis.measurement\nmeasurement_model = hypothesis.measurement.measurement_model\nmeasurement_model = self._check_measurement_model(measurement_model)\nif hypothesis.measurement_prediction is None:\n hypothesis.measurement_prediction = self.predict_measureme... | <|body_start_0|>
prediction = hypothesis.prediction
measurement = hypothesis.measurement
measurement_model = hypothesis.measurement.measurement_model
measurement_model = self._check_measurement_model(measurement_model)
if hypothesis.measurement_prediction is None:
hyp... | Hidden Markov model updater | HMMUpdater | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\... | stack_v2_sparse_classes_36k_train_005664 | 5,093 | permissive | [
{
"docstring": "The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\\\alpha_t^i = E^{ki}(F\\\\alpha_{t-1})^i Measurements are assumed to be discrete categories from a finite set of measuremen... | 3 | null | Implement the Python class `HMMUpdater` described below.
Class description:
Hidden Markov model updater
Method signatures and docstrings:
- def update(self, hypothesis, **kwargs): The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculat... | Implement the Python class `HMMUpdater` described below.
Class description:
Hidden Markov model updater
Method signatures and docstrings:
- def update(self, hypothesis, **kwargs): The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculat... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\alpha_{t-1})^... | the_stack_v2_python_sparse | stonesoup/updater/categorical.py | dstl/Stone-Soup | train | 315 |
a493f068c9af5ad63e06b7eabe026c26ea7ec218 | [
"cap_url = self.webhook['links'].capability\nexecute_wb_resp = self.autoscale_client.execute_webhook(cap_url)\nself.assertEquals(execute_wb_resp.status_code, 202, msg='Execute webhook failed with {0} for group {1}'.format(execute_wb_resp.status_code, self.group.id))\nself.validate_headers(execute_wb_resp.headers)",... | <|body_start_0|>
cap_url = self.webhook['links'].capability
execute_wb_resp = self.autoscale_client.execute_webhook(cap_url)
self.assertEquals(execute_wb_resp.status_code, 202, msg='Execute webhook failed with {0} for group {1}'.format(execute_wb_resp.status_code, self.group.id))
self.va... | Create a webhook, get and validate | ExecuteWebhook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecuteWebhook:
"""Create a webhook, get and validate"""
def test_execute_webhook(self):
"""Execute a webhook and verify response code 202 and headers."""
<|body_0|>
def test_execute_webhook_after_update(self):
"""Update a webhook and verify execution of the same... | stack_v2_sparse_classes_36k_train_005665 | 2,641 | permissive | [
{
"docstring": "Execute a webhook and verify response code 202 and headers.",
"name": "test_execute_webhook",
"signature": "def test_execute_webhook(self)"
},
{
"docstring": "Update a webhook and verify execution of the same.",
"name": "test_execute_webhook_after_update",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_001045 | Implement the Python class `ExecuteWebhook` described below.
Class description:
Create a webhook, get and validate
Method signatures and docstrings:
- def test_execute_webhook(self): Execute a webhook and verify response code 202 and headers.
- def test_execute_webhook_after_update(self): Update a webhook and verify ... | Implement the Python class `ExecuteWebhook` described below.
Class description:
Create a webhook, get and validate
Method signatures and docstrings:
- def test_execute_webhook(self): Execute a webhook and verify response code 202 and headers.
- def test_execute_webhook_after_update(self): Update a webhook and verify ... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class ExecuteWebhook:
"""Create a webhook, get and validate"""
def test_execute_webhook(self):
"""Execute a webhook and verify response code 202 and headers."""
<|body_0|>
def test_execute_webhook_after_update(self):
"""Update a webhook and verify execution of the same... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecuteWebhook:
"""Create a webhook, get and validate"""
def test_execute_webhook(self):
"""Execute a webhook and verify response code 202 and headers."""
cap_url = self.webhook['links'].capability
execute_wb_resp = self.autoscale_client.execute_webhook(cap_url)
self.asser... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/functional/webhooks/test_execute_webhook.py | rackerlabs/otter | train | 20 |
18b9f3bb3784e1cb5953e0da9a69174ed1449819 | [
"_inv_index: InvIndex\n_tokenizer: Tokenizer\n_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)\nlogging.info('Loaded inverted index')\nself._inv_index = _inv_index\nself._tokenizer = _tokenizer",
"name: str\nversion: str\ninv_index: InvIndex\ntokenizer: Tokenizer\nif not path.exists(index_path):... | <|body_start_0|>
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Loaded inverted index')
self._inv_index = _inv_index
self._tokenizer = _tokenizer
<|end_body_0|>
<|body_start_1|>
name: st... | Engine class. | Engine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_36k_train_005666 | 2,559 | permissive | [
{
"docstring": "Initialize the search engine.",
"name": "__init__",
"signature": "def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None"
},
{
"docstring": "Load inverted index.",
"name": "__load_inv_index",
"signature": "def __load_inv_index(self, index_path: str, dicdi... | 3 | stack_v2_sparse_classes_30k_train_006154 | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | Implement the Python class `Engine` described below.
Class description:
Engine class.
Method signatures and docstrings:
- def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None: Initialize the search engine.
- def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Token... | c0a221a8038879107a5fe07d2b9452abf51815b1 | <|skeleton|>
class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
<|body_0|>
def __load_inv_index(self, index_path: str, dicdir: Optional[str]) -> Tuple[InvIndex, Tokenizer]:
"""Load inverted ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Engine:
"""Engine class."""
def __init__(self, index_path: str, dicdir: Optional[str]=None) -> None:
"""Initialize the search engine."""
_inv_index: InvIndex
_tokenizer: Tokenizer
_inv_index, _tokenizer = self.__load_inv_index(index_path, dicdir)
logging.info('Load... | the_stack_v2_python_sparse | dzo/engine.py | moriaki3193/dzo | train | 8 |
03f30e93e2e0a561b080fba7afe1e2f6990d5c3a | [
"h.checkAccess('', '', 'read')\nmodel = IcdbModel()\ndata = model.active_index(instrument, experiment)\nfor d in data:\n d['url'] = h.url_for(action='index', instrument=d['instrument'], experiment=d['experiment'])\nif instrument is None and experiment is None:\n return data\nelif data:\n return data[0]\nel... | <|body_start_0|>
h.checkAccess('', '', 'read')
model = IcdbModel()
data = model.active_index(instrument, experiment)
for d in data:
d['url'] = h.url_for(action='index', instrument=d['instrument'], experiment=d['experiment'])
if instrument is None and experiment is Non... | ActiveController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveController:
def index(self, instrument=None, experiment=None):
"""Show requests"""
<|body_0|>
def add(self, instrument, experiment):
"""Create new active experiment"""
<|body_1|>
def delete(self, instrument, experiment):
"""Create new reque... | stack_v2_sparse_classes_36k_train_005667 | 2,800 | no_license | [
{
"docstring": "Show requests",
"name": "index",
"signature": "def index(self, instrument=None, experiment=None)"
},
{
"docstring": "Create new active experiment",
"name": "add",
"signature": "def add(self, instrument, experiment)"
},
{
"docstring": "Create new request",
"nam... | 3 | null | Implement the Python class `ActiveController` described below.
Class description:
Implement the ActiveController class.
Method signatures and docstrings:
- def index(self, instrument=None, experiment=None): Show requests
- def add(self, instrument, experiment): Create new active experiment
- def delete(self, instrume... | Implement the Python class `ActiveController` described below.
Class description:
Implement the ActiveController class.
Method signatures and docstrings:
- def index(self, instrument=None, experiment=None): Show requests
- def add(self, instrument, experiment): Create new active experiment
- def delete(self, instrume... | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | <|skeleton|>
class ActiveController:
def index(self, instrument=None, experiment=None):
"""Show requests"""
<|body_0|>
def add(self, instrument, experiment):
"""Create new active experiment"""
<|body_1|>
def delete(self, instrument, experiment):
"""Create new reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveController:
def index(self, instrument=None, experiment=None):
"""Show requests"""
h.checkAccess('', '', 'read')
model = IcdbModel()
data = model.active_index(instrument, experiment)
for d in data:
d['url'] = h.url_for(action='index', instrument=d['ins... | the_stack_v2_python_sparse | InterfaceCtlr/tags/V01-00-17/web/icws/controllers/active.py | connectthefuture/psdmrepo | train | 0 | |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super(Swish, self).__init__()\nself.swish = swish\nself.eswish = eswish\nself.flatten = flatten\nself.beta = None\nself.param = None\nif eswish is not False:\n self.beta = beta\nif swish is not False:\n self.param = nn.Parameter(torch.randn(1))\n self.param.requires_grad = True\nif flatten is not False:\n... | <|body_start_0|>
super(Swish, self).__init__()
self.swish = swish
self.eswish = eswish
self.flatten = flatten
self.beta = None
self.param = None
if eswish is not False:
self.beta = beta
if swish is not False:
self.param = nn.Paramet... | Swish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Swish:
def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Swish, self).... | stack_v2_sparse_classes_36k_train_005668 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011949 | Implement the Python class `Swish` described below.
Class description:
Implement the Swish class.
Method signatures and docstrings:
- def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `Swish` described below.
Class description:
Implement the Swish class.
Method signatures and docstrings:
- def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class Swish:
... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Swish:
def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Swish:
def __init__(self, eswish=False, swish=False, beta=1.735, flatten=False, pfts=False):
"""Init method."""
super(Swish, self).__init__()
self.swish = swish
self.eswish = eswish
self.flatten = flatten
self.beta = None
self.param = None
if esw... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
2cb7875bec75f1dd54b2829700a5befe6aa410d2 | [
"sentinel_sectPr = self.get_or_add_sectPr()\nself.add_p().set_sectPr(sentinel_sectPr.clone())\nfor hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'):\n sentinel_sectPr.remove(hdrftr_ref)\nreturn sentinel_sectPr",
"if self.sectPr is not None:\n content_elms = self[:-1]\nelse:\n co... | <|body_start_0|>
sentinel_sectPr = self.get_or_add_sectPr()
self.add_p().set_sectPr(sentinel_sectPr.clone())
for hdrftr_ref in sentinel_sectPr.xpath('w:headerReference|w:footerReference'):
sentinel_sectPr.remove(hdrftr_ref)
return sentinel_sectPr
<|end_body_0|>
<|body_start_... | ``<w:body>``, the container element for the main document story in ``document.xml``. | CT_Body | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa... | stack_v2_sparse_classes_36k_train_005669 | 2,543 | permissive | [
{
"docstring": "Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of the previous one, except that all header and footer references are removed (and are therefore now \"inherited\" from the prior secti... | 2 | stack_v2_sparse_classes_30k_train_018921 | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes... | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes... | 2bfcf6b9779bf1abd41e1bc42c27007127ddbefb | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document. The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an exact clone of t... | the_stack_v2_python_sparse | anuvaad-etl/anuvaad-extractor/file_translator/etl-file-translator/docx/oxml/document.py | project-anuvaad/anuvaad | train | 41 |
efc706b568e3f594c74195af12d3261a966f8929 | [
"self.img_dir = f'{semantic_version_dataroot}/images'\nself.ade20k_instance_dataroot = instance_version_dataroot\nself.id_to_classname_map = names_utils.get_dataloader_id_to_classname_map(dataset_name='ade20k-151')\nself.classname_to_id_map = names_utils.get_classname_to_dataloaderid_map(dataset_name='ade20k-151')\... | <|body_start_0|>
self.img_dir = f'{semantic_version_dataroot}/images'
self.ade20k_instance_dataroot = instance_version_dataroot
self.id_to_classname_map = names_utils.get_dataloader_id_to_classname_map(dataset_name='ade20k-151')
self.classname_to_id_map = names_utils.get_classname_to_dat... | Simple API to interact with instance masks of ADE20K dataset. | Ade20kMaskDataset | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ade20kMaskDataset:
"""Simple API to interact with instance masks of ADE20K dataset."""
def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str):
"""Args: semantic_version_dataroot: from ADEChallengeData2016 instance_verson_dataroot: from ADE20K_2016_07_26"""... | stack_v2_sparse_classes_36k_train_005670 | 10,767 | permissive | [
{
"docstring": "Args: semantic_version_dataroot: from ADEChallengeData2016 instance_verson_dataroot: from ADE20K_2016_07_26",
"name": "__init__",
"signature": "def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str)"
},
{
"docstring": "Get for all splits, at once. Args... | 4 | stack_v2_sparse_classes_30k_train_016526 | Implement the Python class `Ade20kMaskDataset` described below.
Class description:
Simple API to interact with instance masks of ADE20K dataset.
Method signatures and docstrings:
- def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str): Args: semantic_version_dataroot: from ADEChallengeDat... | Implement the Python class `Ade20kMaskDataset` described below.
Class description:
Simple API to interact with instance masks of ADE20K dataset.
Method signatures and docstrings:
- def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str): Args: semantic_version_dataroot: from ADEChallengeDat... | 2fcd605578bf12982494ee3235f8872a933645cd | <|skeleton|>
class Ade20kMaskDataset:
"""Simple API to interact with instance masks of ADE20K dataset."""
def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str):
"""Args: semantic_version_dataroot: from ADEChallengeData2016 instance_verson_dataroot: from ADE20K_2016_07_26"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ade20kMaskDataset:
"""Simple API to interact with instance masks of ADE20K dataset."""
def __init__(self, semantic_version_dataroot: str, instance_version_dataroot: str):
"""Args: semantic_version_dataroot: from ADEChallengeData2016 instance_verson_dataroot: from ADE20K_2016_07_26"""
self... | the_stack_v2_python_sparse | mseg_semantic/mseg-api/mseg/dataset_apis/Ade20kMaskLevelDataset.py | daniel-bogdoll/unknown_objects_roads | train | 16 |
6290846563d58bc66022e2f87e51d057bc0d14b2 | [
"server_proc = mp.Process(target=Sample.server, args=())\nclient_procs = [mp.Process(target=Sample.client, args=(str(i),)) for i in range(10, 61, 10)]\nclient_all_proc = mp.Process(target=Sample.client_all, args=())\nfor p in client_procs:\n p.start()\nelse:\n client_all_proc.start()\n server_proc.start()\... | <|body_start_0|>
server_proc = mp.Process(target=Sample.server, args=())
client_procs = [mp.Process(target=Sample.client, args=(str(i),)) for i in range(10, 61, 10)]
client_all_proc = mp.Process(target=Sample.client_all, args=())
for p in client_procs:
p.start()
else:... | ZeroMQ の PUB-SUB パターンのサンプルです。 | Sample | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sample:
"""ZeroMQ の PUB-SUB パターンのサンプルです。"""
def exec(self):
"""サンプル処理を実行します。"""
<|body_0|>
def server():
"""PUB側の処理を行います。"""
<|body_1|>
def client(sub_filter):
"""SUB側の処理を行います。(フィルター付き)"""
<|body_2|>
def client_all():
"""... | stack_v2_sparse_classes_36k_train_005671 | 4,809 | permissive | [
{
"docstring": "サンプル処理を実行します。",
"name": "exec",
"signature": "def exec(self)"
},
{
"docstring": "PUB側の処理を行います。",
"name": "server",
"signature": "def server()"
},
{
"docstring": "SUB側の処理を行います。(フィルター付き)",
"name": "client",
"signature": "def client(sub_filter)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_020040 | Implement the Python class `Sample` described below.
Class description:
ZeroMQ の PUB-SUB パターンのサンプルです。
Method signatures and docstrings:
- def exec(self): サンプル処理を実行します。
- def server(): PUB側の処理を行います。
- def client(sub_filter): SUB側の処理を行います。(フィルター付き)
- def client_all(): SUB側の処理を行います。(フィルター無し(全部取得)) | Implement the Python class `Sample` described below.
Class description:
ZeroMQ の PUB-SUB パターンのサンプルです。
Method signatures and docstrings:
- def exec(self): サンプル処理を実行します。
- def server(): PUB側の処理を行います。
- def client(sub_filter): SUB側の処理を行います。(フィルター付き)
- def client_all(): SUB側の処理を行います。(フィルター無し(全部取得))
<|skeleton|>
class Sa... | 9bfb649d3f5b249b67991a30865201be794e29a9 | <|skeleton|>
class Sample:
"""ZeroMQ の PUB-SUB パターンのサンプルです。"""
def exec(self):
"""サンプル処理を実行します。"""
<|body_0|>
def server():
"""PUB側の処理を行います。"""
<|body_1|>
def client(sub_filter):
"""SUB側の処理を行います。(フィルター付き)"""
<|body_2|>
def client_all():
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sample:
"""ZeroMQ の PUB-SUB パターンのサンプルです。"""
def exec(self):
"""サンプル処理を実行します。"""
server_proc = mp.Process(target=Sample.server, args=())
client_procs = [mp.Process(target=Sample.client, args=(str(i),)) for i in range(10, 61, 10)]
client_all_proc = mp.Process(target=Sample.c... | the_stack_v2_python_sparse | trypython/extlib/zmq/zmq02.py | devlights/try-python-extlib | train | 0 |
35a1278cccb18d15aed26b6add0860d905920a97 | [
"if root is None:\n return '()'\nreturn '({}{}{})'.format(root.val, self.serialize(root.left), self.serialize(root.right))",
"data = data[1:len(data) - 1]\nif not data:\n return None\nflp = data.index('(')\ncur_node = TreeNode(int(data[:flp]))\nscore = 0\nfor i in range(flp, len(data)):\n if data[i] == '... | <|body_start_0|>
if root is None:
return '()'
return '({}{}{})'.format(root.val, self.serialize(root.left), self.serialize(root.right))
<|end_body_0|>
<|body_start_1|>
data = data[1:len(data) - 1]
if not data:
return None
flp = data.index('(')
cur... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005672 | 2,318 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 34a78e06d493e61b21d4442747e9102abf9b319b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return '()'
return '({}{}{})'.format(root.val, self.serialize(root.left), self.serialize(root.right))
def deserialize(self, data):
"""De... | the_stack_v2_python_sparse | 297_Serialize_and_Deserialize_Binary_Tree.py | sunnyyeti/Leetcode-solutions | train | 0 | |
4c8a5b72ba9fb1f23d9cbfaa2698a533322adc8e | [
"executable = configuration.get('executable')\nif not executable:\n raise ValueError(\"No 'executable' given in configuration of %s\", configuration['name'])\narguments = [executable]\nfor level in (configuration, configuration.get('boot', {})):\n boot_args = level.get('boot_args')\n if boot_args:\n ... | <|body_start_0|>
executable = configuration.get('executable')
if not executable:
raise ValueError("No 'executable' given in configuration of %s", configuration['name'])
arguments = [executable]
for level in (configuration, configuration.get('boot', {})):
boot_args... | Isolate starter for simple executables | ExeStarter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExeStarter:
"""Isolate starter for simple executables"""
def _prepare_arguments(configuration):
"""Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first one being the name of the executable"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_005673 | 4,207 | permissive | [
{
"docstring": "Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first one being the name of the executable",
"name": "_prepare_arguments",
"signature": "def _prepare_arguments(configuration)"
},
{
"docstring": "Starts an is... | 2 | stack_v2_sparse_classes_30k_train_009477 | Implement the Python class `ExeStarter` described below.
Class description:
Isolate starter for simple executables
Method signatures and docstrings:
- def _prepare_arguments(configuration): Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first o... | Implement the Python class `ExeStarter` described below.
Class description:
Isolate starter for simple executables
Method signatures and docstrings:
- def _prepare_arguments(configuration): Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first o... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class ExeStarter:
"""Isolate starter for simple executables"""
def _prepare_arguments(configuration):
"""Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first one being the name of the executable"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExeStarter:
"""Isolate starter for simple executables"""
def _prepare_arguments(configuration):
"""Prepares arguments to run an executable :param configuration: An isolate configuration :return: A list of arguments, the first one being the name of the executable"""
executable = configurat... | the_stack_v2_python_sparse | python/cohorte/forker/starters/exe.py | cohorte/cohorte-runtime | train | 3 |
1520a971329c4150b93b3ff3ce58efa576077087 | [
"super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)\nself.hash_length = 256\nself.hash_256 = lambda x: generate_256_hash()(x) % self.hash_length\nself.word_client = self.client\nif frag_client is not None:\n self.fragment_client = copy.deepcopy(self.... | <|body_start_0|>
super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)
self.hash_length = 256
self.hash_256 = lambda x: generate_256_hash()(x) % self.hash_length
self.word_client = self.client
if frag_client is not None:... | SFPClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_str... | stack_v2_sparse_classes_36k_train_005674 | 3,799 | permissive | [
{
"docstring": "Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_string_length (int): maximum size of the strings to find alphabet (optional list): The alphabet over which we are privatising strings index_mapper (optional func): Index map fu... | 3 | stack_v2_sparse_classes_30k_train_021440 | Implement the Python class `SFPClient` described below.
Class description:
Implement the SFPClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'): Args: epsilon: float priv... | Implement the Python class `SFPClient` described below.
Class description:
Implement the SFPClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'): Args: epsilon: float priv... | d0fe2a8ce29515a638d6964419b72b58046dcc44 | <|skeleton|>
class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_string_length (in... | the_stack_v2_python_sparse | pure_ldp/heavy_hitters/apple_sfp/sfp_client.py | hbcbh1999/pure-LDP | train | 0 | |
a0bb364f699895722d5ab88777a41059245036bd | [
"dummy_node = ListNode(-1)\ndummy_node.next = head\npre_node = dummy_node\ncur_node = dummy_node.next\nwhile cur_node:\n if cur_node.val == val:\n pre_node.next = cur_node.next\n break\n pre_node = cur_node\n cur_node = cur_node.next\nreturn dummy_node.next",
"if head.val == val:\n retur... | <|body_start_0|>
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
pre_node.next = cur_node.next
break
pre_node = cur_node
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy_nod... | stack_v2_sparse_classes_36k_train_005675 | 1,496 | no_license | [
{
"docstring": "使用了虚拟头节点,因为匹配的值可能是第一个。",
"name": "deleteNode2",
"signature": "def deleteNode2(self, head: ListNode, val: int) -> ListNode"
},
{
"docstring": "如果匹配的值是第一个直接返回即可.",
"name": "deleteNode",
"signature": "def deleteNode(self, head: ListNode, val: int) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_012971 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可.
<|skeleton|>
... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 18. 删除链表的节点.py | tenqaz/crazy_arithmetic | train | 0 | |
c1f75ab7a967e0786bb46318234cd997e53c5bf9 | [
"self.cryptogen = cryptogen + '/cryptogen'\nself.filepath = filepath\nself.version = version\nself.name = name",
"try:\n call([self.cryptogen, 'generate', '--output={}/{}/{}'.format(self.filepath, self.name, output), '--config={}/{}/{}'.format(self.filepath, self.name, config)])\nexcept Exception as e:\n er... | <|body_start_0|>
self.cryptogen = cryptogen + '/cryptogen'
self.filepath = filepath
self.version = version
self.name = name
<|end_body_0|>
<|body_start_1|>
try:
call([self.cryptogen, 'generate', '--output={}/{}/{}'.format(self.filepath, self.name, output), '--config=... | Class represents crypto-config tool. | CryptoGen | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CryptoGen:
"""Class represents crypto-config tool."""
def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0'):
"""init CryptoGen param: name: organization's name cryptogen: tool path version: version filepath: cello's working directory return:"""
... | stack_v2_sparse_classes_36k_train_005676 | 1,964 | permissive | [
{
"docstring": "init CryptoGen param: name: organization's name cryptogen: tool path version: version filepath: cello's working directory return:",
"name": "__init__",
"signature": "def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0')"
},
{
"docstring": "Generate... | 3 | stack_v2_sparse_classes_30k_train_006269 | Implement the Python class `CryptoGen` described below.
Class description:
Class represents crypto-config tool.
Method signatures and docstrings:
- def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0'): init CryptoGen param: name: organization's name cryptogen: tool path version: versi... | Implement the Python class `CryptoGen` described below.
Class description:
Class represents crypto-config tool.
Method signatures and docstrings:
- def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0'): init CryptoGen param: name: organization's name cryptogen: tool path version: versi... | cb4d24347228ad9d1ae24cd0d6188bf29b1b8cbe | <|skeleton|>
class CryptoGen:
"""Class represents crypto-config tool."""
def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0'):
"""init CryptoGen param: name: organization's name cryptogen: tool path version: version filepath: cello's working directory return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CryptoGen:
"""Class represents crypto-config tool."""
def __init__(self, name, filepath=CELLO_HOME, cryptogen=FABRIC_TOOL, version='2.2.0'):
"""init CryptoGen param: name: organization's name cryptogen: tool path version: version filepath: cello's working directory return:"""
self.cryptog... | the_stack_v2_python_sparse | src/api-engine/api/lib/pki/cryptogen/cryptogen.py | hyperledger/cello | train | 957 |
dd8f1f12622561cb2874aba12e32454de84f9840 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceInstallState()",
"from .entity import Entity\nfrom .install_state import InstallState\nfrom .entity import Entity\nfrom .install_state import InstallState\nfields: Dict[str, Callable[[Any], None]] = {'deviceId': lambda n: setattr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceInstallState()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .install_state import InstallState
from .entity import Entity
from .install_state imp... | Contains properties for the installation state for a device. | DeviceInstallState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | stack_v2_sparse_classes_36k_train_005677 | 3,783 | 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: DeviceInstallState",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_008728 | Implement the Python class `DeviceInstallState` described below.
Class description:
Contains properties for the installation state for a device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState: Creates a new instance of the appropriat... | Implement the Python class `DeviceInstallState` described below.
Class description:
Contains properties for the installation state for a device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node ... | the_stack_v2_python_sparse | msgraph/generated/models/device_install_state.py | microsoftgraph/msgraph-sdk-python | train | 135 |
1923eca2c554da07ddd0738b25996aefddf2ee0c | [
"l_project = get_project(name)\nif not len(l_project):\n d_msg = {'error': 'name {} is not found.'.format(name)}\n return (d_msg, 404)\nreturn l_project[0]",
"b_ret, s_msg = delete_project(name)\nif not b_ret:\n d_msg = {'error': s_msg}\n return (d_msg, 404)\nreturn (None, 204)"
] | <|body_start_0|>
l_project = get_project(name)
if not len(l_project):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_project[0]
<|end_body_0|>
<|body_start_1|>
b_ret, s_msg = delete_project(name)
if not b_ret:
... | ProjectItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectItem:
def get(self, name):
"""Returns the project information."""
<|body_0|>
def delete(self, name):
"""Deletes the project."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l_project = get_project(name)
if not len(l_project):
... | stack_v2_sparse_classes_36k_train_005678 | 2,133 | permissive | [
{
"docstring": "Returns the project information.",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "Deletes the project.",
"name": "delete",
"signature": "def delete(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019257 | Implement the Python class `ProjectItem` described below.
Class description:
Implement the ProjectItem class.
Method signatures and docstrings:
- def get(self, name): Returns the project information.
- def delete(self, name): Deletes the project. | Implement the Python class `ProjectItem` described below.
Class description:
Implement the ProjectItem class.
Method signatures and docstrings:
- def get(self, name): Returns the project information.
- def delete(self, name): Deletes the project.
<|skeleton|>
class ProjectItem:
def get(self, name):
"""R... | 65d01799296fce043e87ba58106f8fa8c1d8aa98 | <|skeleton|>
class ProjectItem:
def get(self, name):
"""Returns the project information."""
<|body_0|>
def delete(self, name):
"""Deletes the project."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectItem:
def get(self, name):
"""Returns the project information."""
l_project = get_project(name)
if not len(l_project):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_project[0]
def delete(self, name):
... | the_stack_v2_python_sparse | pengrixio/api/project/endpoints/route.py | iorchard/pengrixio | train | 0 | |
304acb7016bb103c0a2c3224b7ad2c9b43df6cc5 | [
"if not isinstance(existing_channels, ChannelMontageTuple):\n existing_channels = ChannelMontageTuple(existing_channels, True)\nif not isinstance(channels_required, ChannelMontageTuple):\n channels_required = ChannelMontageTuple(channels_required, True)\nself.channels_required = channels_required\nself.existi... | <|body_start_0|>
if not isinstance(existing_channels, ChannelMontageTuple):
existing_channels = ChannelMontageTuple(existing_channels, True)
if not isinstance(channels_required, ChannelMontageTuple):
channels_required = ChannelMontageTuple(channels_required, True)
self.ch... | TODO | ChannelMontageCreator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
<|body_0|>
def _create_montage(channel_data, channels, montage_to_create):
"""TODO Args: channel_data: channels: montage_to_create: Returns... | stack_v2_sparse_classes_36k_train_005679 | 7,729 | permissive | [
{
"docstring": "TODO",
"name": "__init__",
"signature": "def __init__(self, existing_channels, channels_required, allow_missing=False)"
},
{
"docstring": "TODO Args: channel_data: channels: montage_to_create: Returns:",
"name": "_create_montage",
"signature": "def _create_montage(channel... | 3 | stack_v2_sparse_classes_30k_train_007026 | Implement the Python class `ChannelMontageCreator` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, existing_channels, channels_required, allow_missing=False): TODO
- def _create_montage(channel_data, channels, montage_to_create): TODO Args: channel_data: channels: monta... | Implement the Python class `ChannelMontageCreator` described below.
Class description:
TODO
Method signatures and docstrings:
- def __init__(self, existing_channels, channels_required, allow_missing=False): TODO
- def _create_montage(channel_data, channels, montage_to_create): TODO Args: channel_data: channels: monta... | f7c8e3f1368f43226872a69b0fbb8c29990e4bd9 | <|skeleton|>
class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
<|body_0|>
def _create_montage(channel_data, channels, montage_to_create):
"""TODO Args: channel_data: channels: montage_to_create: Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelMontageCreator:
"""TODO"""
def __init__(self, existing_channels, channels_required, allow_missing=False):
"""TODO"""
if not isinstance(existing_channels, ChannelMontageTuple):
existing_channels = ChannelMontageTuple(existing_channels, True)
if not isinstance(cha... | the_stack_v2_python_sparse | utime/io/channels/montage_creator.py | jennynanap/U-Time | train | 0 |
9b6a98d96b52a2a80e2eeda2d43d5bd68ed7af93 | [
"dict_s, dict_t = ({}, {})\nfor i in s:\n if i not in dict_s:\n dict_s[i] = 1\n else:\n dict_s[i] += 1\nfor i in t:\n if i not in dict_t:\n dict_t[i] = 1\n else:\n dict_t[i] += 1\nreturn True if dict_s == dict_t else False",
"dict_str = {}\nif len(s) != len(t):\n return ... | <|body_start_0|>
dict_s, dict_t = ({}, {})
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
for i in t:
if i not in dict_t:
dict_t[i] = 1
else:
dict_t[i] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAnagram1(self, s: str, t: str) -> bool:
"""通过dict形式"""
<|body_0|>
def isAnagram2(self, s: str, t: str) -> bool:
"""通过dict形式,优化只需要一个dict"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict_s, dict_t = ({}, {})
for i in s:
... | stack_v2_sparse_classes_36k_train_005680 | 1,363 | no_license | [
{
"docstring": "通过dict形式",
"name": "isAnagram1",
"signature": "def isAnagram1(self, s: str, t: str) -> bool"
},
{
"docstring": "通过dict形式,优化只需要一个dict",
"name": "isAnagram2",
"signature": "def isAnagram2(self, s: str, t: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_010201 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram1(self, s: str, t: str) -> bool: 通过dict形式
- def isAnagram2(self, s: str, t: str) -> bool: 通过dict形式,优化只需要一个dict | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram1(self, s: str, t: str) -> bool: 通过dict形式
- def isAnagram2(self, s: str, t: str) -> bool: 通过dict形式,优化只需要一个dict
<|skeleton|>
class Solution:
def isAnagram1(self... | d265eb981a7586d46d0ced3accc2ea186dc7691c | <|skeleton|>
class Solution:
def isAnagram1(self, s: str, t: str) -> bool:
"""通过dict形式"""
<|body_0|>
def isAnagram2(self, s: str, t: str) -> bool:
"""通过dict形式,优化只需要一个dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isAnagram1(self, s: str, t: str) -> bool:
"""通过dict形式"""
dict_s, dict_t = ({}, {})
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
for i in t:
if i not in dict_t:
... | the_stack_v2_python_sparse | pythonCode/No241-250/no242.py | odinfor/leetcode | train | 0 | |
ac9a15cc097da230fd2a669e061a4f8322aaec31 | [
"if game_state is None:\n self.ball: PhysicsWrapper = PhysicsWrapper()\n self.cars: List[CarWrapper] = []\n for i in range(blue_count):\n self.cars.append(CarWrapper(0, BLUE_ID1 + i))\n for i in range(orange_count):\n self.cars.append(CarWrapper(1, ORANGE_ID1 + i))\nelse:\n self._read_f... | <|body_start_0|>
if game_state is None:
self.ball: PhysicsWrapper = PhysicsWrapper()
self.cars: List[CarWrapper] = []
for i in range(blue_count):
self.cars.append(CarWrapper(0, BLUE_ID1 + i))
for i in range(orange_count):
self.cars.... | StateWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateWrapper:
def __init__(self, blue_count: int=0, orange_count: int=0, game_state=None):
"""StateWrapper constructor. Under most circumstances, users should not expect to instantiate their own StateWrapper objects. :param blue_count: Integer indicating the amount of players on the blue... | stack_v2_sparse_classes_36k_train_005681 | 7,156 | permissive | [
{
"docstring": "StateWrapper constructor. Under most circumstances, users should not expect to instantiate their own StateWrapper objects. :param blue_count: Integer indicating the amount of players on the blue team. :param orange_count: Integer indicating The amount of players on the orange team. :param game_s... | 3 | stack_v2_sparse_classes_30k_train_001075 | Implement the Python class `StateWrapper` described below.
Class description:
Implement the StateWrapper class.
Method signatures and docstrings:
- def __init__(self, blue_count: int=0, orange_count: int=0, game_state=None): StateWrapper constructor. Under most circumstances, users should not expect to instantiate th... | Implement the Python class `StateWrapper` described below.
Class description:
Implement the StateWrapper class.
Method signatures and docstrings:
- def __init__(self, blue_count: int=0, orange_count: int=0, game_state=None): StateWrapper constructor. Under most circumstances, users should not expect to instantiate th... | 7f07bfa980b84eea11627939dd7d7b1689efcfa7 | <|skeleton|>
class StateWrapper:
def __init__(self, blue_count: int=0, orange_count: int=0, game_state=None):
"""StateWrapper constructor. Under most circumstances, users should not expect to instantiate their own StateWrapper objects. :param blue_count: Integer indicating the amount of players on the blue... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateWrapper:
def __init__(self, blue_count: int=0, orange_count: int=0, game_state=None):
"""StateWrapper constructor. Under most circumstances, users should not expect to instantiate their own StateWrapper objects. :param blue_count: Integer indicating the amount of players on the blue team. :param ... | the_stack_v2_python_sparse | rlgym/utils/state_setters/state_wrapper.py | L0laapk3/rocket-league-gym | train | 0 | |
46b1fce46aaec00aee7e8011fc02a3a7a6e62714 | [
"loan = Loan.objects.all()\nserializer = LoanSerializer2(loan, many=True)\nreturn Response(serializer.data)",
"json_data = request.data\nloan = {'loan_amount': request.data['loan_amount'], 'loan_duration': request.data['loan_duration'], 'rate_of_interest': request.data['rate_of_interest'], 'interest_amount': requ... | <|body_start_0|>
loan = Loan.objects.all()
serializer = LoanSerializer2(loan, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
json_data = request.data
loan = {'loan_amount': request.data['loan_amount'], 'loan_duration': request.data['loan_duration'], ... | Management | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Management:
def get(self, request):
"""Get tha Loan data."""
<|body_0|>
def post(self, request):
"""Post loan data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
loan = Loan.objects.all()
serializer = LoanSerializer2(loan, many=True)
... | stack_v2_sparse_classes_36k_train_005682 | 3,932 | no_license | [
{
"docstring": "Get tha Loan data.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Post loan data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013059 | Implement the Python class `Management` described below.
Class description:
Implement the Management class.
Method signatures and docstrings:
- def get(self, request): Get tha Loan data.
- def post(self, request): Post loan data | Implement the Python class `Management` described below.
Class description:
Implement the Management class.
Method signatures and docstrings:
- def get(self, request): Get tha Loan data.
- def post(self, request): Post loan data
<|skeleton|>
class Management:
def get(self, request):
"""Get tha Loan data... | 83455c50e2ee910f03db47fbe1420d1cbd7eb292 | <|skeleton|>
class Management:
def get(self, request):
"""Get tha Loan data."""
<|body_0|>
def post(self, request):
"""Post loan data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Management:
def get(self, request):
"""Get tha Loan data."""
loan = Loan.objects.all()
serializer = LoanSerializer2(loan, many=True)
return Response(serializer.data)
def post(self, request):
"""Post loan data"""
json_data = request.data
loan = {'loa... | the_stack_v2_python_sparse | mcred/loan_operation/views.py | vshaladhav97/django_practise_projects | train | 0 | |
a45f8238b4d14d35f9c3a97c49be7b82349847d0 | [
"context_data = super(ProfileSocialUpdate, self).get_context_data(**kwargs)\nif self.request.POST:\n context_data['usersocials'] = SocialUserFormSet(self.request.POST, instance=self.object)\nelse:\n context_data['usersocials'] = SocialUserFormSet(instance=self.object)\nreturn context_data",
"context = self.... | <|body_start_0|>
context_data = super(ProfileSocialUpdate, self).get_context_data(**kwargs)
if self.request.POST:
context_data['usersocials'] = SocialUserFormSet(self.request.POST, instance=self.object)
else:
context_data['usersocials'] = SocialUserFormSet(instance=self.o... | Profile Create/Update Form | ProfileSocialUpdate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileSocialUpdate:
"""Profile Create/Update Form"""
def get_context_data(self, **kwargs):
"""Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Based-Views. :param kwargs: :return:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_005683 | 7,183 | no_license | [
{
"docstring": "Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Based-Views. :param kwargs: :return:",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Saves social... | 2 | stack_v2_sparse_classes_30k_train_016379 | Implement the Python class `ProfileSocialUpdate` described below.
Class description:
Profile Create/Update Form
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Ba... | Implement the Python class `ProfileSocialUpdate` described below.
Class description:
Profile Create/Update Form
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Ba... | b06dde37ca24f60050bee1f48a02ac8e5bf2b3c0 | <|skeleton|>
class ProfileSocialUpdate:
"""Profile Create/Update Form"""
def get_context_data(self, **kwargs):
"""Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Based-Views. :param kwargs: :return:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileSocialUpdate:
"""Profile Create/Update Form"""
def get_context_data(self, **kwargs):
"""Adds social media platforms formset to profile update form since they're on a related table and are not easily accessed via Class-Based-Views. :param kwargs: :return:"""
context_data = super(Pro... | the_stack_v2_python_sparse | accounts/views.py | bo-boka/tech-collab | train | 0 |
5e1a0dbf05923b37b90d66627727da342d894863 | [
"query = '\\n INSERT\\n INTO blob_encryption_keys(blob_id, key_name)\\n VALUES (%s, %s)\\n '\nargs = []\nfor blob_id, key_name in key_names.items():\n args.append((blob_id.AsBytes(), key_name))\ncursor.executemany(query, args)",
"if not blob_ids:\n return {}\nblob_ids_bytes = [blob_id.AsBytes(... | <|body_start_0|>
query = '\n INSERT\n INTO blob_encryption_keys(blob_id, key_name)\n VALUES (%s, %s)\n '
args = []
for blob_id, key_name in key_names.items():
args.append((blob_id.AsBytes(), key_name))
cursor.executemany(query, args)
<|end_body_0|>
<|body_start... | A MySQL database mixin class with blobstore encryption keys methods. | MySQLDBBlobKeysMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLDBBlobKeysMixin:
"""A MySQL database mixin class with blobstore encryption keys methods."""
def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None:
"""Associates the specified blobs with the given encryption keys."""
... | stack_v2_sparse_classes_36k_train_005684 | 2,122 | permissive | [
{
"docstring": "Associates the specified blobs with the given encryption keys.",
"name": "WriteBlobEncryptionKeys",
"signature": "def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None"
},
{
"docstring": "Retrieves encryption keys asso... | 2 | null | Implement the Python class `MySQLDBBlobKeysMixin` described below.
Class description:
A MySQL database mixin class with blobstore encryption keys methods.
Method signatures and docstrings:
- def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None: Associates... | Implement the Python class `MySQLDBBlobKeysMixin` described below.
Class description:
A MySQL database mixin class with blobstore encryption keys methods.
Method signatures and docstrings:
- def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None: Associates... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class MySQLDBBlobKeysMixin:
"""A MySQL database mixin class with blobstore encryption keys methods."""
def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None:
"""Associates the specified blobs with the given encryption keys."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySQLDBBlobKeysMixin:
"""A MySQL database mixin class with blobstore encryption keys methods."""
def WriteBlobEncryptionKeys(self, key_names: Dict[rdf_objects.BlobID, str], cursor: MySQLdb.cursors.Cursor) -> None:
"""Associates the specified blobs with the given encryption keys."""
query ... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/mysql_blob_keys.py | google/grr | train | 4,683 |
8d925e4c7a2719ac7a10c0546a33b42d738b758e | [
"self.api_adapter = api_adapter\nself.gke_uri = gke_uri\nself.gke_cluster = gke_cluster\nself.kubeconfig = kubeconfig\nself.internal_ip = internal_ip\nself.cross_connect_subnetwork = cross_connect_subnetwork\nself.private_endpoint_fqdn = private_endpoint_fqdn\nself.context = context\nif not c_util.CheckKubectlInsta... | <|body_start_0|>
self.api_adapter = api_adapter
self.gke_uri = gke_uri
self.gke_cluster = gke_cluster
self.kubeconfig = kubeconfig
self.internal_ip = internal_ip
self.cross_connect_subnetwork = cross_connect_subnetwork
self.private_endpoint_fqdn = private_endpoint... | A helper class that processes kubeconfig and context arguments. | KubeconfigProcessor | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapt... | stack_v2_sparse_classes_36k_train_005685 | 44,482 | permissive | [
{
"docstring": "Constructor for KubeconfigProcessor. Args: api_adapter: the GKE api adapter used for running kubernetes commands gke_uri: the URI of the GKE cluster; for example, 'https://container.googleapis.com/v1/projects/my-project/locations/us-central1-a/clusters/my-cluster' gke_cluster: the \"location/nam... | 3 | null | Implement the Python class `KubeconfigProcessor` described below.
Class description:
A helper class that processes kubeconfig and context arguments.
Method signatures and docstrings:
- def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, conte... | Implement the Python class `KubeconfigProcessor` described below.
Class description:
A helper class that processes kubeconfig and context arguments.
Method signatures and docstrings:
- def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, conte... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapter: the GKE a... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/container/hub/kube_util.py | twistedpair/google-cloud-sdk | train | 58 |
03ef2d1b7ccd3387384920667193fdba7791550b | [
"i = 1\nlistUsername = ['185']\nwhile i <= 8:\n Usernamecode = str(random.choice(range(10)))\n listUsername.append(Usernamecode)\n i += 1\nlogging.info(f'手机号为:{listUsername}')\nreturn ''.join(listUsername)",
"i = 1\nlist_username_i_d = ['2321']\nwhile i <= 14:\n Usernamecode = str(random.choice(range(... | <|body_start_0|>
i = 1
listUsername = ['185']
while i <= 8:
Usernamecode = str(random.choice(range(10)))
listUsername.append(Usernamecode)
i += 1
logging.info(f'手机号为:{listUsername}')
return ''.join(listUsername)
<|end_body_0|>
<|body_start_1|>... | myMethod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myMethod:
def randomTel(self):
""":return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机"""
<|body_0|>
def randomID(self):
""":return:身份证号码"""
<|body_1|>
def bankId(self):
""":return: 银行卡号 6212260200094536345"""
<|body_2|>
def wait_time(self, ... | stack_v2_sparse_classes_36k_train_005686 | 14,739 | no_license | [
{
"docstring": ":return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机",
"name": "randomTel",
"signature": "def randomTel(self)"
},
{
"docstring": ":return:身份证号码",
"name": "randomID",
"signature": "def randomID(self)"
},
{
"docstring": ":return: 银行卡号 6212260200094536345",
"name": "bank... | 4 | stack_v2_sparse_classes_30k_val_000903 | Implement the Python class `myMethod` described below.
Class description:
Implement the myMethod class.
Method signatures and docstrings:
- def randomTel(self): :return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机
- def randomID(self): :return:身份证号码
- def bankId(self): :return: 银行卡号 6212260200094536345
- def wait_time(self, ... | Implement the Python class `myMethod` described below.
Class description:
Implement the myMethod class.
Method signatures and docstrings:
- def randomTel(self): :return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机
- def randomID(self): :return:身份证号码
- def bankId(self): :return: 银行卡号 6212260200094536345
- def wait_time(self, ... | 93fe784a3127e76995e9ae018605efbe78238385 | <|skeleton|>
class myMethod:
def randomTel(self):
""":return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机"""
<|body_0|>
def randomID(self):
""":return:身份证号码"""
<|body_1|>
def bankId(self):
""":return: 银行卡号 6212260200094536345"""
<|body_2|>
def wait_time(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class myMethod:
def randomTel(self):
""":return: 封装一个随机生成电话号码的方法,默认方法首位字母为185,其余八位随机"""
i = 1
listUsername = ['185']
while i <= 8:
Usernamecode = str(random.choice(range(10)))
listUsername.append(Usernamecode)
i += 1
logging.info(f'手机号为:{li... | the_stack_v2_python_sparse | 早期/熊猫.py | huangno27/learn | train | 0 | |
63de02efd96c938e770916f822e15843bfe1d4de | [
"self.Lbox = 250.0\nself.particle_mass = 100000000.0\nself.simname = 'fake'\nself.seed = seed\nself.num_massbins = num_massbins\nself.num_halos_per_massbin = num_halos_per_massbin\nself.num_halos = self.num_massbins * self.num_halos_per_massbin\nself.num_ptcl = num_ptcl",
"np.random.seed(self.seed)\nhaloid = np.a... | <|body_start_0|>
self.Lbox = 250.0
self.particle_mass = 100000000.0
self.simname = 'fake'
self.seed = seed
self.num_massbins = num_massbins
self.num_halos_per_massbin = num_halos_per_massbin
self.num_halos = self.num_massbins * self.num_halos_per_massbin
s... | Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The columns of the `halos` and `particles` attributes of `FakeSim` are generated w... | FakeSim | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FakeSim:
"""Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The columns of the `halos` and `particles` attr... | stack_v2_sparse_classes_36k_train_005687 | 11,539 | permissive | [
{
"docstring": "Parameters ---------- num_massbins : int, optional Number of distinct masses that will appear in the halo catalog. Default is 6. num_halos_per_massbin : int, optional Default is 1000 num_ptcl : int, optional Number of dark matter particles. Default is 1000. seed : int, optional Random number see... | 3 | stack_v2_sparse_classes_30k_train_018742 | Implement the Python class `FakeSim` described below.
Class description:
Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The colu... | Implement the Python class `FakeSim` described below.
Class description:
Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The colu... | f63988f7e1d66c7c19d7c2b4d628ed2524b7aec1 | <|skeleton|>
class FakeSim:
"""Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The columns of the `halos` and `particles` attr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FakeSim:
"""Fake simulation data used in the test suite of `~halotools.empirical_models`. The `FakeSim` object has all the attributes required by Mock Factories such as `~halotools.empirical_models.HodMockFactory` to create a mock galaxy population. The columns of the `halos` and `particles` attributes of `Fa... | the_stack_v2_python_sparse | halotools/sim_manager/generate_random_sim.py | lanakurdi/halotools | train | 1 |
a523e67d0ec10737d8979193fec21051a91a82b4 | [
"nums.sort()\nres = []\nfor i in range(len(nums) - 2):\n if i == 0 or nums[i] != nums[i - 1]:\n low = i + 1\n high = len(nums) - 1\n target = -1 * nums[i]\n while low < high:\n if nums[low] + nums[high] == target:\n res.append([nums[i], nums[low], nums[high]]... | <|body_start_0|>
nums.sort()
res = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] != nums[i - 1]:
low = i + 1
high = len(nums) - 1
target = -1 * nums[i]
while low < high:
if nums[low] + nums[h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
res = [... | stack_v2_sparse_classes_36k_train_005688 | 2,228 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015980 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | a56efa191b075f25793aafbf7e6d100a06011cb7 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
res = []
for i in range(len(nums) - 2):
if i == 0 or nums[i] != nums[i - 1]:
low = i + 1
high = len(nums) - 1
target =... | the_stack_v2_python_sparse | 3Sum.py | JustinNew/LeetCode2 | train | 0 | |
ba9c3d93f21944a4b7f6dbf60a31d7663516af06 | [
"email_account_map = collections.defaultdict(list)\nfor i, account in enumerate(accounts):\n for email in account[1:]:\n email_account_map[email].append(i)\n\ndef dfs(i, emails, visited):\n if visited[i]:\n return\n visited[i] = True\n for email in accounts[i][1:]:\n emails.add(emai... | <|body_start_0|>
email_account_map = collections.defaultdict(list)
for i, account in enumerate(accounts):
for email in account[1:]:
email_account_map[email].append(i)
def dfs(i, emails, visited):
if visited[i]:
return
visited[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]:
"""graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))"""
<|body_0|>
def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]:
"""union-find"""
... | stack_v2_sparse_classes_36k_train_005689 | 4,358 | no_license | [
{
"docstring": "graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))",
"name": "accountsMerge1",
"signature": "def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]"
},
{
"docstring": "union-find",
"name": "accountsMerge1",
"signature": "def accou... | 2 | stack_v2_sparse_classes_30k_train_013231 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))
- def accountsMerge1(self, ac... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))
- def accountsMerge1(self, ac... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]:
"""graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))"""
<|body_0|>
def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]:
"""union-find"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]:
"""graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))"""
email_account_map = collections.defaultdict(list)
for i, account in enumerate(accounts):
for email in account... | the_stack_v2_python_sparse | Leetcode 0721. Accounts Merge.py | Chaoran-sjsu/leetcode | train | 0 | |
481734dba7e7c4c179d6a8924ce14e7163d4b72d | [
"if x < 0:\n sig = True\n x = -x\nelse:\n sig = False\nx_reverse = 0\nwhile x > 0:\n x_reverse = x_reverse * 10 + x % 10\n x = x // 10\nif sig:\n x_reverse = -x_reverse\nif -2 ** 31 <= x_reverse < 2 ** 31:\n return x_reverse\nelse:\n return 0",
"if x >= 0:\n x = int(str(x)[::-1])\nelse:... | <|body_start_0|>
if x < 0:
sig = True
x = -x
else:
sig = False
x_reverse = 0
while x > 0:
x_reverse = x_reverse * 10 + x % 10
x = x // 10
if sig:
x_reverse = -x_reverse
if -2 ** 31 <= x_reverse < 2 **... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
"""a direct solution"""
<|body_0|>
def reverse2(self, x):
"""string method"""
<|body_1|>
def reverse3(self, x):
"""binary method"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
... | stack_v2_sparse_classes_36k_train_005690 | 1,694 | permissive | [
{
"docstring": "a direct solution",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": "string method",
"name": "reverse2",
"signature": "def reverse2(self, x)"
},
{
"docstring": "binary method",
"name": "reverse3",
"signature": "def reverse3(self, x... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): a direct solution
- def reverse2(self, x): string method
- def reverse3(self, x): binary method | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): a direct solution
- def reverse2(self, x): string method
- def reverse3(self, x): binary method
<|skeleton|>
class Solution:
def reverse(self, x):
... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def reverse(self, x):
"""a direct solution"""
<|body_0|>
def reverse2(self, x):
"""string method"""
<|body_1|>
def reverse3(self, x):
"""binary method"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
"""a direct solution"""
if x < 0:
sig = True
x = -x
else:
sig = False
x_reverse = 0
while x > 0:
x_reverse = x_reverse * 10 + x % 10
x = x // 10
if sig:
x_rev... | the_stack_v2_python_sparse | leetcode/0007_reverse_integer.py | chaosWsF/Python-Practice | train | 1 | |
a16a4f21792204d488fa34cf1f0bd0dd4a90b40a | [
"self.frag_centers = frag_centers\nself.frag_sizes = frag_sizes\nself.renderer = renderer\nself.knn_frags = knn_frags",
"num_pts = xyz.shape[0]\nnn_index = spatial.cKDTree(self.frag_centers[obj_id])\nnn_dists, nn_ids = nn_index.query(xyz, k=self.knn_frags)\nnn_weights = np.ones((num_pts, self.knn_frags), np.float... | <|body_start_0|>
self.frag_centers = frag_centers
self.frag_sizes = frag_sizes
self.renderer = renderer
self.knn_frags = knn_frags
<|end_body_0|>
<|body_start_1|>
num_pts = xyz.shape[0]
nn_index = spatial.cKDTree(self.frag_centers[obj_id])
nn_dists, nn_ids = nn_i... | Generates GT fields with fragment labels and 3D fragment coordinates. | FragmentFieldGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FragmentFieldGenerator:
"""Generates GT fields with fragment labels and 3D fragment coordinates."""
def __init__(self, frag_centers, frag_sizes, renderer, knn_frags=1):
"""Initializes the fragment field generator. Args: frag_centers: Map from obj ID to [num_bins, 3] ndarray with frag... | stack_v2_sparse_classes_36k_train_005691 | 9,350 | permissive | [
{
"docstring": "Initializes the fragment field generator. Args: frag_centers: Map from obj ID to [num_bins, 3] ndarray with frag. centers. frag_sizes: A map from obj ID to [num_bins] ndarray with fragment sizes. knn_frags: Number of the nearest fragments to assign to each point on the model surface. renderer: R... | 4 | stack_v2_sparse_classes_30k_train_019881 | Implement the Python class `FragmentFieldGenerator` described below.
Class description:
Generates GT fields with fragment labels and 3D fragment coordinates.
Method signatures and docstrings:
- def __init__(self, frag_centers, frag_sizes, renderer, knn_frags=1): Initializes the fragment field generator. Args: frag_ce... | Implement the Python class `FragmentFieldGenerator` described below.
Class description:
Generates GT fields with fragment labels and 3D fragment coordinates.
Method signatures and docstrings:
- def __init__(self, frag_centers, frag_sizes, renderer, knn_frags=1): Initializes the fragment field generator. Args: frag_ce... | d67657bbb06da5a6adb8a035a2f58fc305e396f7 | <|skeleton|>
class FragmentFieldGenerator:
"""Generates GT fields with fragment labels and 3D fragment coordinates."""
def __init__(self, frag_centers, frag_sizes, renderer, knn_frags=1):
"""Initializes the fragment field generator. Args: frag_centers: Map from obj ID to [num_bins, 3] ndarray with frag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FragmentFieldGenerator:
"""Generates GT fields with fragment labels and 3D fragment coordinates."""
def __init__(self, frag_centers, frag_sizes, renderer, knn_frags=1):
"""Initializes the fragment field generator. Args: frag_centers: Map from obj ID to [num_bins, 3] ndarray with frag. centers. fr... | the_stack_v2_python_sparse | epos_lib/datagen_utils.py | Joris-dehoog/epos | train | 0 |
bef906634579f0acf939507a9ba3a24a93016370 | [
"try:\n blog = Blog.objects.get(id=self.kwargs.get('blog_pk'))\n return blog.likes.all()\nexcept Blog.DoesNotExist:\n return []",
"data = {'status': True}\ncurrent_user = request.user\ntry:\n blog = Blog.objects.get(id=kwargs.get('blog_pk'))\n react_type = blog.react(current_user)\n data['msg'] ... | <|body_start_0|>
try:
blog = Blog.objects.get(id=self.kwargs.get('blog_pk'))
return blog.likes.all()
except Blog.DoesNotExist:
return []
<|end_body_0|>
<|body_start_1|>
data = {'status': True}
current_user = request.user
try:
blog ... | API Controller to manage likes on the blog. | LikeBlogAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikeBlogAPIView:
"""API Controller to manage likes on the blog."""
def get_queryset(self):
"""Return the list of liked user of a specific blog."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Performing like and unlike on block."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005692 | 6,013 | no_license | [
{
"docstring": "Return the list of liked user of a specific blog.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Performing like and unlike on block.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008514 | Implement the Python class `LikeBlogAPIView` described below.
Class description:
API Controller to manage likes on the blog.
Method signatures and docstrings:
- def get_queryset(self): Return the list of liked user of a specific blog.
- def post(self, request, *args, **kwargs): Performing like and unlike on block. | Implement the Python class `LikeBlogAPIView` described below.
Class description:
API Controller to manage likes on the blog.
Method signatures and docstrings:
- def get_queryset(self): Return the list of liked user of a specific blog.
- def post(self, request, *args, **kwargs): Performing like and unlike on block.
<... | 74c9eba52b4f47d60fad17b6cba874e3547b37d4 | <|skeleton|>
class LikeBlogAPIView:
"""API Controller to manage likes on the blog."""
def get_queryset(self):
"""Return the list of liked user of a specific blog."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Performing like and unlike on block."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LikeBlogAPIView:
"""API Controller to manage likes on the blog."""
def get_queryset(self):
"""Return the list of liked user of a specific blog."""
try:
blog = Blog.objects.get(id=self.kwargs.get('blog_pk'))
return blog.likes.all()
except Blog.DoesNotExist:
... | the_stack_v2_python_sparse | apps/blog/views.py | cisin-python/django-rest-sample | train | 0 |
2bf8bb6ba837db4e60674ae98d90e11276c90f1f | [
"self.root = root.lstrip('/')\nself.conf = conf\nself.scon = SwiftConnector(self.root, self.conf)\nobjects = self.scon.get_container_objects()\nif not objects:\n raise Exception('There is not any GIT repo here : %s' % self.root)\nobjects = [o['name'].split('/')[0] for o in objects]\nif OBJECTDIR not in objects:\... | <|body_start_0|>
self.root = root.lstrip('/')
self.conf = conf
self.scon = SwiftConnector(self.root, self.conf)
objects = self.scon.get_container_objects()
if not objects:
raise Exception('There is not any GIT repo here : %s' % self.root)
objects = [o['name'].... | SwiftRepo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwiftRepo:
def __init__(self, root, conf):
"""Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attribute is the Swift container that contain the Git bare repository. :param root: The container which ... | stack_v2_sparse_classes_36k_train_005693 | 34,936 | permissive | [
{
"docstring": "Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attribute is the Swift container that contain the Git bare repository. :param root: The container which contains the bare repo :param conf: A ConfigParser obj... | 3 | stack_v2_sparse_classes_30k_train_006821 | Implement the Python class `SwiftRepo` described below.
Class description:
Implement the SwiftRepo class.
Method signatures and docstrings:
- def __init__(self, root, conf): Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attrib... | Implement the Python class `SwiftRepo` described below.
Class description:
Implement the SwiftRepo class.
Method signatures and docstrings:
- def __init__(self, root, conf): Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attrib... | 7d482c7db2c7b4daae10289b765f09a4f348a50c | <|skeleton|>
class SwiftRepo:
def __init__(self, root, conf):
"""Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attribute is the Swift container that contain the Git bare repository. :param root: The container which ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwiftRepo:
def __init__(self, root, conf):
"""Init a Git bare Repository on top of a Swift container. References are managed in info/refs objects by `SwiftInfoRefsContainer`. The root attribute is the Swift container that contain the Git bare repository. :param root: The container which contains the b... | the_stack_v2_python_sparse | site-packages/stash/lib/dulwich/contrib/swift.py | DocVaughan/Pythonista | train | 7 | |
cd34f510e5250e6220afb5084fc86c2d44fbfb66 | [
"self.repeat_period = repeat_period\nself._last_log_time = 0\nself.last_state = self.ST_IN_RANGE",
"now = time.time()\ncurrent_state = self.ST_OUT_OF_RANGE if min_age < -warn_limit or max_age > warn_limit else self.ST_IN_RANGE\nwarning_state, shall_repeat = self.result_lookup[self.last_state, current_state]\nif s... | <|body_start_0|>
self.repeat_period = repeat_period
self._last_log_time = 0
self.last_state = self.ST_IN_RANGE
<|end_body_0|>
<|body_start_1|>
now = time.time()
current_state = self.ST_OUT_OF_RANGE if min_age < -warn_limit or max_age > warn_limit else self.ST_IN_RANGE
wa... | A Helper to reduce log warnings regarding determination time. | DeterminationTimeWarner | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeterminationTimeWarner:
"""A Helper to reduce log warnings regarding determination time."""
def __init__(self, repeat_period: int=30):
"""Construct the DeterminationTimeWarner. :param repeat_period: period after which an existing warning condition the warning shall be repeated."""
... | stack_v2_sparse_classes_36k_train_005694 | 21,820 | permissive | [
{
"docstring": "Construct the DeterminationTimeWarner. :param repeat_period: period after which an existing warning condition the warning shall be repeated.",
"name": "__init__",
"signature": "def __init__(self, repeat_period: int=30)"
},
{
"docstring": ":return: one of above constants.",
"n... | 2 | stack_v2_sparse_classes_30k_train_006270 | Implement the Python class `DeterminationTimeWarner` described below.
Class description:
A Helper to reduce log warnings regarding determination time.
Method signatures and docstrings:
- def __init__(self, repeat_period: int=30): Construct the DeterminationTimeWarner. :param repeat_period: period after which an exist... | Implement the Python class `DeterminationTimeWarner` described below.
Class description:
A Helper to reduce log warnings regarding determination time.
Method signatures and docstrings:
- def __init__(self, repeat_period: int=30): Construct the DeterminationTimeWarner. :param repeat_period: period after which an exist... | dab57b38ed9a9e70e6bc6a9cf44140b96fd95851 | <|skeleton|>
class DeterminationTimeWarner:
"""A Helper to reduce log warnings regarding determination time."""
def __init__(self, repeat_period: int=30):
"""Construct the DeterminationTimeWarner. :param repeat_period: period after which an existing warning condition the warning shall be repeated."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeterminationTimeWarner:
"""A Helper to reduce log warnings regarding determination time."""
def __init__(self, repeat_period: int=30):
"""Construct the DeterminationTimeWarner. :param repeat_period: period after which an existing warning condition the warning shall be repeated."""
self.r... | the_stack_v2_python_sparse | src/sdc11073/mdib/consumermdibxtra.py | deichmab-draeger/sdc11073 | train | 0 |
f6defbd42a86546d088088fc7ebc7498d386340b | [
"try:\n menu = Menu.find_by_id(menu_id)\n if not menu:\n raise MealError.NotFound('Menu does not exist yet! Create one?')\n else:\n meal = Meal.find_by_id(meal_id)\n if not meal:\n raise MealError.NotFound(\"Sorry, Meal does't exist! Create one?\")\n data = Response.define_meal(m... | <|body_start_0|>
try:
menu = Menu.find_by_id(menu_id)
if not menu:
raise MealError.NotFound('Menu does not exist yet! Create one?')
else:
meal = Meal.find_by_id(meal_id)
if not meal:
raise MealError.NotFound("Sorry, ... | Contains GET, PUT and DELETE methods for manipulating a single meal | MealView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MealView:
"""Contains GET, PUT and DELETE methods for manipulating a single meal"""
def get(self, menu_id, meal_id):
"""Endpoint for fetching a particular order."""
<|body_0|>
def put(self, menu_id, meal_id, user_id):
"""Endpoint for updating a particular meal.""... | stack_v2_sparse_classes_36k_train_005695 | 6,144 | no_license | [
{
"docstring": "Endpoint for fetching a particular order.",
"name": "get",
"signature": "def get(self, menu_id, meal_id)"
},
{
"docstring": "Endpoint for updating a particular meal.",
"name": "put",
"signature": "def put(self, menu_id, meal_id, user_id)"
},
{
"docstring": "Endpoi... | 3 | stack_v2_sparse_classes_30k_train_000945 | Implement the Python class `MealView` described below.
Class description:
Contains GET, PUT and DELETE methods for manipulating a single meal
Method signatures and docstrings:
- def get(self, menu_id, meal_id): Endpoint for fetching a particular order.
- def put(self, menu_id, meal_id, user_id): Endpoint for updating... | Implement the Python class `MealView` described below.
Class description:
Contains GET, PUT and DELETE methods for manipulating a single meal
Method signatures and docstrings:
- def get(self, menu_id, meal_id): Endpoint for fetching a particular order.
- def put(self, menu_id, meal_id, user_id): Endpoint for updating... | b98a0fbaa7b881e7f39152cc4f7846cfac3e8029 | <|skeleton|>
class MealView:
"""Contains GET, PUT and DELETE methods for manipulating a single meal"""
def get(self, menu_id, meal_id):
"""Endpoint for fetching a particular order."""
<|body_0|>
def put(self, menu_id, meal_id, user_id):
"""Endpoint for updating a particular meal.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MealView:
"""Contains GET, PUT and DELETE methods for manipulating a single meal"""
def get(self, menu_id, meal_id):
"""Endpoint for fetching a particular order."""
try:
menu = Menu.find_by_id(menu_id)
if not menu:
raise MealError.NotFound('Menu doe... | the_stack_v2_python_sparse | app/api/v2/views/meal.py | mashafrancis/fast-food-fast-api | train | 0 |
9e0e45d46a3d8009059101e433f45d7038fedd31 | [
"modules_data = data[src]\nif self._n_modules == 1:\n return _maybe_squeeze_to_image(modules_data)\nif isinstance(modules_data, np.ndarray):\n return modules_data\nreturn _stack_detector_modules(modules_data, src, modules, pulse_resolved=False)",
"modules_data = data[src]\nif self._n_modules == 1:\n retu... | <|body_start_0|>
modules_data = data[src]
if self._n_modules == 1:
return _maybe_squeeze_to_image(modules_data)
if isinstance(modules_data, np.ndarray):
return modules_data
return _stack_detector_modules(modules_data, src, modules, pulse_resolved=False)
<|end_body... | EPix100ImageAssembler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EPix100ImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. - calibrated, "data.image", (y, x, 1) - raw, "data.image.data", (1, y, x) -> (y, x)"""
<|body_0|>
def _get_modules_file(self, data, src, modules):
"""Override. - calibrated, "data.... | stack_v2_sparse_classes_36k_train_005696 | 23,340 | permissive | [
{
"docstring": "Override. - calibrated, \"data.image\", (y, x, 1) - raw, \"data.image.data\", (1, y, x) -> (y, x)",
"name": "_get_modules_bridge",
"signature": "def _get_modules_bridge(self, data, src, modules)"
},
{
"docstring": "Override. - calibrated, \"data.image.pixels\", (y, x) - raw, \"da... | 2 | stack_v2_sparse_classes_30k_train_020878 | Implement the Python class `EPix100ImageAssembler` described below.
Class description:
Implement the EPix100ImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. - calibrated, "data.image", (y, x, 1) - raw, "data.image.data", (1, y, x) -> (y, x)
- def _... | Implement the Python class `EPix100ImageAssembler` described below.
Class description:
Implement the EPix100ImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. - calibrated, "data.image", (y, x, 1) - raw, "data.image.data", (1, y, x) -> (y, x)
- def _... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class EPix100ImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. - calibrated, "data.image", (y, x, 1) - raw, "data.image.data", (1, y, x) -> (y, x)"""
<|body_0|>
def _get_modules_file(self, data, src, modules):
"""Override. - calibrated, "data.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EPix100ImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. - calibrated, "data.image", (y, x, 1) - raw, "data.image.data", (1, y, x) -> (y, x)"""
modules_data = data[src]
if self._n_modules == 1:
return _maybe_squeeze_to_image(modules_data)
... | the_stack_v2_python_sparse | extra_foam/pipeline/processors/image_assembler.py | European-XFEL/EXtra-foam | train | 8 | |
3e53ebba10be2b2c70c9d2efc190f5cef9dd8aca | [
"mycursor = self.db.connection.cursor()\nsql = 'INSERT INTO Category (name_cat) VALUES (%(cat_name)s)'\nfor category in CATEGORIES:\n mycursor.execute(sql, {'cat_name': category})\nself.db.connection.commit()",
"mycursor = self.db.connection.cursor()\nmycursor.execute('SELECT name_cat FROM Category')\nmyresult... | <|body_start_0|>
mycursor = self.db.connection.cursor()
sql = 'INSERT INTO Category (name_cat) VALUES (%(cat_name)s)'
for category in CATEGORIES:
mycursor.execute(sql, {'cat_name': category})
self.db.connection.commit()
<|end_body_0|>
<|body_start_1|>
mycursor = self... | Manage the categories in the SQL database | CategoryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryManager:
"""Manage the categories in the SQL database"""
def insert_categories(self):
"""Inserts all the categories from the constant.py module into the SQL Category table"""
<|body_0|>
def fetch_all_categories(self):
"""Fetch all the categories from the ... | stack_v2_sparse_classes_36k_train_005697 | 7,181 | no_license | [
{
"docstring": "Inserts all the categories from the constant.py module into the SQL Category table",
"name": "insert_categories",
"signature": "def insert_categories(self)"
},
{
"docstring": "Fetch all the categories from the SQL Category table so that the controllers can call them",
"name":... | 2 | stack_v2_sparse_classes_30k_test_000585 | Implement the Python class `CategoryManager` described below.
Class description:
Manage the categories in the SQL database
Method signatures and docstrings:
- def insert_categories(self): Inserts all the categories from the constant.py module into the SQL Category table
- def fetch_all_categories(self): Fetch all the... | Implement the Python class `CategoryManager` described below.
Class description:
Manage the categories in the SQL database
Method signatures and docstrings:
- def insert_categories(self): Inserts all the categories from the constant.py module into the SQL Category table
- def fetch_all_categories(self): Fetch all the... | 8b1ae1ed03d2274e85b8a38c39ebfcf354857e42 | <|skeleton|>
class CategoryManager:
"""Manage the categories in the SQL database"""
def insert_categories(self):
"""Inserts all the categories from the constant.py module into the SQL Category table"""
<|body_0|>
def fetch_all_categories(self):
"""Fetch all the categories from the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryManager:
"""Manage the categories in the SQL database"""
def insert_categories(self):
"""Inserts all the categories from the constant.py module into the SQL Category table"""
mycursor = self.db.connection.cursor()
sql = 'INSERT INTO Category (name_cat) VALUES (%(cat_name)s... | the_stack_v2_python_sparse | core/managers.py | bientavu/openfoodfacts | train | 0 |
08e7c57db0a98a6429e8857c13300161322df682 | [
"if not info:\n return None\nnamespace = info['namespace']\nif self.type == 'input':\n tag_name = etree.QName(namespace, self.operation.name)\nelse:\n tag_name = etree.QName(namespace, self.abstract.name.localname)\nelements = []\nfor name, msg in parts.items():\n if msg.element:\n elements.appen... | <|body_start_0|>
if not info:
return None
namespace = info['namespace']
if self.type == 'input':
tag_name = etree.QName(namespace, self.operation.name)
else:
tag_name = etree.QName(namespace, self.abstract.name.localname)
elements = []
... | In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the wrapper, represented by an accessor n... | RpcMessage | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcMessage:
"""In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the... | stack_v2_sparse_classes_36k_train_005698 | 19,450 | permissive | [
{
"docstring": "Return an XSD element for the SOAP:Body. Each part is a parameter or a return value and appears inside a wrapper element within the body named identically to the operation name and its namespace is the value of the namespace attribute.",
"name": "_resolve_body",
"signature": "def _resolv... | 2 | stack_v2_sparse_classes_30k_train_011103 | Implement the Python class `RpcMessage` described below.
Class description:
In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each mes... | Implement the Python class `RpcMessage` described below.
Class description:
In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each mes... | 377d9313b1b4807a31a5ee42227f1dc7e7e0471e | <|skeleton|>
class RpcMessage:
"""In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RpcMessage:
"""In RPC messages each part is a parameter or a return value and appears inside a wrapper element within the body. The wrapper element is named identically to the operation name and its namespace is the value of the namespace attribute. Each message part (parameter) appears under the wrapper, rep... | the_stack_v2_python_sparse | src/zeep/wsdl/messages/soap.py | mvantellingen/python-zeep | train | 1,938 |
412234f3cc68d56bb498c294609ed195b1fdab85 | [
"if self.is_db:\n return get_tables(self.db_url)\nreturn []",
"if self.is_db:\n ds = get_table(self.db_url, self.table)\nelse:\n ds = pd.read_csv(self.dataset.file)\nreturn ds.columns.to_list()"
] | <|body_start_0|>
if self.is_db:
return get_tables(self.db_url)
return []
<|end_body_0|>
<|body_start_1|>
if self.is_db:
ds = get_table(self.db_url, self.table)
else:
ds = pd.read_csv(self.dataset.file)
return ds.columns.to_list()
<|end_body_1|... | Scenario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBMS"""
<|body_0|>
def columns(self):
"""Return columns in selected dataset"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.is_db:
return get_tables(self.db_url)
return []
<|... | stack_v2_sparse_classes_36k_train_005699 | 2,759 | permissive | [
{
"docstring": "Return table in DBMS",
"name": "tables",
"signature": "def tables(self)"
},
{
"docstring": "Return columns in selected dataset",
"name": "columns",
"signature": "def columns(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000948 | Implement the Python class `Scenario` described below.
Class description:
Implement the Scenario class.
Method signatures and docstrings:
- def tables(self): Return table in DBMS
- def columns(self): Return columns in selected dataset | Implement the Python class `Scenario` described below.
Class description:
Implement the Scenario class.
Method signatures and docstrings:
- def tables(self): Return table in DBMS
- def columns(self): Return columns in selected dataset
<|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBM... | 4299f09a338209fb6f03cc7c0806f8cc01447fe0 | <|skeleton|>
class Scenario:
def tables(self):
"""Return table in DBMS"""
<|body_0|>
def columns(self):
"""Return columns in selected dataset"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scenario:
def tables(self):
"""Return table in DBMS"""
if self.is_db:
return get_tables(self.db_url)
return []
def columns(self):
"""Return columns in selected dataset"""
if self.is_db:
ds = get_table(self.db_url, self.table)
else:
... | the_stack_v2_python_sparse | msp/models.py | softlab-unimore/MASQ | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.