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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9214029d439a4adbb3ccc25e22d7118d47dcdc5 | [
"Dialog.__init__(self, text, screen, False)\nself.choices = [str(choice) for choice in choices]\nself.scriptEngine = script_engine.ScriptEngine()\nmaxWidth = max(list(map(self.font.calcWidth, self.choices)))\nsize = (maxWidth + self.xBorder * 2 + self.sideCursor.get_width(), (self.font.height + LINEBUFFER) * len(se... | <|body_start_0|>
Dialog.__init__(self, text, screen, False)
self.choices = [str(choice) for choice in choices]
self.scriptEngine = script_engine.ScriptEngine()
maxWidth = max(list(map(self.font.calcWidth, self.choices)))
size = (maxWidth + self.xBorder * 2 + self.sideCursor.get_w... | Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable. | ChoiceDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font ... | stack_v2_sparse_classes_36k_train_000700 | 7,179 | no_license | [
{
"docstring": "Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font with which to write the text. screen - the surface to draw the dialog onto. scriptEngine - the engine to return the option chosen to. choices - the possible options to choose from... | 3 | stack_v2_sparse_classes_30k_train_008063 | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, screen, choices): Initialize the dialog and create the choice box. text - a li... | Implement the Python class `ChoiceDialog` described below.
Class description:
Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable.
Method signatures and docstrings:
- def __init__(self, text, screen, choices): Initialize the dialog and create the choice box. text - a li... | 72841fc503c716ac3b524e42f2311cbd9d18a092 | <|skeleton|>
class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChoiceDialog:
"""Adds a choice box to a dialog. Returns the choice selected to the LASTRESULT script engine variable."""
def __init__(self, text, screen, choices):
"""Initialize the dialog and create the choice box. text - a list of lines of text to go in the dialog. font - the font with which to... | the_stack_v2_python_sparse | eng/dialog.py | andrew-turner/Ditto | train | 0 |
e545309e47a2d3d4c3091f57d19a300a4f5dd68f | [
"super().__init__(discriminator.config)\nself.generator = generator\nself.discriminator = discriminator\nself.tokenizer = tokenizer\nself.weight = weight\nif self.generator.config.model_type == self.discriminator.config.model_type:\n self.discriminator.set_input_embeddings(self.generator.get_input_embeddings())\... | <|body_start_0|>
super().__init__(discriminator.config)
self.generator = generator
self.discriminator = discriminator
self.tokenizer = tokenizer
self.weight = weight
if self.generator.config.model_type == self.discriminator.config.model_type:
self.discriminato... | Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are incorrect. More on this training objective can be found in the ELECTRA paper. | TokenDetection | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenDetection:
"""Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are incorrect. More on this training objective... | stack_v2_sparse_classes_36k_train_000701 | 4,659 | permissive | [
{
"docstring": "Creates a new TokenDetection class. Args: generator: Generator model, must be a masked language model discriminator: Discriminator model, must be a model that can detect replaced tokens. Any model can can be customized for this task. See ElectraForPretraining for more.",
"name": "__init__",
... | 3 | null | Implement the Python class `TokenDetection` described below.
Class description:
Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are inc... | Implement the Python class `TokenDetection` described below.
Class description:
Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are inc... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class TokenDetection:
"""Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are incorrect. More on this training objective... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenDetection:
"""Runs the replaced token detection training objective. This method was first proposed by the ELECTRA model. The method consists of a masked language model generator feeding data to a discriminator that determines which of the tokens are incorrect. More on this training objective can be found... | the_stack_v2_python_sparse | src/python/txtai/models/tokendetection.py | neuml/txtai | train | 4,804 |
213d40a0ee761a9adba16e95b30d63937da0cc0d | [
"try:\n return blob_api.get_by_id(pk, request.user)\nexcept exceptions.DoesNotExist:\n raise Http404",
"try:\n blob_object = self.get_object(request, pk)\n return get_file_http_response(blob_object.blob, blob_object.filename)\nexcept AccessControlError as e:\n content = {'message': str(e)}\n ret... | <|body_start_0|>
try:
return blob_api.get_by_id(pk, request.user)
except exceptions.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
try:
blob_object = self.get_object(request, pk)
return get_file_http_response(blob_object.blob, blob_ob... | Download Blob | BlobDownload | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlobDownload:
"""Download Blob"""
def get_object(self, request, pk):
"""Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob"""
<|body_0|>
def get(self, request, pk):
"""Download the Blob file Args: request: HTTP request pk: ObjectId Returns: -... | stack_v2_sparse_classes_36k_train_000702 | 11,564 | permissive | [
{
"docstring": "Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob",
"name": "get_object",
"signature": "def get_object(self, request, pk)"
},
{
"docstring": "Download the Blob file Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: Blob file - code: 403 ... | 2 | stack_v2_sparse_classes_30k_train_004153 | Implement the Python class `BlobDownload` described below.
Class description:
Download Blob
Method signatures and docstrings:
- def get_object(self, request, pk): Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob
- def get(self, request, pk): Download the Blob file Args: request: HTTP request pk... | Implement the Python class `BlobDownload` described below.
Class description:
Download Blob
Method signatures and docstrings:
- def get_object(self, request, pk): Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob
- def get(self, request, pk): Download the Blob file Args: request: HTTP request pk... | 568cb75a40ccff1d74a1a757866112535efd769a | <|skeleton|>
class BlobDownload:
"""Download Blob"""
def get_object(self, request, pk):
"""Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob"""
<|body_0|>
def get(self, request, pk):
"""Download the Blob file Args: request: HTTP request pk: ObjectId Returns: -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlobDownload:
"""Download Blob"""
def get_object(self, request, pk):
"""Get Blob from db Args: request: HTTP request pk: ObjectId Returns: Blob"""
try:
return blob_api.get_by_id(pk, request.user)
except exceptions.DoesNotExist:
raise Http404
def get(se... | the_stack_v2_python_sparse | core_main_app/rest/blob/views.py | adilmania/core_main_app | train | 0 |
ecfa48899df6ed01dd23b357346161becb632582 | [
"from .. import command\ncmd = command.ZCLCommand()\ncmd.one_byte = value\nreturn cmd",
"from .. import command\ncmd = command.ZCLCommand()\ncmd.low_byte = value & 255\ncmd.high_byte = value >> 8 & 255\nreturn cmd"
] | <|body_start_0|>
from .. import command
cmd = command.ZCLCommand()
cmd.one_byte = value
return cmd
<|end_body_0|>
<|body_start_1|>
from .. import command
cmd = command.ZCLCommand()
cmd.low_byte = value & 255
cmd.high_byte = value >> 8 & 255
return... | Command generator base class | CommandGen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
<|body_0|>
def two_byte(self, value):
"""Two byte command"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from .. import command
cmd = comma... | stack_v2_sparse_classes_36k_train_000703 | 9,321 | no_license | [
{
"docstring": "One byte command",
"name": "one_byte",
"signature": "def one_byte(self, value)"
},
{
"docstring": "Two byte command",
"name": "two_byte",
"signature": "def two_byte(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000160 | Implement the Python class `CommandGen` described below.
Class description:
Command generator base class
Method signatures and docstrings:
- def one_byte(self, value): One byte command
- def two_byte(self, value): Two byte command | Implement the Python class `CommandGen` described below.
Class description:
Command generator base class
Method signatures and docstrings:
- def one_byte(self, value): One byte command
- def two_byte(self, value): Two byte command
<|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byt... | fff610a7d045a9611f07e7c46888b4fab5bca1f5 | <|skeleton|>
class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
<|body_0|>
def two_byte(self, value):
"""Two byte command"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandGen:
"""Command generator base class"""
def one_byte(self, value):
"""One byte command"""
from .. import command
cmd = command.ZCLCommand()
cmd.one_byte = value
return cmd
def two_byte(self, value):
"""Two byte command"""
from .. import ... | the_stack_v2_python_sparse | sf/protocol/zigbee/zcl/base.py | stevenylai/pysf | train | 0 |
f9602a8538972ace1e62716b535587ec60962ff6 | [
"super(CNN, self).__init__()\nself.conv1 = nn.Conv2d(3, 32, 3, 1)\nself.conv2 = nn.Conv2d(32, 64, 3, 1)\nself.dropout1 = nn.Dropout2d(0.25)\nself.dropout2 = nn.Dropout2d(0.5)\nself.fc1 = nn.Linear(12544, 128)\nself.fc2 = nn.Linear(128, y_dim)",
"x = F.relu(self.conv1(x))\nx = F.relu(self.conv2(x))\nx = F.max_pool... | <|body_start_0|>
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(12544, 128)
self.fc2 = nn.Linear(128, y_dim)
<|end_body_... | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
<|body_0|>
def forward(self, x):
"""Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probabi... | stack_v2_sparse_classes_36k_train_000704 | 2,997 | no_license | [
{
"docstring": "Initialize classifier Inputs: - y_dim : number of classes",
"name": "__init__",
"signature": "def __init__(self, y_dim)"
},
{
"docstring": "Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probability ... | 2 | stack_v2_sparse_classes_30k_train_008445 | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, y_dim): Initialize classifier Inputs: - y_dim : number of classes
- def forward(self, x): Perform classification using the CNN classifier Inputs: - x : input data sample... | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, y_dim): Initialize classifier Inputs: - y_dim : number of classes
- def forward(self, x): Perform classification using the CNN classifier Inputs: - x : input data sample... | 4df31e1670cf56331af7eb3524505d83c2dc98c7 | <|skeleton|>
class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
<|body_0|>
def forward(self, x):
"""Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probabi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0... | the_stack_v2_python_sparse | src/model/classifier.py | nick11roberts/manifold-autoencoder-extended | train | 0 | |
812697aa157f025b26d1fce46c5c905e33c886e3 | [
"super(Data, self).__init__(xmi_dir, tokenizer, max_input_length, max_output_length, n_files)\nself.partition = partition\nself.extract_events_and_times()",
"caption = 'event/time %s data' % self.partition\nfor xmi_path in tqdm(self.xmi_paths, desc=caption):\n xmi_file_name = xmi_path.split('/')[-1]\n id = ... | <|body_start_0|>
super(Data, self).__init__(xmi_dir, tokenizer, max_input_length, max_output_length, n_files)
self.partition = partition
self.extract_events_and_times()
<|end_body_0|>
<|body_start_1|>
caption = 'event/time %s data' % self.partition
for xmi_path in tqdm(self.xmi_... | Thyme data | Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""Thyme data"""
def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all'):
"""Thyme data"""
<|body_0|>
def extract_events_and_times(self):
"""Extract events and times"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_000705 | 3,084 | no_license | [
{
"docstring": "Thyme data",
"name": "__init__",
"signature": "def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all')"
},
{
"docstring": "Extract events and times",
"name": "extract_events_and_times",
"signature": "def extract_events_and_tim... | 2 | stack_v2_sparse_classes_30k_train_014295 | Implement the Python class `Data` described below.
Class description:
Thyme data
Method signatures and docstrings:
- def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all'): Thyme data
- def extract_events_and_times(self): Extract events and times | Implement the Python class `Data` described below.
Class description:
Thyme data
Method signatures and docstrings:
- def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all'): Thyme data
- def extract_events_and_times(self): Extract events and times
<|skeleton|>
class Data... | 7d44509621dcbd394d503301859002f8da132b5b | <|skeleton|>
class Data:
"""Thyme data"""
def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all'):
"""Thyme data"""
<|body_0|>
def extract_events_and_times(self):
"""Extract events and times"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Data:
"""Thyme data"""
def __init__(self, xmi_dir, tokenizer, max_input_length, max_output_length, partition, n_files='all'):
"""Thyme data"""
super(Data, self).__init__(xmi_dir, tokenizer, max_input_length, max_output_length, n_files)
self.partition = partition
self.extra... | the_stack_v2_python_sparse | Archive/T5/dataset_events.py | dmitriydligach/Thyme | train | 0 |
922e39e75755aeb7f855f2618d22ce33a560477c | [
"res = []\n\ndef helper(node):\n if not node:\n return\n res.append(str(node.val))\n res.append(str(len(node.children)))\n for _ in node.children:\n helper(_)\nhelper(root)\nreturn ','.join(res)",
"if not data:\n return None\n\ndef helper(A):\n val = int(A.popleft())\n size = in... | <|body_start_0|>
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
for _ in node.children:
helper(_)
helper(root)
return ','.join(res)
<|end_body_0|... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_000706 | 1,184 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_test_000633 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
... | the_stack_v2_python_sparse | _0428_Serialize_and_Deserialize_N_ary_Tree.py | mingweihe/leetcode | train | 3 | |
a3a7385e79a5496d92d8fa0b6500965a2dd01f3a | [
"super(My_attention, self).__init__()\nself.encoder_att = nn.Linear(encoder_dim, attention_dim)\nself.decoder_att = nn.Linear(decoder_dim, attention_dim)\nself.full_att = nn.Linear(attention_dim, 1)\nself.relu = nn.ReLU()\nself.softmax = nn.Softmax(dim=1)",
"att1 = self.encoder_att(encoder_out)\natt2 = self.decod... | <|body_start_0|>
super(My_attention, self).__init__()
self.encoder_att = nn.Linear(encoder_dim, attention_dim)
self.decoder_att = nn.Linear(decoder_dim, attention_dim)
self.full_att = nn.Linear(attention_dim, 1)
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1)
<|end... | Attention Network. | My_attention | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class My_attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forwa... | stack_v2_sparse_classes_36k_train_000707 | 30,636 | permissive | [
{
"docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network",
"name": "__init__",
"signature": "def __init__(self, encoder_dim, decoder_dim, attention_dim)"
},
{
"docstring": "Forward propagation... | 2 | stack_v2_sparse_classes_30k_train_005693 | Implement the Python class `My_attention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of t... | Implement the Python class `My_attention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of t... | 54e05d68c66c9cc5b9698e453981c0f1a6b216cf | <|skeleton|>
class My_attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class My_attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
super(My_attention, self).__init__()
... | the_stack_v2_python_sparse | src/model/decoder/decoder_vis_old.py | daniil-777/geneuclidean | train | 0 |
e20f5a7bd4ee82fefbd4779b6ba2a5672746357e | [
"res, curr = (0, 0)\nN = len(heights)\nfor i in range(N):\n mini = heights[i]\n curr = mini * 1\n res = max(res, curr)\n for j in range(i + 1, N):\n mini = min(mini, heights[j])\n curr = mini * (j - i + 1)\n res = max(res, curr)\nreturn res",
"res, curr = (0, 0)\nN = len(heights)\... | <|body_start_0|>
res, curr = (0, 0)
N = len(heights)
for i in range(N):
mini = heights[i]
curr = mini * 1
res = max(res, curr)
for j in range(i + 1, N):
mini = min(mini, heights[j])
curr = mini * (j - i + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
<|body_0|>
def largestRectangleArea2(self, heights: List[int]) -> int:
"""For each ba... | stack_v2_sparse_classes_36k_train_000708 | 2,284 | no_license | [
{
"docstring": "Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights: List[int]) -> int"
},
{
"docstring": "For each bar, expands from left and right to ge... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights: List[int]) -> int: Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.
- def larges... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights: List[int]) -> int: Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.
- def larges... | 9a0e41d2d718803eb297430995e464fcab472a55 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
<|body_0|>
def largestRectangleArea2(self, heights: List[int]) -> int:
"""For each ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
res, curr = (0, 0)
N = len(heights)
for i in range(N):
mini = heights[i]
... | the_stack_v2_python_sparse | leetcode/84.py | evinpinar/competitive_python | train | 0 | |
60be2273fb2a1406ba8a2dc94bc59a4ac63657ed | [
"self.device_name_vec = device_name_vec\nself.max_volume_size_bytes = max_volume_size_bytes\nself.raw_query = raw_query\nself.tag_params_vec = tag_params_vec\nself.volume_id_vec = volume_id_vec\nself.volume_type_vec = volume_type_vec",
"if dictionary is None:\n return None\ndevice_name_vec = dictionary.get('de... | <|body_start_0|>
self.device_name_vec = device_name_vec
self.max_volume_size_bytes = max_volume_size_bytes
self.raw_query = raw_query
self.tag_params_vec = tag_params_vec
self.volume_id_vec = volume_id_vec
self.volume_type_vec = volume_type_vec
<|end_body_0|>
<|body_star... | Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) exclusion criteria. If a criterion is specified at both object-level and job-level, then job-... | EBSVolumeExclusionParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EBSVolumeExclusionParams:
"""Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) exclusion criteria. If a criterion is spe... | stack_v2_sparse_classes_36k_train_000709 | 4,317 | permissive | [
{
"docstring": "Constructor for the EBSVolumeExclusionParams class",
"name": "__init__",
"signature": "def __init__(self, device_name_vec=None, max_volume_size_bytes=None, raw_query=None, tag_params_vec=None, volume_id_vec=None, volume_type_vec=None)"
},
{
"docstring": "Creates an instance of th... | 2 | null | Implement the Python class `EBSVolumeExclusionParams` described below.
Class description:
Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) ex... | Implement the Python class `EBSVolumeExclusionParams` described below.
Class description:
Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) ex... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class EBSVolumeExclusionParams:
"""Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) exclusion criteria. If a criterion is spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EBSVolumeExclusionParams:
"""Implementation of the 'EBSVolumeExclusionParams' model. Message defining the different criteria to exclude EBS volumes from backup. This is used to specify both object-level (BackupSourceParams) and job-level (EnvBackupParams) exclusion criteria. If a criterion is specified at bot... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ebs_volume_exclusion_params.py | cohesity/management-sdk-python | train | 24 |
46334f62e8cc2b9ab509889d70e79c60017a0818 | [
"res = random_log_uniform(1 / s, s, self._size)\nif frac != 1:\n res[np.random.random(self._size) > frac] = 0\nreturn res",
"s, frac = (s[0], frac[0])\nres = np.zeros_like(x)\nidx = (1 < x * s) & (x < s)\nres[idx] = frac / (x[idx] * np.log(s * s))\nreturn res",
"s, frac = (s[0], frac[0])\nres = np.zeros_like... | <|body_start_0|>
res = random_log_uniform(1 / s, s, self._size)
if frac != 1:
res[np.random.random(self._size) > frac] = 0
return res
<|end_body_0|>
<|body_start_1|>
s, frac = (s[0], frac[0])
res = np.zeros_like(x)
idx = (1 < x * s) & (x < s)
res[idx]... | partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero | PartialLogUniformDistribution_gen | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartialLogUniformDistribution_gen:
"""partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero"""
def _rvs(self, s, frac):
"""random variates"""
<|body_0|>
def _pdf(self, x... | stack_v2_sparse_classes_36k_train_000710 | 19,718 | permissive | [
{
"docstring": "random variates",
"name": "_rvs",
"signature": "def _rvs(self, s, frac)"
},
{
"docstring": "probability density function",
"name": "_pdf",
"signature": "def _pdf(self, x, s, frac)"
},
{
"docstring": "cumulative probability function",
"name": "_cdf",
"signa... | 4 | null | Implement the Python class `PartialLogUniformDistribution_gen` described below.
Class description:
partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero
Method signatures and docstrings:
- def _rvs(self, s, frac): ra... | Implement the Python class `PartialLogUniformDistribution_gen` described below.
Class description:
partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero
Method signatures and docstrings:
- def _rvs(self, s, frac): ra... | 2afae32df4fe9609c792a3b608cad79833f4178f | <|skeleton|>
class PartialLogUniformDistribution_gen:
"""partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero"""
def _rvs(self, s, frac):
"""random variates"""
<|body_0|>
def _pdf(self, x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartialLogUniformDistribution_gen:
"""partial log-uniform distribution. a fraction `frac` of the distribution follows a log-uniform distribution, while the remaining fraction `1 - frac` is zero"""
def _rvs(self, s, frac):
"""random variates"""
res = random_log_uniform(1 / s, s, self._size... | the_stack_v2_python_sparse | utils/math/distributions.py | david-zwicker/py-utils | train | 0 |
982de57a1d9a2327f8f2caf5c5383ae05163bdd7 | [
"nlu_namespaces_to_check = [nlu.Spellbook.pretrained_pipe_references, nlu.Spellbook.pretrained_models_references, nlu.Spellbook.pretrained_healthcare_model_references, nlu.Spellbook.licensed_storage_ref_2_nlu_ref, nlu.Spellbook.storage_ref_2_nlu_ref]\nfor dict_ in nlu_namespaces_to_check:\n if lang:\n if ... | <|body_start_0|>
nlu_namespaces_to_check = [nlu.Spellbook.pretrained_pipe_references, nlu.Spellbook.pretrained_models_references, nlu.Spellbook.pretrained_healthcare_model_references, nlu.Spellbook.licensed_storage_ref_2_nlu_ref, nlu.Spellbook.storage_ref_2_nlu_ref]
for dict_ in nlu_namespaces_to_check:... | ModelHubUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelHubUtils:
def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str:
"""Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return. lang : what language is the model in."""
<|body_0|>
def get_url_by_nlu_refrence(nlu_ref... | stack_v2_sparse_classes_36k_train_000711 | 2,567 | permissive | [
{
"docstring": "Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return. lang : what language is the model in.",
"name": "NLU_ref_to_NLP_ref",
"signature": "def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str"
},
{
"docstring": "Rsolves... | 3 | stack_v2_sparse_classes_30k_train_001029 | Implement the Python class `ModelHubUtils` described below.
Class description:
Implement the ModelHubUtils class.
Method signatures and docstrings:
- def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str: Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return... | Implement the Python class `ModelHubUtils` described below.
Class description:
Implement the ModelHubUtils class.
Method signatures and docstrings:
- def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str: Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return... | fd7e73bc3e331b49361fca93cf8d07cccd934adc | <|skeleton|>
class ModelHubUtils:
def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str:
"""Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return. lang : what language is the model in."""
<|body_0|>
def get_url_by_nlu_refrence(nlu_ref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelHubUtils:
def NLU_ref_to_NLP_ref(nlu_ref: str, lang: str=None) -> str:
"""Resolve a Spark NLU reference to a NLP reference. Args : NLU_ref : which nlu model's nlp refrence to return. lang : what language is the model in."""
nlu_namespaces_to_check = [nlu.Spellbook.pretrained_pipe_referenc... | the_stack_v2_python_sparse | nlu/pipe/utils/modelhub_utils.py | prakashcinna/nlu | train | 0 | |
0b55c5d84ee26f11cc18460b2254ad0c99c82f28 | [
"self.request.errors.add('body', 'data', \"Can't update lot for tender stage2\")\nself.request.errors.status = 403\nreturn",
"self.request.errors.add('body', 'data', \"Can't create lot for tender stage2\")\nself.request.errors.status = 403\nreturn",
"self.request.errors.add('body', 'data', \"Can't delete lot fo... | <|body_start_0|>
self.request.errors.add('body', 'data', "Can't update lot for tender stage2")
self.request.errors.status = 403
return
<|end_body_0|>
<|body_start_1|>
self.request.errors.add('body', 'data', "Can't create lot for tender stage2")
self.request.errors.status = 403
... | TenderStage2UALotResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderStage2UALotResource:
def patch(self):
"""Update of lot"""
<|body_0|>
def collection_post(self):
"""Add a lot"""
<|body_1|>
def delete(self):
"""Lot deleting"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.request.erro... | stack_v2_sparse_classes_36k_train_000712 | 2,757 | permissive | [
{
"docstring": "Update of lot",
"name": "patch",
"signature": "def patch(self)"
},
{
"docstring": "Add a lot",
"name": "collection_post",
"signature": "def collection_post(self)"
},
{
"docstring": "Lot deleting",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_017121 | Implement the Python class `TenderStage2UALotResource` described below.
Class description:
Implement the TenderStage2UALotResource class.
Method signatures and docstrings:
- def patch(self): Update of lot
- def collection_post(self): Add a lot
- def delete(self): Lot deleting | Implement the Python class `TenderStage2UALotResource` described below.
Class description:
Implement the TenderStage2UALotResource class.
Method signatures and docstrings:
- def patch(self): Update of lot
- def collection_post(self): Add a lot
- def delete(self): Lot deleting
<|skeleton|>
class TenderStage2UALotReso... | fb955c110ceb40ca7b82b11280602145385a017f | <|skeleton|>
class TenderStage2UALotResource:
def patch(self):
"""Update of lot"""
<|body_0|>
def collection_post(self):
"""Add a lot"""
<|body_1|>
def delete(self):
"""Lot deleting"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenderStage2UALotResource:
def patch(self):
"""Update of lot"""
self.request.errors.add('body', 'data', "Can't update lot for tender stage2")
self.request.errors.status = 403
return
def collection_post(self):
"""Add a lot"""
self.request.errors.add('body', ... | the_stack_v2_python_sparse | openprocurement/tender/competitivedialogue/views/stage2/lot.py | VDigitall/openprocurement.tender.competitivedialogue | train | 0 | |
42992f185c943abe534ab86eb968e04530cb33fc | [
"if not self._unscale:\n raise ResourceValueError('SAM requires unscaled values')\nres_df = pd.DataFrame({'Year': self.time_index.year, 'Month': self.time_index.month, 'Day': self.time_index.day, 'Hour': self.time_index.hour})\nif len(self) > 8784:\n res_df['Minute'] = self.time_index.minute\ntime_zone = self... | <|body_start_0|>
if not self._unscale:
raise ResourceValueError('SAM requires unscaled values')
res_df = pd.DataFrame({'Year': self.time_index.year, 'Month': self.time_index.month, 'Day': self.time_index.day, 'Hour': self.time_index.hour})
if len(self) > 8784:
res_df['Min... | Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class | WaveResource | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaveResource:
"""Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM wave resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract ... | stack_v2_sparse_classes_36k_train_000713 | 43,525 | permissive | [
{
"docstring": "Get SAM wave resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract SAM DataFrame for Returns ------- res_df : pandas.DataFrame time-series DataFrame of resource variables needed to run SAM",
"name": "_get_SAM_df",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_011338 | Implement the Python class `WaveResource` described below.
Class description:
Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _get_SAM_df(self, ds_name, site): Get SAM wave resource DataFrame for given site Parameters ---------- ds_nam... | Implement the Python class `WaveResource` described below.
Class description:
Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _get_SAM_df(self, ds_name, site): Get SAM wave resource DataFrame for given site Parameters ---------- ds_nam... | ca598da8bbcd9983fb1355fe3b67d58273eef5c6 | <|skeleton|>
class WaveResource:
"""Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM wave resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WaveResource:
"""Class to handle Wave Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM wave resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract SAM DataFrame... | the_stack_v2_python_sparse | rex/renewable_resource.py | aidanbharath/rex | train | 0 |
97c8f9bf93a7fb14a83ce34d692cfce38d97cca4 | [
"self.sense_sep = sense_sep\nself.sense_markers = sense_markers\nself.log = log\nself.crossrefs = crossref_markers\nself._idgen = IDGenerator('SN')\nself.senses = sfm.SFM()",
"extracted_markers, rest = split_by_pred(lambda pair: pair[0] in self.sense_markers, entry)\ngroups = list(group_by_separator(self.sense_se... | <|body_start_0|>
self.sense_sep = sense_sep
self.sense_markers = sense_markers
self.log = log
self.crossrefs = crossref_markers
self._idgen = IDGenerator('SN')
self.senses = sfm.SFM()
<|end_body_0|>
<|body_start_1|>
extracted_markers, rest = split_by_pred(lambda ... | Visitor for extracting Sense information from an SFM entry. | SenseExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenseExtractor:
"""Visitor for extracting Sense information from an SFM entry."""
def __init__(self, sense_sep, sense_markers, crossref_markers, log):
"""Create an entry extractor. :arg sense_sep: marker, which separates senses from each other. :arg sense_markers: collection of marke... | stack_v2_sparse_classes_36k_train_000714 | 44,273 | permissive | [
{
"docstring": "Create an entry extractor. :arg sense_sep: marker, which separates senses from each other. :arg sense_markers: collection of markers, which make up a sense. :arg crossref_markers: collection of markers, which refer to other entries",
"name": "__init__",
"signature": "def __init__(self, s... | 2 | stack_v2_sparse_classes_30k_train_019807 | Implement the Python class `SenseExtractor` described below.
Class description:
Visitor for extracting Sense information from an SFM entry.
Method signatures and docstrings:
- def __init__(self, sense_sep, sense_markers, crossref_markers, log): Create an entry extractor. :arg sense_sep: marker, which separates senses... | Implement the Python class `SenseExtractor` described below.
Class description:
Visitor for extracting Sense information from an SFM entry.
Method signatures and docstrings:
- def __init__(self, sense_sep, sense_markers, crossref_markers, log): Create an entry extractor. :arg sense_sep: marker, which separates senses... | 9fcb35608ab7ce0df3f02a88aba893ce3920e48a | <|skeleton|>
class SenseExtractor:
"""Visitor for extracting Sense information from an SFM entry."""
def __init__(self, sense_sep, sense_markers, crossref_markers, log):
"""Create an entry extractor. :arg sense_sep: marker, which separates senses from each other. :arg sense_markers: collection of marke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SenseExtractor:
"""Visitor for extracting Sense information from an SFM entry."""
def __init__(self, sense_sep, sense_markers, crossref_markers, log):
"""Create an entry extractor. :arg sense_sep: marker, which separates senses from each other. :arg sense_markers: collection of markers, which mak... | the_stack_v2_python_sparse | src/pydictionaria/sfm2cldf.py | dictionaria/pydictionaria | train | 1 |
921a411be5997ace8ca5e5bb595b6eea2e472d54 | [
"if n <= 2:\n return 0\na = self.create_candidates(n)\nm = int(n ** 0.5) + 1\nfor i in range(3, m):\n if a[i] == 1:\n j = 2\n while i * j < n:\n a[i * j] = 0\n j += 1\nreturn sum(a)",
"a = [1 if i > 1 and i % 2 == 1 else 0 for i in range(n)]\na[2] = 1\nreturn a"
] | <|body_start_0|>
if n <= 2:
return 0
a = self.create_candidates(n)
m = int(n ** 0.5) + 1
for i in range(3, m):
if a[i] == 1:
j = 2
while i * j < n:
a[i * j] = 0
j += 1
return sum(a)
<|... | Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n"""
def count_primes(self, n):
"""Determines number of prime integ... | stack_v2_sparse_classes_36k_train_000715 | 2,714 | permissive | [
{
"docstring": "Determines number of prime integers below input value. Using the \"Sieve of Eratosthenes\" Algorithm, all integers which are multiples of primes are excluded as candidates in subsequent evaluations. :param int n: maximum value for prime range (exclusive) :return: number of prime integers below i... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n
Method signatures and docstrings:
- de... | Implement the Python class `Solution` described below.
Class description:
Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n
Method signatures and docstrings:
- de... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n"""
def count_primes(self, n):
"""Determines number of prime integ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Traverse array using the "Sieve of Eratosthenes" Algorithm. Time complexity: O(n * log(log(n))) - Iterate all integers up to n ** 0.5 and multiples below n Space complexity: O(n) - Requires array of size n"""
def count_primes(self, n):
"""Determines number of prime integers below inp... | the_stack_v2_python_sparse | 0204_count_primes/python_source.py | arthurdysart/LeetCode | train | 0 |
fc8b4ccd477953ab1a3f95df69d7e4f2c520cddc | [
"if n_features <= 0:\n raise ValueError('The number of features must be positive')\nif depth <= 0:\n raise ValueError('The region graph depth must be positive')\nif depth > int(np.log2(n_features)):\n raise ValueError('Invalid region graph depth based on the number of features')\nself.items = tuple(range(n... | <|body_start_0|>
if n_features <= 0:
raise ValueError('The number of features must be positive')
if depth <= 0:
raise ValueError('The region graph depth must be positive')
if depth > int(np.log2(n_features)):
raise ValueError('Invalid region graph depth based ... | RegionGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represent... | stack_v2_sparse_classes_36k_train_000716 | 4,391 | permissive | [
{
"docstring": "Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represented as sorted tuples with unique entries. A *partition* P of a region R is defined as a collection of non-empty sets... | 3 | stack_v2_sparse_classes_30k_train_011650 | Implement the Python class `RegionGraph` described below.
Class description:
Implement the RegionGraph class.
Method signatures and docstrings:
- def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None): Initialize a region graph. A region graph is defined w.r.t. a set of indices of r... | Implement the Python class `RegionGraph` described below.
Class description:
Implement the RegionGraph class.
Method signatures and docstrings:
- def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None): Initialize a region graph. A region graph is defined w.r.t. a set of indices of r... | 76094fb627e97867542ba2be1292a070028dbfdd | <|skeleton|>
class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represented as sorted t... | the_stack_v2_python_sparse | deeprob/utils/region.py | deeprob-org/deeprob-kit | train | 66 | |
bf7ff66f19ceb5f06261e90ba6cc9bcd31e7a87f | [
"s_len, p_len = (len(string), len(pattern))\ns_idx = p_idx = 0\nstar_idx = s_temp_idx = -1\nwhile s_idx < s_len:\n if pattern[p_idx] in [string[s_idx], '?']:\n s_idx += 1\n p_idx += 1\n elif p_idx < p_len and pattern[p_idx] == '*':\n star_idx = p_idx\n s_temp_idx = s_idx\n p... | <|body_start_0|>
s_len, p_len = (len(string), len(pattern))
s_idx = p_idx = 0
star_idx = s_temp_idx = -1
while s_idx < s_len:
if pattern[p_idx] in [string[s_idx], '?']:
s_idx += 1
p_idx += 1
elif p_idx < p_len and pattern[p_idx] == ... | WildCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WildCard:
def is_match(self, string: str, pattern: str) -> bool:
"""Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:"""
<|body_0|>
def is_match_(self, string: str, pattern: str) -> bool:
"""Approach: Dynami... | stack_v2_sparse_classes_36k_train_000717 | 2,690 | no_license | [
{
"docstring": "Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:",
"name": "is_match",
"signature": "def is_match(self, string: str, pattern: str) -> bool"
},
{
"docstring": "Approach: Dynamic Programming Time Complexity: O(SP) Space C... | 2 | null | Implement the Python class `WildCard` described below.
Class description:
Implement the WildCard class.
Method signatures and docstrings:
- def is_match(self, string: str, pattern: str) -> bool: Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:
- def is_matc... | Implement the Python class `WildCard` described below.
Class description:
Implement the WildCard class.
Method signatures and docstrings:
- def is_match(self, string: str, pattern: str) -> bool: Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:
- def is_matc... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class WildCard:
def is_match(self, string: str, pattern: str) -> bool:
"""Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:"""
<|body_0|>
def is_match_(self, string: str, pattern: str) -> bool:
"""Approach: Dynami... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WildCard:
def is_match(self, string: str, pattern: str) -> bool:
"""Approach: Back Tracking Time Complexity: O(SP) Space Complexity: O(1) :param string: :param pattern: :return:"""
s_len, p_len = (len(string), len(pattern))
s_idx = p_idx = 0
star_idx = s_temp_idx = -1
w... | the_stack_v2_python_sparse | revisited/math_and_strings/strings/wildcard_matching.py | Shiv2157k/leet_code | train | 1 | |
acff81cdceda08001ed3a9e3bfb77a02379b3a0f | [
"self.tweetSeq = 0\nself.tweets = {}\nself.follows = {}",
"if userId not in self.tweets:\n self.tweets[userId] = []\nself.tweets[userId].append((self.tweetSeq, tweetId))\nself.tweetSeq += 1",
"searchUserIds = set([userId])\nif userId in self.follows:\n searchUserIds |= self.follows[userId]\nallFollowedTwe... | <|body_start_0|>
self.tweetSeq = 0
self.tweets = {}
self.follows = {}
<|end_body_0|>
<|body_start_1|>
if userId not in self.tweets:
self.tweets[userId] = []
self.tweets[userId].append((self.tweetSeq, tweetId))
self.tweetSeq += 1
<|end_body_1|>
<|body_start_2... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k_train_000718 | 2,333 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: void",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | fbd42d8c0cc142aa56531b4fe127bf4bc2996abd | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.tweetSeq = 0
self.tweets = {}
self.follows = {}
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
if userId not in ... | the_stack_v2_python_sparse | 355-design-twitter/john/solution.py | dennis2030/leetcodeStudyGroup | train | 6 | |
eee5b0b3595809d6df59ab3cdd9733465b3dd466 | [
"i = 0\nn = len(lists)\nwhile i < n:\n if lists[i] is None:\n del lists[i]\n n = len(lists)\n else:\n i += 1\ncur_l = sorted(lists, key=lambda i: i.val)\nif len(lists) == 0:\n return None\nhead = cur_l[0]\np = head\nif cur_l[0].next is not None:\n cur_l[0] = cur_l[0].next\nelse:\n ... | <|body_start_0|>
i = 0
n = len(lists)
while i < n:
if lists[i] is None:
del lists[i]
n = len(lists)
else:
i += 1
cur_l = sorted(lists, key=lambda i: i.val)
if len(lists) == 0:
return None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def sort_l(self, cur_l):
"""cur_l is a list and the first node is with the minimum value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
... | stack_v2_sparse_classes_36k_train_000719 | 1,726 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": "cur_l is a list and the first node is with the minimum value",
"name": "sort_l",
"signature": "def sort_l(self, cur_l)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def sort_l(self, cur_l): cur_l is a list and the first node is with the minimum value | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def sort_l(self, cur_l): cur_l is a list and the first node is with the minimum value
<|skeleton|>
c... | 112e9b0e2a44efc6c56d4b97976efb95b2d929b6 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def sort_l(self, cur_l):
"""cur_l is a list and the first node is with the minimum value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
i = 0
n = len(lists)
while i < n:
if lists[i] is None:
del lists[i]
n = len(lists)
else:
i += 1
cur_l = sor... | the_stack_v2_python_sparse | Merge k Sorted Lists_v2.py | MasKong/Algorithms | train | 0 | |
ee7b959f12a81d2d981a9ebf5c2fdb4cef154f76 | [
"super(InfoGAN_Generator, self).__init__()\nself.n_layer = n_layer\nself.n_conti = n_conti\nself.n_discrete = n_discrete\nself.num_category = num_category\nn_input = noise_dim + n_conti + n_discrete * num_category\nself.featmap_dim = featmap_dim\nself.fc_in = nn.Linear(n_input, featmap_dim * 4 * 4)\nconvs = []\nBNs... | <|body_start_0|>
super(InfoGAN_Generator, self).__init__()
self.n_layer = n_layer
self.n_conti = n_conti
self.n_discrete = n_discrete
self.num_category = num_category
n_input = noise_dim + n_conti + n_discrete * num_category
self.featmap_dim = featmap_dim
... | InfoGAN_Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoGAN_Generator:
def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN."""
<|body_0|>
def f... | stack_v2_sparse_classes_36k_train_000720 | 19,546 | no_license | [
{
"docstring": "InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN.",
"name": "__init__",
"signature": "def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_016242 | Implement the Python class `InfoGAN_Generator` described below.
Class description:
Implement the InfoGAN_Generator class.
Method signatures and docstrings:
- def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Generator, have an a... | Implement the Python class `InfoGAN_Generator` described below.
Class description:
Implement the InfoGAN_Generator class.
Method signatures and docstrings:
- def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Generator, have an a... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class InfoGAN_Generator:
def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN."""
<|body_0|>
def f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfoGAN_Generator:
def __init__(self, noise_dim=10, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Generator, have an additional input branch for latent codes. Architecture brought from DCGAN."""
super(InfoGAN_Generator, self).__in... | the_stack_v2_python_sparse | generated/test_AaronYALai_Generative_Adversarial_Networks_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 | |
6c8eab7ac2d0dbdb7bd59c68071698a4a0b00c27 | [
"sums = [0] * (len(nums) + 1)\nfor i in range(len(nums)):\n sums[i + 1] = nums[i] + sums[i]\nres = 0\nfor i in range(1, len(nums) + 1):\n for j in range(i):\n if sums[i] - sums[j] == k:\n res += 1\nreturn res",
"pre_sum_freq = dict()\npre_sum_freq[0] = 1\npre_sum = 0\ncount = 0\nfor num in... | <|body_start_0|>
sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
sums[i + 1] = nums[i] + sums[i]
res = 0
for i in range(1, len(nums) + 1):
for j in range(i):
if sums[i] - sums[j] == k:
res += 1
return res
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
<|body_0|>
def subarraySum1(self, nums: List[int], k: int) -> int:
"""使用字典优化前缀和 :param nums: :param k: :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_000721 | 1,228 | no_license | [
{
"docstring": "前缀和,数组长度20000 :param nums: :param k: :return:",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: List[int], k: int) -> int"
},
{
"docstring": "使用字典优化前缀和 :param nums: :param k: :return:",
"name": "subarraySum1",
"signature": "def subarraySum1(self, nums: Li... | 2 | stack_v2_sparse_classes_30k_train_002991 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 前缀和,数组长度20000 :param nums: :param k: :return:
- def subarraySum1(self, nums: List[int], k: int) -> int: 使用字典优化前缀和 :param nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 前缀和,数组长度20000 :param nums: :param k: :return:
- def subarraySum1(self, nums: List[int], k: int) -> int: 使用字典优化前缀和 :param nu... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
<|body_0|>
def subarraySum1(self, nums: List[int], k: int) -> int:
"""使用字典优化前缀和 :param nums: :param k: :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""前缀和,数组长度20000 :param nums: :param k: :return:"""
sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
sums[i + 1] = nums[i] + sums[i]
res = 0
for i in range(1, len(nums) + 1):
... | the_stack_v2_python_sparse | datastructure/binary_array/SubarraySum.py | yinhuax/leet_code | train | 0 | |
8f9b24eec01e3b2bedc2d29dec72bb56a49ab782 | [
"self.entity_description = description\nself._build = None\nself._data = data\nself._repo_name = repo_name\nself._user = user\nself._branch = branch\nself._attr_name = f'{repo_name} {description.name}'",
"attrs = {}\nif self._build and self._attr_native_value is not None:\n if self._user and self.entity_descri... | <|body_start_0|>
self.entity_description = description
self._build = None
self._data = data
self._repo_name = repo_name
self._user = user
self._branch = branch
self._attr_name = f'{repo_name} {description.name}'
<|end_body_0|>
<|body_start_1|>
attrs = {}
... | Representation of a Travis CI sensor. | TravisCISensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TravisCISensor:
"""Representation of a Travis CI sensor."""
def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def extra_state_attributes(self):
"""Return the state attributes."... | stack_v2_sparse_classes_36k_train_000722 | 5,862 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None"
},
{
"docstring": "Return the state attributes.",
"name": "extra_state_attributes",
"signature": "def extra_state_at... | 3 | stack_v2_sparse_classes_30k_train_018879 | Implement the Python class `TravisCISensor` described below.
Class description:
Representation of a Travis CI sensor.
Method signatures and docstrings:
- def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: Initialize the sensor.
- def extra_state_attributes(self): Return t... | Implement the Python class `TravisCISensor` described below.
Class description:
Representation of a Travis CI sensor.
Method signatures and docstrings:
- def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None: Initialize the sensor.
- def extra_state_attributes(self): Return t... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TravisCISensor:
"""Representation of a Travis CI sensor."""
def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def extra_state_attributes(self):
"""Return the state attributes."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TravisCISensor:
"""Representation of a Travis CI sensor."""
def __init__(self, data, repo_name, user, branch, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
self.entity_description = description
self._build = None
self._data = data
self... | the_stack_v2_python_sparse | homeassistant/components/travisci/sensor.py | home-assistant/core | train | 35,501 |
ebf76420f3873e687371e29f074708814bb132ff | [
"option_view = '\\n 1. 列出所有学生\\n 2. 查询\\n '\nprint('学生信息系统'.center(cls.width, '='))\nprint(option_view)\nnumber = input('请选择(Ctrl + c 退出):')\nfunc_dict = {'1': cls.list_student, '2': cls.search}\nif number not in func_dict.keys():\n raise Exception('【提示】:输入有误, 请重新选择')\nfunc = func_dict[numbe... | <|body_start_0|>
option_view = '\n 1. 列出所有学生\n 2. 查询\n '
print('学生信息系统'.center(cls.width, '='))
print(option_view)
number = input('请选择(Ctrl + c 退出):')
func_dict = {'1': cls.list_student, '2': cls.search}
if number not in func_dict.keys():
... | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
def menu(cls):
"""主菜单"""
<|body_0|>
def list_student(cls):
"""列出所有学生"""
<|body_1|>
def search(cls):
"""查询"""
<|body_2|>
def search_student(cls):
"""查询学生信息"""
<|body_3|>
def search_score(cls):
"""查询成... | stack_v2_sparse_classes_36k_train_000723 | 3,327 | no_license | [
{
"docstring": "主菜单",
"name": "menu",
"signature": "def menu(cls)"
},
{
"docstring": "列出所有学生",
"name": "list_student",
"signature": "def list_student(cls)"
},
{
"docstring": "查询",
"name": "search",
"signature": "def search(cls)"
},
{
"docstring": "查询学生信息",
"na... | 5 | stack_v2_sparse_classes_30k_val_000994 | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def menu(cls): 主菜单
- def list_student(cls): 列出所有学生
- def search(cls): 查询
- def search_student(cls): 查询学生信息
- def search_score(cls): 查询成绩 | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def menu(cls): 主菜单
- def list_student(cls): 列出所有学生
- def search(cls): 查询
- def search_student(cls): 查询学生信息
- def search_score(cls): 查询成绩
<|skeleton|>
class View:
def menu(cls):
... | b7f29743883739e3b298d49a170f367944ee0d9a | <|skeleton|>
class View:
def menu(cls):
"""主菜单"""
<|body_0|>
def list_student(cls):
"""列出所有学生"""
<|body_1|>
def search(cls):
"""查询"""
<|body_2|>
def search_student(cls):
"""查询学生信息"""
<|body_3|>
def search_score(cls):
"""查询成... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
def menu(cls):
"""主菜单"""
option_view = '\n 1. 列出所有学生\n 2. 查询\n '
print('学生信息系统'.center(cls.width, '='))
print(option_view)
number = input('请选择(Ctrl + c 退出):')
func_dict = {'1': cls.list_student, '2': cls.search}
if number not i... | the_stack_v2_python_sparse | 16-17/01_界面/src/view.py | ucookie/basic-python | train | 0 | |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"super(Exponential, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)\nlogger.debug('Initializing %s kernel.' % self.name)\nself.variance = np.float64(variance)\nself.lengthscale = np.float64(lengthscale)\nself.parameter_list = ['variance', 'lengthscale']\nself.constraint_map = {'variance': '+ve', '... | <|body_start_0|>
super(Exponential, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)
logger.debug('Initializing %s kernel.' % self.name)
self.variance = np.float64(variance)
self.lengthscale = np.float64(lengthscale)
self.parameter_list = ['variance', 'lengthscal... | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be spe... | stack_v2_sparse_classes_36k_train_000724 | 9,047 | no_license | [
{
"docstring": "squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified",
"name": "__init__",
"signature": "def __init__(self, n_dims, variance=1.0, lengthscale=1.0, act... | 2 | stack_v2_sparse_classes_30k_train_005228 | Implement the Python class `Exponential` described below.
Class description:
Implement the Exponential class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel v... | Implement the Python class `Exponential` described below.
Class description:
Implement the Exponential class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel v... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Exponential:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified"""
... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 | |
c05882a28031ccf5fc36bd308f02b7355d765e1f | [
"method_map = kwargs['method_map'] if kwargs.get('method_map', None) else self.method_map\nfor request_method, mapped_method in method_map.items():\n mapped_method = getattr(self, mapped_method)\n method_proxy = self.view_proxy(mapped_method)\n setattr(self, request_method, method_proxy)\nsuper(APIMethodMa... | <|body_start_0|>
method_map = kwargs['method_map'] if kwargs.get('method_map', None) else self.method_map
for request_method, mapped_method in method_map.items():
mapped_method = getattr(self, mapped_method)
method_proxy = self.view_proxy(mapped_method)
setattr(self, ... | map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'} | APIMethodMapMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIMethodMapMixin:
"""map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""map request method. search for method_map args. expected dict. find corresponding value. if method_map... | stack_v2_sparse_classes_36k_train_000725 | 7,548 | no_license | [
{
"docstring": "map request method. search for method_map args. expected dict. find corresponding value. if method_map is passed in,then refer to pass-in method_map :param args: position args :param kwargs: keyword args",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_008913 | Implement the Python class `APIMethodMapMixin` described below.
Class description:
map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'}
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): map request method. search for method_map arg... | Implement the Python class `APIMethodMapMixin` described below.
Class description:
map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'}
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): map request method. search for method_map arg... | 86bc4d3466d648caa93f8591619b5ca3b06a6470 | <|skeleton|>
class APIMethodMapMixin:
"""map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""map request method. search for method_map args. expected dict. find corresponding value. if method_map... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIMethodMapMixin:
"""map request method to Mixin method :method_map: dict, if we map GET to list mixin,then dict should be {'get':'list'}"""
def __init__(self, *args, **kwargs):
"""map request method. search for method_map args. expected dict. find corresponding value. if method_map is passed in... | the_stack_v2_python_sparse | Python/04_Restful/online_intepreter_project/online_intepreter_app/mixins.py | xiaolongjia/techTrees | train | 0 |
c0c6aea8e298c52e99e367bcb4a56fb04d49abbc | [
"super().__init__(task_params, num_shards)\nloss_fn_name = self.task_params.get('main_loss', None)\nif loss_fn_name is None:\n if self.dataset.meta_data['num_classes'] == 1:\n loss_fn_name = 'sigmoid_cross_entropy'\n else:\n loss_fn_name = 'categorical_cross_entropy'\nself.main_loss_fn = functoo... | <|body_start_0|>
super().__init__(task_params, num_shards)
loss_fn_name = self.task_params.get('main_loss', None)
if loss_fn_name is None:
if self.dataset.meta_data['num_classes'] == 1:
loss_fn_name = 'sigmoid_cross_entropy'
else:
loss_fn_n... | Classification Task. | ClassificationTask | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationTask:
"""Classification Task."""
def __init__(self, task_params, num_shards):
"""Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000726 | 44,080 | permissive | [
{
"docstring": "Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over.",
"name": "__init__",
"signature": "def __init__(self, task_params, num_shards)"
},
{
"docstring": "Calculates met... | 3 | null | Implement the Python class `ClassificationTask` described below.
Class description:
Classification Task.
Method signatures and docstrings:
- def __init__(self, task_params, num_shards): Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of devi... | Implement the Python class `ClassificationTask` described below.
Class description:
Classification Task.
Method signatures and docstrings:
- def __init__(self, task_params, num_shards): Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of devi... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ClassificationTask:
"""Classification Task."""
def __init__(self, task_params, num_shards):
"""Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationTask:
"""Classification Task."""
def __init__(self, task_params, num_shards):
"""Initializing Classification based Tasks. Args: task_params: configdict; Hyperparameters of the task. num_shards: int; Number of deviced that we shard the batch over."""
super().__init__(task_par... | the_stack_v2_python_sparse | gift/tasks/task.py | Jimmy-INL/google-research | train | 1 |
d84ce34fc4ed8980cc7b87a706a70a282e8e6c0c | [
"self.imgpathfile = imgpathfile\nself.labelpath = labelpath\nself.imgsize = size\nassert os.path.exists(self.imgpathfile), 'File {} does not exist'.format(self.imgpathfile)\nself.dataloaders = self.get_data_loaders(use_test_data)",
"with open(self.imgpathfile, 'r') as f:\n train_paths, valid_paths, test_paths ... | <|body_start_0|>
self.imgpathfile = imgpathfile
self.labelpath = labelpath
self.imgsize = size
assert os.path.exists(self.imgpathfile), 'File {} does not exist'.format(self.imgpathfile)
self.dataloaders = self.get_data_loaders(use_test_data)
<|end_body_0|>
<|body_start_1|>
... | DataManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataManager:
def __init__(self, imgpathfile, labelpath=None, size=[320, 240], use_test_data=False):
"""imgpathfile: a text file containing paths of all images in the dataset stored as a list containting three lists for train, valid, test splits ex: [[p1,p2,p6...],[p3,p4...],[p5...]] labe... | stack_v2_sparse_classes_36k_train_000727 | 4,436 | no_license | [
{
"docstring": "imgpathfile: a text file containing paths of all images in the dataset stored as a list containting three lists for train, valid, test splits ex: [[p1,p2,p6...],[p3,p4...],[p5...]] labelpath (optional): path of .npy file which has a numpy array of size (N, 1000) containing pre-computed soft targ... | 2 | stack_v2_sparse_classes_30k_train_003137 | Implement the Python class `DataManager` described below.
Class description:
Implement the DataManager class.
Method signatures and docstrings:
- def __init__(self, imgpathfile, labelpath=None, size=[320, 240], use_test_data=False): imgpathfile: a text file containing paths of all images in the dataset stored as a li... | Implement the Python class `DataManager` described below.
Class description:
Implement the DataManager class.
Method signatures and docstrings:
- def __init__(self, imgpathfile, labelpath=None, size=[320, 240], use_test_data=False): imgpathfile: a text file containing paths of all images in the dataset stored as a li... | a2b93f81714bc6a72771e04418d7f86be0ead494 | <|skeleton|>
class DataManager:
def __init__(self, imgpathfile, labelpath=None, size=[320, 240], use_test_data=False):
"""imgpathfile: a text file containing paths of all images in the dataset stored as a list containting three lists for train, valid, test splits ex: [[p1,p2,p6...],[p3,p4...],[p5...]] labe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataManager:
def __init__(self, imgpathfile, labelpath=None, size=[320, 240], use_test_data=False):
"""imgpathfile: a text file containing paths of all images in the dataset stored as a list containting three lists for train, valid, test splits ex: [[p1,p2,p6...],[p3,p4...],[p5...]] labelpath (optiona... | the_stack_v2_python_sparse | style-transfer-zoom/dataset.py | lovelyyoshino/learnopencv | train | 4 | |
910fb218042b70b9f1322d79d62dc4277c7d72c5 | [
"connection = pymysql.connect(host='localhost', user='itymos', password='qSa$5cQf', db='jobs')\ncursor = connection.cursor()\nreturn (connection, cursor)",
"conn, cursor = self.open_conn()\nfor i in list_of_tasks:\n if cursor.execute(\"insert into `tasks` (`job_type`, `config`, `created`, `status`) values ({},... | <|body_start_0|>
connection = pymysql.connect(host='localhost', user='itymos', password='qSa$5cQf', db='jobs')
cursor = connection.cursor()
return (connection, cursor)
<|end_body_0|>
<|body_start_1|>
conn, cursor = self.open_conn()
for i in list_of_tasks:
if cursor.e... | This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them | DBUpdater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBUpdater:
"""This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them"""
def open_conn(self):
"""This method opens connection to the db and initializes cursor object to communicate with it :returns tuple: curs... | stack_v2_sparse_classes_36k_train_000728 | 4,935 | no_license | [
{
"docstring": "This method opens connection to the db and initializes cursor object to communicate with it :returns tuple: cursor - obj, the object for communicating with db; connection - the connection object",
"name": "open_conn",
"signature": "def open_conn(self)"
},
{
"docstring": "The meth... | 5 | stack_v2_sparse_classes_30k_train_001852 | Implement the Python class `DBUpdater` described below.
Class description:
This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them
Method signatures and docstrings:
- def open_conn(self): This method opens connection to the db and initializes ... | Implement the Python class `DBUpdater` described below.
Class description:
This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them
Method signatures and docstrings:
- def open_conn(self): This method opens connection to the db and initializes ... | 969c528c6b1dbf7c792bfe21197098aa2fb1b3d7 | <|skeleton|>
class DBUpdater:
"""This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them"""
def open_conn(self):
"""This method opens connection to the db and initializes cursor object to communicate with it :returns tuple: curs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBUpdater:
"""This class is the database updater which responds to requests from clients and server to update info in db tables and fulfils them"""
def open_conn(self):
"""This method opens connection to the db and initializes cursor object to communicate with it :returns tuple: cursor - obj, the... | the_stack_v2_python_sparse | python_tasks_ss/andriy_task/db_handler.py | Rocckk/my-repo | train | 0 |
1e0cb55544bf5d06761e6d89e3766d8483ad0580 | [
"question = Question.objects.all()\nserializer = QuestionSerializer(question, many=True)\nreturn Response(serializer.data, status=200)",
"serializer = QuestionSerializer(data=self.request.data)\nif serializer.is_valid():\n serializer.save(self.request.user)\n return Response(status=201)\nreturn Response(ser... | <|body_start_0|>
question = Question.objects.all()
serializer = QuestionSerializer(question, many=True)
return Response(serializer.data, status=200)
<|end_body_0|>
<|body_start_1|>
serializer = QuestionSerializer(data=self.request.data)
if serializer.is_valid():
seri... | Questions API | QuestionAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
<|body_0|>
def create(self, *args, **kwargs):
"""creates a question"""
<|body_1|>
def details(self, *args, **kwargs):
"""view details of a question"""... | stack_v2_sparse_classes_36k_train_000729 | 1,648 | no_license | [
{
"docstring": "lists all questions",
"name": "list",
"signature": "def list(self, *args, **kwargs)"
},
{
"docstring": "creates a question",
"name": "create",
"signature": "def create(self, *args, **kwargs)"
},
{
"docstring": "view details of a question",
"name": "details",
... | 4 | stack_v2_sparse_classes_30k_train_007455 | Implement the Python class `QuestionAPI` described below.
Class description:
Questions API
Method signatures and docstrings:
- def list(self, *args, **kwargs): lists all questions
- def create(self, *args, **kwargs): creates a question
- def details(self, *args, **kwargs): view details of a question
- def edit(self, ... | Implement the Python class `QuestionAPI` described below.
Class description:
Questions API
Method signatures and docstrings:
- def list(self, *args, **kwargs): lists all questions
- def create(self, *args, **kwargs): creates a question
- def details(self, *args, **kwargs): view details of a question
- def edit(self, ... | 4795bbc9ea90badc5e2a6804110b3a21f4cab9ce | <|skeleton|>
class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
<|body_0|>
def create(self, *args, **kwargs):
"""creates a question"""
<|body_1|>
def details(self, *args, **kwargs):
"""view details of a question"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
question = Question.objects.all()
serializer = QuestionSerializer(question, many=True)
return Response(serializer.data, status=200)
def create(self, *args, **kwargs):
"... | the_stack_v2_python_sparse | questions/views.py | Swiftkind/qna | train | 0 |
01895a4046eca661f203cbda16c54c73245d3930 | [
"self.sess = tf.Session(config=config)\nwith open(pbfile, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n self.sess.graph.as_default()\n tf.import_graph_def(graph_def, name='')\nself.sess.run(tf.global_variables_initializer())\nself.img = self.sess.graph.get_tensor_by_nam... | <|body_start_0|>
self.sess = tf.Session(config=config)
with open(pbfile, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
self.sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
self.sess.run(tf.global_variable... | Predictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
<|body_0|>
def __resize_image(self, image, short_edge_length=224, max_length=224):
"""resize image return: resized image"""
... | stack_v2_sparse_classes_36k_train_000730 | 1,721 | no_license | [
{
"docstring": "pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)",
"name": "__init__",
"signature": "def __init__(self, pbfile, config: tf.ConfigProto)"
},
{
"docstring": "resize image return: resized image",
"name": "__resize_image",
"signature": "def __resize_imag... | 3 | stack_v2_sparse_classes_30k_train_015653 | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, pbfile, config: tf.ConfigProto): pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)
- def __resize_image(self, image, short_edge_length=2... | Implement the Python class `Predictor` described below.
Class description:
Implement the Predictor class.
Method signatures and docstrings:
- def __init__(self, pbfile, config: tf.ConfigProto): pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)
- def __resize_image(self, image, short_edge_length=2... | df392eabef563dcca47fc8389da079553a016650 | <|skeleton|>
class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
<|body_0|>
def __resize_image(self, image, short_edge_length=224, max_length=224):
"""resize image return: resized image"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Predictor:
def __init__(self, pbfile, config: tf.ConfigProto):
"""pbfile: pb file config: like tf.ConfigProto(allow_soft_placement=True)"""
self.sess = tf.Session(config=config)
with open(pbfile, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.... | the_stack_v2_python_sparse | others/tf_1_15_0_materials/tf_1.15.0_workspace/tf_alexnet_test/tf_detect_pb.py | guoqiang0148666/person_caffe_mish | train | 0 | |
3775f085a18f1884a6b0708f81feb8d15dc7bf7e | [
"if cls.ENGINE is not None:\n return cls.ENGINE\nelse:\n if user is None:\n user = cls.MYSQL_USER\n if password is None:\n password = cls.MYSQL_PASS\n if host is None:\n host = cls.MYSQL_HOST\n if dev is False:\n database = cls.MYSQL_DB\n else:\n database = 'mvi_... | <|body_start_0|>
if cls.ENGINE is not None:
return cls.ENGINE
else:
if user is None:
user = cls.MYSQL_USER
if password is None:
password = cls.MYSQL_PASS
if host is None:
host = cls.MYSQL_HOST
if ... | Connection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Connection:
def get_engine(cls, dev=False, user=None, password=None, host=None, echo=False):
"""SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :param password: :param host: :param echo: if True, the Engine will log all statements as well as a rep... | stack_v2_sparse_classes_36k_train_000731 | 1,766 | no_license | [
{
"docstring": "SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :param password: :param host: :param echo: if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. :return: SQLAlchemy `E... | 2 | stack_v2_sparse_classes_30k_train_007573 | Implement the Python class `Connection` described below.
Class description:
Implement the Connection class.
Method signatures and docstrings:
- def get_engine(cls, dev=False, user=None, password=None, host=None, echo=False): SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :par... | Implement the Python class `Connection` described below.
Class description:
Implement the Connection class.
Method signatures and docstrings:
- def get_engine(cls, dev=False, user=None, password=None, host=None, echo=False): SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :par... | 91081877ca221089776acc9816dc907dcd5d2f73 | <|skeleton|>
class Connection:
def get_engine(cls, dev=False, user=None, password=None, host=None, echo=False):
"""SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :param password: :param host: :param echo: if True, the Engine will log all statements as well as a rep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Connection:
def get_engine(cls, dev=False, user=None, password=None, host=None, echo=False):
"""SQL connections, SQL execution and high-level DB-API interface. :param dev: :param user: :param password: :param host: :param echo: if True, the Engine will log all statements as well as a repr() of their p... | the_stack_v2_python_sparse | utils/database/connection.py | armsky/MVI | train | 0 | |
314ced44a2df83b2f5a2f983434a22bcb6eca3ca | [
"logging.warning('Combined all categorical features to single embedding table.')\nembeddings.append(dlrm.nn.BuckleEmbedding(categorical_feature_sizes, embedding_dim))\nfor cat, size in enumerate(categorical_feature_sizes):\n module = embeddings[0]\n nn.init.uniform_(module.embedding.weight.data[module.offsets... | <|body_start_0|>
logging.warning('Combined all categorical features to single embedding table.')
embeddings.append(dlrm.nn.BuckleEmbedding(categorical_feature_sizes, embedding_dim))
for cat, size in enumerate(categorical_feature_sizes):
module = embeddings[0]
nn.init.unif... | DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance. | DlrmJointEmbedding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DlrmJointEmbedding:
"""DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance."""
def _create_embeddings(self, embeddings, embedding_dim, categorical_feature_sizes):
"""Combine all one hot embeddings as one"""
... | stack_v2_sparse_classes_36k_train_000732 | 14,106 | permissive | [
{
"docstring": "Combine all one hot embeddings as one",
"name": "_create_embeddings",
"signature": "def _create_embeddings(self, embeddings, embedding_dim, categorical_feature_sizes)"
},
{
"docstring": "Args: numerical_input (Tensor): with shape [batch_size, num_numerical_features] categorical_i... | 2 | null | Implement the Python class `DlrmJointEmbedding` described below.
Class description:
DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance.
Method signatures and docstrings:
- def _create_embeddings(self, embeddings, embedding_dim, categorical_feat... | Implement the Python class `DlrmJointEmbedding` described below.
Class description:
DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance.
Method signatures and docstrings:
- def _create_embeddings(self, embeddings, embedding_dim, categorical_feat... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class DlrmJointEmbedding:
"""DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance."""
def _create_embeddings(self, embeddings, embedding_dim, categorical_feature_sizes):
"""Combine all one hot embeddings as one"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DlrmJointEmbedding:
"""DLRM uses one hot embedding only If all embeddings are one hot, they can be easily combined and will have better performance."""
def _create_embeddings(self, embeddings, embedding_dim, categorical_feature_sizes):
"""Combine all one hot embeddings as one"""
logging.w... | the_stack_v2_python_sparse | recommendation/ctr/dlrm/pytorch/dlrm/deprecated_model.py | Deep-Spark/DeepSparkHub | train | 7 |
1c76306cbac0863ca58f76cdcc76a9c657d3fa4a | [
"super(FullyConnected, self).__init__()\nself.seq = nn.ModuleList([Layer(num_in, hidden, dropout=dropout, norm=norm)])\nself.seq += stack_layers(hidden, layers=LAYERS_FULL - 1, dropout=dropout, norm=norm)",
"for m in self.seq:\n x = m(x)\nreturn x"
] | <|body_start_0|>
super(FullyConnected, self).__init__()
self.seq = nn.ModuleList([Layer(num_in, hidden, dropout=dropout, norm=norm)])
self.seq += stack_layers(hidden, layers=LAYERS_FULL - 1, dropout=dropout, norm=norm)
<|end_body_0|>
<|body_start_1|>
for m in self.seq:
x = m... | FullyConnected | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyConnected:
def __init__(self, num_in, dropout=None, hidden=None, norm=None):
""":param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: size of each hidden layer. :param norm: string type of normalization."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k_train_000733 | 5,028 | permissive | [
{
"docstring": ":param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: size of each hidden layer. :param norm: string type of normalization.",
"name": "__init__",
"signature": "def __init__(self, num_in, dropout=None, hidden=None, norm=None)"
},
{
"doc... | 2 | null | Implement the Python class `FullyConnected` described below.
Class description:
Implement the FullyConnected class.
Method signatures and docstrings:
- def __init__(self, num_in, dropout=None, hidden=None, norm=None): :param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: s... | Implement the Python class `FullyConnected` described below.
Class description:
Implement the FullyConnected class.
Method signatures and docstrings:
- def __init__(self, num_in, dropout=None, hidden=None, norm=None): :param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: s... | b40e9b147186ca04efd384d05b0f5e27ff8bd71a | <|skeleton|>
class FullyConnected:
def __init__(self, num_in, dropout=None, hidden=None, norm=None):
""":param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: size of each hidden layer. :param norm: string type of normalization."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullyConnected:
def __init__(self, num_in, dropout=None, hidden=None, norm=None):
""":param num_in: scalar number of input weights. :param dropout: scalar dropout rate. :param hidden: size of each hidden layer. :param norm: string type of normalization."""
super(FullyConnected, self).__init__(... | the_stack_v2_python_sparse | nets/util.py | yuwei-cheng/eBay | train | 0 | |
07a98d68b565e9bb91911bba2883692db6463b28 | [
"if len(prices) < 2:\n return 0\nprofit = 0\nfor i in xrange(1, len(prices)):\n if prices[i] > prices[i - 1]:\n profit += prices[i] - prices[i - 1]\nreturn profit",
"if len(prices) < 2:\n return 0\nlow = prices[0]\nprofit = 0\nfor i in range(1, len(prices)):\n if prices[i] >= prices[i - 1]:\n ... | <|body_start_0|>
if len(prices) < 2:
return 0
profit = 0
for i in xrange(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit
<|end_body_0|>
<|body_start_1|>
if len(prices) < 2:
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(prices) < 2:
return 0... | stack_v2_sparse_classes_36k_train_000734 | 1,261 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if len(prices) < 2:
return 0
profit = 0
for i in xrange(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return pro... | the_stack_v2_python_sparse | prob122_best_time_buy_sell_stock2.py | Hu-Wenchao/leetcode | train | 0 | |
c43098e360efe030c96e00170f5b328229875bdf | [
"self.cookie = json.loads(cookies)\nself.url_list = url_list\nself.session = requests.Session()\nself.ckjar = requests.cookies.RequestsCookieJar()\nself.result = []\nself.headers = headers\nfor i in self.cookie:\n self.ckjar.set(i['name'], i['value'])\nself.session.cookies.update(self.ckjar)",
"for url in self... | <|body_start_0|>
self.cookie = json.loads(cookies)
self.url_list = url_list
self.session = requests.Session()
self.ckjar = requests.cookies.RequestsCookieJar()
self.result = []
self.headers = headers
for i in self.cookie:
self.ckjar.set(i['name'], i['v... | 带cookie访问查询结果 | CookieRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
<|body_0|>
def cookie_requests(self):
"""带cookie依次访问各个查询结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cookie ... | stack_v2_sparse_classes_36k_train_000735 | 26,194 | no_license | [
{
"docstring": "设置requests中的session的cookie",
"name": "__init__",
"signature": "def __init__(self, cookies, url_list=None, headers=None)"
},
{
"docstring": "带cookie依次访问各个查询结果",
"name": "cookie_requests",
"signature": "def cookie_requests(self)"
}
] | 2 | null | Implement the Python class `CookieRequest` described below.
Class description:
带cookie访问查询结果
Method signatures and docstrings:
- def __init__(self, cookies, url_list=None, headers=None): 设置requests中的session的cookie
- def cookie_requests(self): 带cookie依次访问各个查询结果 | Implement the Python class `CookieRequest` described below.
Class description:
带cookie访问查询结果
Method signatures and docstrings:
- def __init__(self, cookies, url_list=None, headers=None): 设置requests中的session的cookie
- def cookie_requests(self): 带cookie依次访问各个查询结果
<|skeleton|>
class CookieRequest:
"""带cookie访问查询结果""... | dc9dbbb5bf5e3d29cd664219826ca334916b953f | <|skeleton|>
class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
<|body_0|>
def cookie_requests(self):
"""带cookie依次访问各个查询结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CookieRequest:
"""带cookie访问查询结果"""
def __init__(self, cookies, url_list=None, headers=None):
"""设置requests中的session的cookie"""
self.cookie = json.loads(cookies)
self.url_list = url_list
self.session = requests.Session()
self.ckjar = requests.cookies.RequestsCookieJa... | the_stack_v2_python_sparse | skill/crawler_gov.py | mj3428/python_for_practice | train | 1 |
3861605213769ea43a4fc8fb34df844bc0daabfb | [
"name = input.get('name')\nnew_tour = tournament_model(name=name)\nnew_tour.save()\nreturn new_tour",
"try:\n if input.get('tournament_id', None):\n tournament_to_update = extract_value_from_input(input=input, field_id='tournament_id', model_type='Tournament', model=tournament_model)\nexcept ObjectDoesN... | <|body_start_0|>
name = input.get('name')
new_tour = tournament_model(name=name)
new_tour.save()
return new_tour
<|end_body_0|>
<|body_start_1|>
try:
if input.get('tournament_id', None):
tournament_to_update = extract_value_from_input(input=input, fie... | TournamentService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TournamentService:
def createTournament(self, input):
"""Crea un nuovo torneo."""
<|body_0|>
def update_tournament(self, input):
"""Modifica dei dati di un torneo."""
<|body_1|>
def delete_tournament(self, input):
"""Cancellazione di un torneo.""... | stack_v2_sparse_classes_36k_train_000736 | 1,775 | permissive | [
{
"docstring": "Crea un nuovo torneo.",
"name": "createTournament",
"signature": "def createTournament(self, input)"
},
{
"docstring": "Modifica dei dati di un torneo.",
"name": "update_tournament",
"signature": "def update_tournament(self, input)"
},
{
"docstring": "Cancellazion... | 3 | stack_v2_sparse_classes_30k_train_004547 | Implement the Python class `TournamentService` described below.
Class description:
Implement the TournamentService class.
Method signatures and docstrings:
- def createTournament(self, input): Crea un nuovo torneo.
- def update_tournament(self, input): Modifica dei dati di un torneo.
- def delete_tournament(self, inp... | Implement the Python class `TournamentService` described below.
Class description:
Implement the TournamentService class.
Method signatures and docstrings:
- def createTournament(self, input): Crea un nuovo torneo.
- def update_tournament(self, input): Modifica dei dati di un torneo.
- def delete_tournament(self, inp... | f097eae54a12ba4f3983869fef627ea1d55a37d1 | <|skeleton|>
class TournamentService:
def createTournament(self, input):
"""Crea un nuovo torneo."""
<|body_0|>
def update_tournament(self, input):
"""Modifica dei dati di un torneo."""
<|body_1|>
def delete_tournament(self, input):
"""Cancellazione di un torneo.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TournamentService:
def createTournament(self, input):
"""Crea un nuovo torneo."""
name = input.get('name')
new_tour = tournament_model(name=name)
new_tour.save()
return new_tour
def update_tournament(self, input):
"""Modifica dei dati di un torneo."""
... | the_stack_v2_python_sparse | rtcbproj/rtcb/tournament/service.py | arsenico13/rtcb-backend | train | 0 | |
7e36bd0a93c1562ad212bf7e819cba0634f51dbe | [
"collections = ['sn4_AOI_6_Atlanta']\nassert image in {'MS', 'PAN', 'PS-RGBNIR'}\nself.angles = angles\nif self.angles:\n for angle in self.angles:\n assert angle in self.angle_catalog_map.keys()\nsuper().__init__(root, image, collections, transforms, download, api_key, checksum)",
"files = []\nnadir = ... | <|body_start_0|>
collections = ['sn4_AOI_6_Atlanta']
assert image in {'MS', 'PAN', 'PS-RGBNIR'}
self.angles = angles
if self.angles:
for angle in self.angles:
assert angle in self.angle_catalog_map.keys()
super().__init__(root, image, collections, tran... | SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off-nadir angle ranges from 7 degrees to 54 degrees. Dataset features: * No. of... | SpaceNet4 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceNet4:
"""SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off-nadir angle ranges from 7 degrees to 5... | stack_v2_sparse_classes_36k_train_000737 | 45,367 | permissive | [
{
"docstring": "Initialize a new SpaceNet 4 Dataset instance. Args: root: root directory where dataset can be found image: image selection which must be in [\"MS\", \"PAN\", \"PS-RGBNIR\"] angles: angle selection which must be in [\"nadir\", \"off-nadir\", \"very-off-nadir\"] transforms: a function/transform th... | 2 | null | Implement the Python class `SpaceNet4` described below.
Class description:
SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off... | Implement the Python class `SpaceNet4` described below.
Class description:
SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class SpaceNet4:
"""SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off-nadir angle ranges from 7 degrees to 5... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceNet4:
"""SpaceNet 4: Off-Nadir Buildings Dataset. `SpaceNet 4 <https://spacenet.ai/off-nadir-building-detection/>`_ is a dataset of 27 WV-2 imagery captured at varying off-nadir angles and associated building footprints over the city of Atlanta. The off-nadir angle ranges from 7 degrees to 54 degrees. Da... | the_stack_v2_python_sparse | torchgeo/datasets/spacenet.py | microsoft/torchgeo | train | 1,724 |
9a1d6f5d8127abefef0e61b1b6e7a0840f7863f3 | [
"if not (attrs['phone_number'] or attrs['email']):\n raise serializers.ValidationError('手机号和邮箱必须要提供一个')\nreturn attrs",
"value = attrs[source]\npattern = re.compile('[0-9]+')\nmatch = pattern.match(value)\nif not match:\n raise serializers.ValidationError('Wrong format in phone number')\nreturn attrs"
] | <|body_start_0|>
if not (attrs['phone_number'] or attrs['email']):
raise serializers.ValidationError('手机号和邮箱必须要提供一个')
return attrs
<|end_body_0|>
<|body_start_1|>
value = attrs[source]
pattern = re.compile('[0-9]+')
match = pattern.match(value)
if not match:
... | QLUserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QLUserSerializer:
def validate(self, attrs):
"""验证手机号码和邮箱必须输入一个"""
<|body_0|>
def validate_phone_number(self, attrs, source):
"""验证手机号是否正确"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not (attrs['phone_number'] or attrs['email']):
... | stack_v2_sparse_classes_36k_train_000738 | 1,523 | no_license | [
{
"docstring": "验证手机号码和邮箱必须输入一个",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "验证手机号是否正确",
"name": "validate_phone_number",
"signature": "def validate_phone_number(self, attrs, source)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000699 | Implement the Python class `QLUserSerializer` described below.
Class description:
Implement the QLUserSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): 验证手机号码和邮箱必须输入一个
- def validate_phone_number(self, attrs, source): 验证手机号是否正确 | Implement the Python class `QLUserSerializer` described below.
Class description:
Implement the QLUserSerializer class.
Method signatures and docstrings:
- def validate(self, attrs): 验证手机号码和邮箱必须输入一个
- def validate_phone_number(self, attrs, source): 验证手机号是否正确
<|skeleton|>
class QLUserSerializer:
def validate(sel... | 95ace626e843061c1d4ee4c7b3ec8f2bd5e0021e | <|skeleton|>
class QLUserSerializer:
def validate(self, attrs):
"""验证手机号码和邮箱必须输入一个"""
<|body_0|>
def validate_phone_number(self, attrs, source):
"""验证手机号是否正确"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QLUserSerializer:
def validate(self, attrs):
"""验证手机号码和邮箱必须输入一个"""
if not (attrs['phone_number'] or attrs['email']):
raise serializers.ValidationError('手机号和邮箱必须要提供一个')
return attrs
def validate_phone_number(self, attrs, source):
"""验证手机号是否正确"""
value = ... | the_stack_v2_python_sparse | qluser/serializers.py | Zhe-Zhu/Qianli-server | train | 0 | |
698a90718259ae16a37dbf14ff84f5e0d3e9138c | [
"super().__init__(name, description, origin, formula, composition, temperature)\nif layers is None:\n layers = []\nself.layers.extend(layers)",
"layer = SpecimenLayer(name, thickness, formula, composition)\nself.layers.append(layer)\nreturn layer"
] | <|body_start_0|>
super().__init__(name, description, origin, formula, composition, temperature)
if layers is None:
layers = []
self.layers.extend(layers)
<|end_body_0|>
<|body_start_1|>
layer = SpecimenLayer(name, thickness, formula, composition)
self.layers.append(l... | SpecimenMultilayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecimenMultilayer:
def __init__(self, name, description=None, origin=None, formula=None, composition=None, temperature=None, layers=None):
"""Defines a multi-layered physical specimen :arg name: name (required) :arg description: description (optional) :arg origin: origin (optional) :arg... | stack_v2_sparse_classes_36k_train_000739 | 3,816 | permissive | [
{
"docstring": "Defines a multi-layered physical specimen :arg name: name (required) :arg description: description (optional) :arg origin: origin (optional) :arg formula: formula (optional) :arg composition: composition (optional) :arg temperature: temperature (optional) :arg layers: layers (optional)",
"na... | 2 | stack_v2_sparse_classes_30k_train_006886 | Implement the Python class `SpecimenMultilayer` described below.
Class description:
Implement the SpecimenMultilayer class.
Method signatures and docstrings:
- def __init__(self, name, description=None, origin=None, formula=None, composition=None, temperature=None, layers=None): Defines a multi-layered physical speci... | Implement the Python class `SpecimenMultilayer` described below.
Class description:
Implement the SpecimenMultilayer class.
Method signatures and docstrings:
- def __init__(self, name, description=None, origin=None, formula=None, composition=None, temperature=None, layers=None): Defines a multi-layered physical speci... | 0081ea29127c72e8a0511a9f8fc58d0fe098b801 | <|skeleton|>
class SpecimenMultilayer:
def __init__(self, name, description=None, origin=None, formula=None, composition=None, temperature=None, layers=None):
"""Defines a multi-layered physical specimen :arg name: name (required) :arg description: description (optional) :arg origin: origin (optional) :arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecimenMultilayer:
def __init__(self, name, description=None, origin=None, formula=None, composition=None, temperature=None, layers=None):
"""Defines a multi-layered physical specimen :arg name: name (required) :arg description: description (optional) :arg origin: origin (optional) :arg formula: form... | the_stack_v2_python_sparse | pyhmsa/spec/condition/specimen.py | pyhmsa/pyhmsa | train | 2 | |
b20c07118efd6f48d1a54ef1f6ebb8eb150d7cac | [
"if cls.instance is None:\n cls.instance = super().__new__(cls)\nreturn cls.instance",
"if not MusicPlayer.init_flag:\n print('初始化音乐播放器')\n MusicPlayer.init_flag = True"
] | <|body_start_0|>
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
<|end_body_0|>
<|body_start_1|>
if not MusicPlayer.init_flag:
print('初始化音乐播放器')
MusicPlayer.init_flag = True
<|end_body_1|>
| MusicPlayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MusicPlayer:
def __new__(cls, *args, **kwargs):
"""重写创建方法"""
<|body_0|>
def __init__(self):
"""重写初始化方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instan... | stack_v2_sparse_classes_36k_train_000740 | 2,738 | no_license | [
{
"docstring": "重写创建方法",
"name": "__new__",
"signature": "def __new__(cls, *args, **kwargs)"
},
{
"docstring": "重写初始化方法",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007326 | Implement the Python class `MusicPlayer` described below.
Class description:
Implement the MusicPlayer class.
Method signatures and docstrings:
- def __new__(cls, *args, **kwargs): 重写创建方法
- def __init__(self): 重写初始化方法 | Implement the Python class `MusicPlayer` described below.
Class description:
Implement the MusicPlayer class.
Method signatures and docstrings:
- def __new__(cls, *args, **kwargs): 重写创建方法
- def __init__(self): 重写初始化方法
<|skeleton|>
class MusicPlayer:
def __new__(cls, *args, **kwargs):
"""重写创建方法"""
... | a4a1ae34daaa2764ee8d7005f414772c12d90c6a | <|skeleton|>
class MusicPlayer:
def __new__(cls, *args, **kwargs):
"""重写创建方法"""
<|body_0|>
def __init__(self):
"""重写初始化方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MusicPlayer:
def __new__(cls, *args, **kwargs):
"""重写创建方法"""
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
"""重写初始化方法"""
if not MusicPlayer.init_flag:
print('初始化音乐播放器')
Music... | the_stack_v2_python_sparse | 02_面向对象/py_09_单例模式.py | sunweiye12/python-BasicLearning | train | 0 | |
34214125728ef5378fc0039be119a79c54feb478 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PrintTaskDefinition()",
"from .app_identity import AppIdentity\nfrom .entity import Entity\nfrom .print_task import PrintTask\nfrom .app_identity import AppIdentity\nfrom .entity import Entity\nfrom .print_task import PrintTask\nfields... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PrintTaskDefinition()
<|end_body_0|>
<|body_start_1|>
from .app_identity import AppIdentity
from .entity import Entity
from .print_task import PrintTask
from .app_identit... | PrintTaskDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrintTaskDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrintTaskDefinition:
"""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 ob... | stack_v2_sparse_classes_36k_train_000741 | 2,858 | 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: PrintTaskDefinition",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | stack_v2_sparse_classes_30k_test_000232 | Implement the Python class `PrintTaskDefinition` described below.
Class description:
Implement the PrintTaskDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrintTaskDefinition: Creates a new instance of the appropriate class based on d... | Implement the Python class `PrintTaskDefinition` described below.
Class description:
Implement the PrintTaskDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrintTaskDefinition: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrintTaskDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrintTaskDefinition:
"""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 ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrintTaskDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrintTaskDefinition:
"""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/print_task_definition.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
08cfdcc97016edc56b3a099c5f01cd65edbe7b3d | [
"Part = self.old_state.apps.get_model('part', 'part')\nBomItem = self.old_state.apps.get_model('part', 'bomitem')\na = Part.objects.create(name='Part A', description='My part A')\nb = Part.objects.create(name='Part B', description='My part B')\nc = Part.objects.create(name='Part C', description='My part C')\nBomIte... | <|body_start_0|>
Part = self.old_state.apps.get_model('part', 'part')
BomItem = self.old_state.apps.get_model('part', 'bomitem')
a = Part.objects.create(name='Part A', description='My part A')
b = Part.objects.create(name='Part B', description='My part B')
c = Part.objects.create... | Tests for BomItem migrations | TestBomItemMigrations | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBomItemMigrations:
"""Tests for BomItem migrations"""
def prepare(self):
"""Create initial dataset"""
<|body_0|>
def test_validated_field(self):
"""Test that the 'validated' field is added to the BomItem objects"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_000742 | 8,200 | permissive | [
{
"docstring": "Create initial dataset",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the 'validated' field is added to the BomItem objects",
"name": "test_validated_field",
"signature": "def test_validated_field(self)"
}
] | 2 | null | Implement the Python class `TestBomItemMigrations` described below.
Class description:
Tests for BomItem migrations
Method signatures and docstrings:
- def prepare(self): Create initial dataset
- def test_validated_field(self): Test that the 'validated' field is added to the BomItem objects | Implement the Python class `TestBomItemMigrations` described below.
Class description:
Tests for BomItem migrations
Method signatures and docstrings:
- def prepare(self): Create initial dataset
- def test_validated_field(self): Test that the 'validated' field is added to the BomItem objects
<|skeleton|>
class TestBo... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestBomItemMigrations:
"""Tests for BomItem migrations"""
def prepare(self):
"""Create initial dataset"""
<|body_0|>
def test_validated_field(self):
"""Test that the 'validated' field is added to the BomItem objects"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBomItemMigrations:
"""Tests for BomItem migrations"""
def prepare(self):
"""Create initial dataset"""
Part = self.old_state.apps.get_model('part', 'part')
BomItem = self.old_state.apps.get_model('part', 'bomitem')
a = Part.objects.create(name='Part A', description='My ... | the_stack_v2_python_sparse | InvenTree/part/test_migrations.py | inventree/InvenTree | train | 3,077 |
9acb8e88722b1681bb55ebcbc23c391d8fdf6396 | [
"async with ClientSession() as session:\n async with session.get(url=url) as response:\n if response.status < 200 or response.status > 399:\n raise APIError(await response.text())\n return await response.json()",
"async with ClientSession() as session:\n async with session.post(url=... | <|body_start_0|>
async with ClientSession() as session:
async with session.get(url=url) as response:
if response.status < 200 or response.status > 399:
raise APIError(await response.text())
return await response.json()
<|end_body_0|>
<|body_start_... | An interface to the REST API. | Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.... | stack_v2_sparse_classes_36k_train_000743 | 12,017 | no_license | [
{
"docstring": "Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.",
"name": "get",
"signature": "async def get(self, url)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_016182 | Implement the Python class `Resource` described below.
Class description:
An interface to the REST API.
Method signatures and docstrings:
- async def get(self, url): Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: AP... | Implement the Python class `Resource` described below.
Class description:
An interface to the REST API.
Method signatures and docstrings:
- async def get(self, url): Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: AP... | 72f407f8c8862e59383bfb913edf55e367d4f45a | <|skeleton|>
class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code."""
a... | the_stack_v2_python_sparse | core/api.py | gorolykmaxim/loadbalancer | train | 0 |
26018fe27f69c9126904fac32c2a816f482c3529 | [
"super(LoadFactOperator, self).__init__(*args, **kwargs)\nself.redshift_conn_id = redshift_conn_id\nself.source_table = source_table\nself.dest_table = dest_table\nself.sql_query = sql_query",
"self.log.info(f'Inserting facts into {self.dest_table}')\nredshift = PostgresHook(postgres_conn_id=self.redshift_conn_id... | <|body_start_0|>
super(LoadFactOperator, self).__init__(*args, **kwargs)
self.redshift_conn_id = redshift_conn_id
self.source_table = source_table
self.dest_table = dest_table
self.sql_query = sql_query
<|end_body_0|>
<|body_start_1|>
self.log.info(f'Inserting facts into... | The LoadFactOperator loads data from staging to fact table. | LoadFactOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadFactOperator:
"""The LoadFactOperator loads data from staging to fact table."""
def __init__(self, redshift_conn_id='', source_table='', dest_table='', sql_query='', *args, **kwargs):
"""Init method for the operator Args: redshift_conn_id Connection information for the datbase so... | stack_v2_sparse_classes_36k_train_000744 | 2,989 | no_license | [
{
"docstring": "Init method for the operator Args: redshift_conn_id Connection information for the datbase source_table Name of the staging table dest_table Name of the destination table sql_query Query to execute for inserting data",
"name": "__init__",
"signature": "def __init__(self, redshift_conn_id... | 2 | stack_v2_sparse_classes_30k_train_020765 | Implement the Python class `LoadFactOperator` described below.
Class description:
The LoadFactOperator loads data from staging to fact table.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id='', source_table='', dest_table='', sql_query='', *args, **kwargs): Init method for the operator Args: r... | Implement the Python class `LoadFactOperator` described below.
Class description:
The LoadFactOperator loads data from staging to fact table.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id='', source_table='', dest_table='', sql_query='', *args, **kwargs): Init method for the operator Args: r... | 27930a41a6de6049a05375f488c9ac94608ed2fe | <|skeleton|>
class LoadFactOperator:
"""The LoadFactOperator loads data from staging to fact table."""
def __init__(self, redshift_conn_id='', source_table='', dest_table='', sql_query='', *args, **kwargs):
"""Init method for the operator Args: redshift_conn_id Connection information for the datbase so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadFactOperator:
"""The LoadFactOperator loads data from staging to fact table."""
def __init__(self, redshift_conn_id='', source_table='', dest_table='', sql_query='', *args, **kwargs):
"""Init method for the operator Args: redshift_conn_id Connection information for the datbase source_table Na... | the_stack_v2_python_sparse | 06-capstone-project/airflow/plugins/operators/load_fact.py | mvillafuertem/udacity-data-engineer-nanodegree | train | 0 |
e3a8f74072497e2b8ba02a3fb84a48f606fd5a79 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.openShiftItem'.casefold():\n from .open_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | ShiftItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShiftItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ShiftItem:
"""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: ShiftI... | stack_v2_sparse_classes_36k_train_000745 | 3,310 | 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: ShiftItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `ShiftItem` described below.
Class description:
Implement the ShiftItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ShiftItem: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `ShiftItem` described below.
Class description:
Implement the ShiftItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ShiftItem: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ShiftItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ShiftItem:
"""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: ShiftI... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShiftItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ShiftItem:
"""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: ShiftItem"""
... | the_stack_v2_python_sparse | msgraph/generated/models/shift_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8395b39aa4f23f5efad29bed9216afe4189f1ebc | [
"super().__init__()\nself.dropout = nn.Dropout(p=dropout)\nself.layers = numlayers\nself.hsz = hiddensize\nself.esz = embeddingsize\nself.lt = nn.Embedding(num_features, embeddingsize, padding_idx=padding_idx, sparse=sparse)\nself.rnn = rnn_class(embeddingsize + hiddensize, hiddensize, numlayers, dropout=dropout if... | <|body_start_0|>
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.layers = numlayers
self.hsz = hiddensize
self.esz = embeddingsize
self.lt = nn.Embedding(num_features, embeddingsize, padding_idx=padding_idx, sparse=sparse)
self.rnn = rnn_class(embeddi... | Recurrent decoder module that uses dialog history encoded by context lstm. | HredDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HredDecoder:
"""Recurrent decoder module that uses dialog history encoded by context lstm."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_length=-1, sparse=False):
"""Initialize recurre... | stack_v2_sparse_classes_36k_train_000746 | 9,697 | permissive | [
{
"docstring": "Initialize recurrent decoder.",
"name": "__init__",
"signature": "def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_length=-1, sparse=False)"
},
{
"docstring": "Decode from input tokens. ... | 2 | null | Implement the Python class `HredDecoder` described below.
Class description:
Recurrent decoder module that uses dialog history encoded by context lstm.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input... | Implement the Python class `HredDecoder` described below.
Class description:
Recurrent decoder module that uses dialog history encoded by context lstm.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class HredDecoder:
"""Recurrent decoder module that uses dialog history encoded by context lstm."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_length=-1, sparse=False):
"""Initialize recurre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HredDecoder:
"""Recurrent decoder module that uses dialog history encoded by context lstm."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_length=-1, sparse=False):
"""Initialize recurrent decoder.""... | the_stack_v2_python_sparse | parlai/agents/hred/modules.py | facebookresearch/ParlAI | train | 10,943 |
9cac6c3e75d096639db82fc0a0c4940cd5081e6d | [
"arr_len = len(arr)\nnew_arr = []\nfor num in arr:\n new_arr.append(num)\n if num == 0:\n new_arr.append(0)\n if len(new_arr) == arr_len:\n break\nfor i in range(arr_len):\n arr[i] = new_arr[i]",
"arr_len = len(arr)\ni = 0\nwhile i < arr_len - 1:\n if arr[i] == 0:\n for j in ra... | <|body_start_0|>
arr_len = len(arr)
new_arr = []
for num in arr:
new_arr.append(num)
if num == 0:
new_arr.append(0)
if len(new_arr) == arr_len:
break
for i in range(arr_len):
arr[i] = new_arr[i]
<|end_body_0|... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr."""
<|body_0|>
def duplicateZeros2(self, arr: List[int]) -> None:
"""Do not return anything, ... | stack_v2_sparse_classes_36k_train_000747 | 1,824 | permissive | [
{
"docstring": "Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr.",
"name": "duplicateZeros",
"signature": "def duplicateZeros(self, arr: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify arr in-place instead. In p... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicateZeros(self, arr: List[int]) -> None: Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr.
- def duplicateZ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicateZeros(self, arr: List[int]) -> None: Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr.
- def duplicateZ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr."""
<|body_0|>
def duplicateZeros2(self, arr: List[int]) -> None:
"""Do not return anything, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""Do not return anything, modify arr in-place instead. Just create a new array, and set the value to the old arr."""
arr_len = len(arr)
new_arr = []
for num in arr:
new_arr.append(num)
if num =... | the_stack_v2_python_sparse | src/1089-DuplicateZeros.py | Jiezhi/myleetcode | train | 1 | |
d466752c6e4c1e57fe2d4f37259e514e3087e930 | [
"super(CodeEntryBox, self).__init__()\nself.id = id\nself.alert_layer = alert_layer",
"self.get_buffer().insert_text(position, new_text, length)\nnext_box = self.alert_layer.get_entry_box(self.id + 1)\nif next_box is not None:\n next_box.grab_focus()\nelse:\n self.alert_layer.confirm_code()\nreturn position... | <|body_start_0|>
super(CodeEntryBox, self).__init__()
self.id = id
self.alert_layer = alert_layer
<|end_body_0|>
<|body_start_1|>
self.get_buffer().insert_text(position, new_text, length)
next_box = self.alert_layer.get_entry_box(self.id + 1)
if next_box is not None:
... | Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation provided by Gtk.Editable, which is call... | CodeEntryBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation... | stack_v2_sparse_classes_36k_train_000748 | 7,836 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, alert_layer=None, id=None)"
},
{
"docstring": "Overrides the default handler for insert_text signals.",
"name": "do_insert_text",
"signature": "def do_insert_text(self, new_text, length, position)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002760 | Implement the Python class `CodeEntryBox` described below.
Class description:
Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This fun... | Implement the Python class `CodeEntryBox` described below.
Class description:
Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This fun... | a63f338c4ee791f9dbf9c2791d1dc8e6326d32f2 | <|skeleton|>
class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation provided by ... | the_stack_v2_python_sparse | interface/notifications/AlertAuthorization.py | mccolm-robotics/ClaverMessageBoard | train | 0 |
846d362b361b0681508272ba588b4b7db9b213e1 | [
"if not root:\n return '[None]'\nans = []\nstack = []\nstack.append(root)\nwhile stack:\n node = stack.pop(0)\n if node:\n stack.append(node.left)\n stack.append(node.right)\n ans.append(node.val)\n else:\n ans.append(None)\nans = ','.join([str(num) for num in ans])\nreturn a... | <|body_start_0|>
if not root:
return '[None]'
ans = []
stack = []
stack.append(root)
while stack:
node = stack.pop(0)
if node:
stack.append(node.left)
stack.append(node.right)
ans.append(node.val)... | 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_000749 | 1,642 | 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_test_000464 | 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:... | 7a54fc8f85e3e7f937bb504a8f4c6de6dd7da3e2 | <|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 '[None]'
ans = []
stack = []
stack.append(root)
while stack:
node = stack.pop(0)
if node:
... | the_stack_v2_python_sparse | 剑指/面试题37.序列化二叉树.py | ElonXie/LeetCode-Practice | train | 0 | |
3a161dd6dbe23017b76349bbd49f1f46af02cbac | [
"r = 0\nhight = 100\nfor i in range(num):\n r += hight\n hight /= 2\n r += hight\nreturn (hight, r)",
"for per in s_father:\n if per == s_child:\n return True\nreturn False",
"s_len = len(s_child)\nfor index_ in range(len(s_father) - s_len + 1):\n per = s_father[index_:index_ + s_len]\n ... | <|body_start_0|>
r = 0
hight = 100
for i in range(num):
r += hight
hight /= 2
r += hight
return (hight, r)
<|end_body_0|>
<|body_start_1|>
for per in s_father:
if per == s_child:
return True
return False
<|e... | Pratice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
<|body_0|>
def func_02(self, s_father, s_child):
"""第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in"""
<... | stack_v2_sparse_classes_36k_train_000750 | 3,368 | no_license | [
{
"docstring": "第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:",
"name": "func_01",
"signature": "def func_01(self, num, is_count=None)"
},
{
"docstring": "第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in",
"name": "func_02",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_007184 | Implement the Python class `Pratice` described below.
Class description:
Implement the Pratice class.
Method signatures and docstrings:
- def func_01(self, num, is_count=None): 第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:
- def func_02(self, s_father, s_child): 第二题: 判断一个单个字符是否在一个字符串里面... | Implement the Python class `Pratice` described below.
Class description:
Implement the Pratice class.
Method signatures and docstrings:
- def func_01(self, num, is_count=None): 第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:
- def func_02(self, s_father, s_child): 第二题: 判断一个单个字符是否在一个字符串里面... | 167c86be6241c6c148eb586b5dd19275246372a7 | <|skeleton|>
class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
<|body_0|>
def func_02(self, s_father, s_child):
"""第二题: 判断一个单个字符是否在一个字符串里面 s_father = 'hello world' s_child = 'd' 注:不能用in"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pratice:
def func_01(self, num, is_count=None):
"""第一题: 给一个下落次数, 1.求出此时小球离地面的距离 2.小球总共走的路径 :param num: :param is_count: :return:"""
r = 0
hight = 100
for i in range(num):
r += hight
hight /= 2
r += hight
return (hight, r)
def fun... | the_stack_v2_python_sparse | py3-study/面向对象课上代码/1901/9-10/练习题02_答案.py | liuluyang/mk | train | 0 | |
ba61ba7954b2a7866bb9c7f494df973efe361271 | [
"super().__init__(*args, **kwargs)\nif 'direct_course' not in self.fields:\n return\nif self.instance.pk:\n course_query = self.instance.get_course().get_snapshots(include_self=True).filter(extended_object__publisher_is_draft=True).distinct()\nelse:\n course_query = models.Course.objects.filter(extended_ob... | <|body_start_0|>
super().__init__(*args, **kwargs)
if 'direct_course' not in self.fields:
return
if self.instance.pk:
course_query = self.instance.get_course().get_snapshots(include_self=True).filter(extended_object__publisher_is_draft=True).distinct()
else:
... | Admin form used for frontend editing. | CourseRunAdminForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseRunAdminForm:
"""Admin form used for frontend editing."""
def __init__(self, *args, **kwargs):
"""If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the maste... | stack_v2_sparse_classes_36k_train_000751 | 11,939 | permissive | [
{
"docstring": "If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the master course or one of its snapshots If the form is instanciated to create a new course run and the \"Add\" form is open... | 2 | stack_v2_sparse_classes_30k_train_011847 | Implement the Python class `CourseRunAdminForm` described below.
Class description:
Admin form used for frontend editing.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): If the form is instanciated to update an existing course run: > show the direct course select box only if the course has on... | Implement the Python class `CourseRunAdminForm` described below.
Class description:
Admin form used for frontend editing.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): If the form is instanciated to update an existing course run: > show the direct course select box only if the course has on... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class CourseRunAdminForm:
"""Admin form used for frontend editing."""
def __init__(self, *args, **kwargs):
"""If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the maste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseRunAdminForm:
"""Admin form used for frontend editing."""
def __init__(self, *args, **kwargs):
"""If the form is instanciated to update an existing course run: > show the direct course select box only if the course has one or more snapshots and limit choices to either the master course or o... | the_stack_v2_python_sparse | src/richie/apps/courses/admin.py | openfun/richie | train | 238 |
bf4de1539026567b345f2737ee45b0e86987bc63 | [
"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... | The price service definition. | PriceServicer | [
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000752 | 4,782 | permissive | [
{
"docstring": "A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request",
"name": "GetPrice",
"signature": "def GetPrice(self, request, context)"
},
{
"docstring": "Sends all available... | 5 | null | Implement the Python class `PriceServicer` described below.
Class description:
The price service definition.
Method signatures and docstrings:
- def GetPrice(self, request, context): A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are... | Implement the Python class `PriceServicer` described below.
Class description:
The price service definition.
Method signatures and docstrings:
- def GetPrice(self, request, context): A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are... | 1604ae035a3bd81e87a4037326b7935d1f268452 | <|skeleton|>
class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
context.set_code(grpc.Stat... | the_stack_v2_python_sparse | services/price/price_pb2_grpc.py | vishalbelsare/XBOS | train | 1 |
761bea4011adc7b579c1ce12dac73a034a182dc7 | [
"super().__init__()\nself._remote_path: epath.Path = epath.Path(path)\nself._cached_path: epath.Path = cache.cache_path() / 'community-datasets-list.jsonl'\nif self._cached_path.exists():\n self._refresh_from_content(self._cached_path.read_text())",
"dataset_packages = [DatasetPackage.from_json(json.loads(line... | <|body_start_0|>
super().__init__()
self._remote_path: epath.Path = epath.Path(path)
self._cached_path: epath.Path = cache.cache_path() / 'community-datasets-list.jsonl'
if self._cached_path.exists():
self._refresh_from_content(self._cached_path.read_text())
<|end_body_0|>
<... | Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package index is a simple list of datasets with their associated source: ```jsonl {"name": ... | _PackageIndex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PackageIndex:
"""Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package index is a simple list of datasets with th... | stack_v2_sparse_classes_36k_train_000753 | 15,868 | permissive | [
{
"docstring": "Contructor. Args: path: Remote location of the package index (file containing the list of dataset packages)",
"name": "__init__",
"signature": "def __init__(self, path: epath.PathLike)"
},
{
"docstring": "Update the index from the given `jsonl` content.",
"name": "_refresh_fr... | 3 | null | Implement the Python class `_PackageIndex` described below.
Class description:
Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package ind... | Implement the Python class `_PackageIndex` described below.
Class description:
Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package ind... | 41ae3cf1439711ed2f50f99caa0e6702082e6d37 | <|skeleton|>
class _PackageIndex:
"""Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package index is a simple list of datasets with th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _PackageIndex:
"""Package index. Package index is a `Dict[DatasetName, _DatasetPackage]` loaded from cache. It has an additional `.refresh()` method to update the local cache by querying the remote index (stored in `gs://tfds-data`). On disk, the package index is a simple list of datasets with their associate... | the_stack_v2_python_sparse | tensorflow_datasets/core/community/register_package.py | tensorflow/datasets | train | 4,224 |
506e22432b46b906ca84796856578ca1d473f842 | [
"super().__init__()\nself.use_sigmoid = use_sigmoid\nmodel = [nn.Conv2d(input_nc, 64, 3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True)]\nmodel += [nn.Conv2d(64, 64, 3, stride=2, padding=1), norm_layer(64), nn.LeakyReLU(0.2, inplace=True)]\ninput_nc = 64\nfor i in range(n_layers_d):\n model += [nn.Conv2d(... | <|body_start_0|>
super().__init__()
self.use_sigmoid = use_sigmoid
model = [nn.Conv2d(input_nc, 64, 3, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(64, 64, 3, stride=2, padding=1), norm_layer(64), nn.LeakyReLU(0.2, inplace=True)]
input_nc = 64
... | NoPatchDiscriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_... | stack_v2_sparse_classes_36k_train_000754 | 1,792 | permissive | [
{
"docstring": "Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_layers_d (int): the number of convolution blocks use_sigmoid (bool): sigmoid activation at the end",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_005817 | Implement the Python class `NoPatchDiscriminator` described below.
Class description:
Implement the NoPatchDiscriminator class.
Method signatures and docstrings:
- def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True): Construct a no patch gan discriminator... | Implement the Python class `NoPatchDiscriminator` described below.
Class description:
Implement the NoPatchDiscriminator class.
Method signatures and docstrings:
- def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True): Construct a no patch gan discriminator... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoPatchDiscriminator:
def __init__(self, input_nc: int, norm_layer: nn.Module=nn.BatchNorm2d, n_layers_d: int=4, use_sigmoid: bool=True):
"""Construct a no patch gan discriminator. Args: input_nc (int): the number of channels in input images norm_layer (nn.Module): normalization layer n_layers_d (int)... | the_stack_v2_python_sparse | simulation/utils/machine_learning/cycle_gan/models/no_patch_discriminator.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 | |
3e27bc73e5e89a0838a15641db44137573030ee3 | [
"overlaps = []\nfor other in shapes:\n if other is self:\n continue\n overlap = self.get_overlap(other)\n if overlap.dist < 0:\n overlaps.append(overlap)\nif len(overlaps) == 0:\n return\noverlaps.sort(key=lambda item: item.area, reverse=True)\nfor i, old_overlap in enumerate(overlaps):\n ... | <|body_start_0|>
overlaps = []
for other in shapes:
if other is self:
continue
overlap = self.get_overlap(other)
if overlap.dist < 0:
overlaps.append(overlap)
if len(overlaps) == 0:
return
overlaps.sort(key=l... | Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject. | CollisionShape | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
... | stack_v2_sparse_classes_36k_train_000755 | 24,636 | permissive | [
{
"docstring": "Resolve this shape's overlap(s) with given list of shapes.",
"name": "resolve_overlaps_with_shapes",
"signature": "def resolve_overlaps_with_shapes(self, shapes)"
},
{
"docstring": "Resolve this shape's given overlap.",
"name": "resolve_overlap",
"signature": "def resolve... | 3 | null | Implement the Python class `CollisionShape` described below.
Class description:
Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject.
Method signatures and docstrings:
- def resolve_overlaps_with_shapes(self, shapes): Resolve... | Implement the Python class `CollisionShape` described below.
Class description:
Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject.
Method signatures and docstrings:
- def resolve_overlaps_with_shapes(self, shapes): Resolve... | 79b3c24deb26d1d2e5855461c8819f0542ce5ea4 | <|skeleton|>
class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
overlap... | the_stack_v2_python_sparse | collision.py | michael-lazar/playscii | train | 28 |
3ab1113c546bc7a99aea7b355fbc03f64f397463 | [
"self.type = typ\nself.rootobj = rootobject\nself.islead = islead\nself.obj = None\nif self.type == 'excel':\n self._findexcel(field)\nelse:\n self._findword(field)",
"found = False\nfor sheet in self.rootobj:\n r = sheet.min_row\n for c in range(sheet.min_column, sheet.max_column + 1):\n if st... | <|body_start_0|>
self.type = typ
self.rootobj = rootobject
self.islead = islead
self.obj = None
if self.type == 'excel':
self._findexcel(field)
else:
self._findword(field)
<|end_body_0|>
<|body_start_1|>
found = False
for sheet in ... | Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self.islead - чи є поле прові... | SourceItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_36k_train_000756 | 5,367 | no_license | [
{
"docstring": "Конструктор. Здійснює під'єднання до джерела даних. rootobject - об'єкт, де розташовано відповідні дані: документ (Document) або робоча книга (Workbook), в залежності від типу. islead - чи є параметр провідним.",
"name": "__init__",
"signature": "def __init__(self, field, typ, rootobject... | 4 | stack_v2_sparse_classes_30k_train_004844 | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | Implement the Python class `SourceItem` described below.
Class description:
Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт ... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceItem:
"""Джерело даних для злиття а також елемент даних для злиття для деякого поля. Призначено для під'єднання до джерела даних та повернення елементів даних по кроках. self.type - тип джерела даних ('word' чи 'excel') self.rootobj - кореневий об'єкт документ (Document) або робоча книга (Workbook) self... | the_stack_v2_python_sparse | dz_others/subject23_MS/merge/t23_22_sourceitem.py | davendiy/ads_course2 | train | 0 |
15e99ba95c604a8f555305823cf1d8d017f8a145 | [
"self.maxNumbers = maxNumbers\nself.used = set()\nself.freed = list()",
"if len(self.used) == self.maxNumbers:\n return -1\nif not self.freed:\n res = len(self.used)\nelse:\n res = self.freed.pop(0)\nself.used.add(res)\nreturn res",
"if number in self.used:\n return False\nreturn True",
"if number... | <|body_start_0|>
self.maxNumbers = maxNumbers
self.used = set()
self.freed = list()
<|end_body_0|>
<|body_start_1|>
if len(self.used) == self.maxNumbers:
return -1
if not self.freed:
res = len(self.used)
else:
res = self.freed.pop(0)
... | PhoneDirectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_36k_train_000757 | 4,081 | no_license | [
{
"docstring": "Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.",
"name": "__init__",
"signature": "def __init__(self, maxNumbers: int)"
},
{
"docstring": "Provide a number which is not assigned to anyone. @return - Return an... | 4 | stack_v2_sparse_classes_30k_train_005204 | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | 6b24724da055a08510c83c645455eaa4ed201298 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
self.maxNumbers = maxNumbers
self.used = set()
self.freed = list()
def get(self) -> int:
... | the_stack_v2_python_sparse | Design/python/leetcode/design_phone_directory.py | sankeerth/Algorithms | train | 0 | |
c13a5c30f27b8591dea3f9be1eca1ba76d870310 | [
"self.covariance = covariance\nself.rho_c_vec = self.covariance.rho_c_vec\nself.gridpoints = self.covariance.gridpoints\nself.l_max = self.covariance.l_max\nself.sigma0 = self.covariance.sigma0",
"zerovec = np.zeros(self.gridpoints)\nidentity = np.identity(self.gridpoints)\nPhiArray = np.zeros([nsamples, self.gri... | <|body_start_0|>
self.covariance = covariance
self.rho_c_vec = self.covariance.rho_c_vec
self.gridpoints = self.covariance.gridpoints
self.l_max = self.covariance.l_max
self.sigma0 = self.covariance.sigma0
<|end_body_0|>
<|body_start_1|>
zerovec = np.zeros(self.gridpoint... | Sampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sampler:
def __init__(self, covariance):
"""Takes a Covariance object [covariance], and grabs some useful data from it."""
<|body_0|>
def GetSamples(self, nubar, nfields, nsamples):
"""Takes a dimensionless field height [nubar], number of waterfall fields [nfields], ... | stack_v2_sparse_classes_36k_train_000758 | 1,793 | no_license | [
{
"docstring": "Takes a Covariance object [covariance], and grabs some useful data from it.",
"name": "__init__",
"signature": "def __init__(self, covariance)"
},
{
"docstring": "Takes a dimensionless field height [nubar], number of waterfall fields [nfields], and number of samples [nsamples], a... | 2 | stack_v2_sparse_classes_30k_train_011881 | Implement the Python class `Sampler` described below.
Class description:
Implement the Sampler class.
Method signatures and docstrings:
- def __init__(self, covariance): Takes a Covariance object [covariance], and grabs some useful data from it.
- def GetSamples(self, nubar, nfields, nsamples): Takes a dimensionless ... | Implement the Python class `Sampler` described below.
Class description:
Implement the Sampler class.
Method signatures and docstrings:
- def __init__(self, covariance): Takes a Covariance object [covariance], and grabs some useful data from it.
- def GetSamples(self, nubar, nfields, nsamples): Takes a dimensionless ... | 6339b5efd4b464f22e35fa4dff6814b6260ffca4 | <|skeleton|>
class Sampler:
def __init__(self, covariance):
"""Takes a Covariance object [covariance], and grabs some useful data from it."""
<|body_0|>
def GetSamples(self, nubar, nfields, nsamples):
"""Takes a dimensionless field height [nubar], number of waterfall fields [nfields], ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sampler:
def __init__(self, covariance):
"""Takes a Covariance object [covariance], and grabs some useful data from it."""
self.covariance = covariance
self.rho_c_vec = self.covariance.rho_c_vec
self.gridpoints = self.covariance.gridpoints
self.l_max = self.covariance.l... | the_stack_v2_python_sparse | stack/sampling_old/Sampler.py | jolyonb/black-holes-stack | train | 3 | |
aae539e233e413b3300fa7da40cfff40a848a57e | [
"super(UiTeamConfig, self).__init__()\nloadUi('../ui/team_config.ui', self)\nself.leadCheckBox = self.findChild(QCheckBox, 'leadCheckBox')\nself.leadCheckBox.setCheckState(settings.lead_status)\nself.leadCheckBox.stateChanged.connect(self.__toggle_lead)\nself.leadIPLabel = self.findChild(QLabel, 'leadIPLabel')\nsel... | <|body_start_0|>
super(UiTeamConfig, self).__init__()
loadUi('../ui/team_config.ui', self)
self.leadCheckBox = self.findChild(QCheckBox, 'leadCheckBox')
self.leadCheckBox.setCheckState(settings.lead_status)
self.leadCheckBox.stateChanged.connect(self.__toggle_lead)
self.l... | The team window which handles the system role and connections to the host when running as a client. | UiTeamConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UiTeamConfig:
"""The team window which handles the system role and connections to the host when running as a client."""
def __init__(self):
"""Initialize the team window and set all signals and slots associated with it."""
<|body_0|>
def __toggle_lead(self):
"""T... | stack_v2_sparse_classes_36k_train_000759 | 1,901 | no_license | [
{
"docstring": "Initialize the team window and set all signals and slots associated with it.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Toggle the host IP label, text line, and connect button; then toggle lead_status.",
"name": "__toggle_lead",
"signature"... | 2 | stack_v2_sparse_classes_30k_val_000558 | Implement the Python class `UiTeamConfig` described below.
Class description:
The team window which handles the system role and connections to the host when running as a client.
Method signatures and docstrings:
- def __init__(self): Initialize the team window and set all signals and slots associated with it.
- def _... | Implement the Python class `UiTeamConfig` described below.
Class description:
The team window which handles the system role and connections to the host when running as a client.
Method signatures and docstrings:
- def __init__(self): Initialize the team window and set all signals and slots associated with it.
- def _... | b2cc3e04cea044f0aba600f78b6eae670e20a0c4 | <|skeleton|>
class UiTeamConfig:
"""The team window which handles the system role and connections to the host when running as a client."""
def __init__(self):
"""Initialize the team window and set all signals and slots associated with it."""
<|body_0|>
def __toggle_lead(self):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UiTeamConfig:
"""The team window which handles the system role and connections to the host when running as a client."""
def __init__(self):
"""Initialize the team window and set all signals and slots associated with it."""
super(UiTeamConfig, self).__init__()
loadUi('../ui/team_co... | the_stack_v2_python_sparse | src/team_config.py | CS4311-spring-2020/pick-tool-team14-keikaku | train | 1 |
9b9d2e92cd91c45f67e6eb750aa266f7d56476ba | [
"n = len(arr)\nids = list(range(n))\nids.sort(key=lambda i: (arr[i], i))\nnextBigger = [-1] * n\nstack = []\nfor id in ids:\n while stack and stack[-1] < id:\n nextBigger[stack.pop()] = id\n stack.append(id)\nids.sort(key=lambda i: (-arr[i], i))\nnextSmaller = [-1] * n\nstack = []\nfor id in ids:\n ... | <|body_start_0|>
n = len(arr)
ids = list(range(n))
ids.sort(key=lambda i: (arr[i], i))
nextBigger = [-1] * n
stack = []
for id in ids:
while stack and stack[-1] < id:
nextBigger[stack.pop()] = id
stack.append(id)
ids.sort(ke... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
<|body_0|>
def helper2(self, nums: List[int]) -> Tuple[List[int], List[int]]:
"""有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的"""
... | stack_v2_sparse_classes_36k_train_000760 | 2,829 | no_license | [
{
"docstring": "寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个",
"name": "helper1",
"signature": "def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]"
},
{
"docstring": "有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的",
"name": "helper2",
"signature": "def helper2(self, nums... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]: 寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个
- def helper2(self, nums: List[int]) -> Tuple[List[int], List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]: 寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个
- def helper2(self, nums: List[int]) -> Tuple[List[int], List[int... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
<|body_0|>
def helper2(self, nums: List[int]) -> Tuple[List[int], List[int]]:
"""有序集合寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 相同大的,取index小的"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def helper1(self, arr: List[int]) -> Tuple[List[int], List[int]]:
"""寻找每个元素右侧比自己大的里最小的和右侧比自己小的里最大的 如果有多个符合题意,取右侧第一个"""
n = len(arr)
ids = list(range(n))
ids.sort(key=lambda i: (arr[i], i))
nextBigger = [-1] * n
stack = []
for id in ids:
... | the_stack_v2_python_sparse | 1_stack/单调栈/对每个数,寻找右侧比自己大的数里最小的那个 copy.py | 981377660LMT/algorithm-study | train | 225 | |
182ba0f72185f59c4102a7399d4598fb257cecc1 | [
"self.e_ner = e_ner\nself.e_link = e_link\nself.e_rel = e_rel\nself.k_graphy = k_graphy",
"print('handle text .')\nentity_list = self.e_ner.extract_entity(text)\nentity_rel_list = self.e_rel.extract_rel(entity_list)"
] | <|body_start_0|>
self.e_ner = e_ner
self.e_link = e_link
self.e_rel = e_rel
self.k_graphy = k_graphy
<|end_body_0|>
<|body_start_1|>
print('handle text .')
entity_list = self.e_ner.extract_entity(text)
entity_rel_list = self.e_rel.extract_rel(entity_list)
<|end_b... | EntityMaster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityMaster:
def __init__(self, e_ner, e_link, e_rel, k_graphy):
"""e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储"""
<|body_0|>
def handle(self, text):
"""实体总体处理流程 输入:text 文本串 输出:list[(head entity, rel, tail entity)]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_000761 | 1,145 | no_license | [
{
"docstring": "e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储",
"name": "__init__",
"signature": "def __init__(self, e_ner, e_link, e_rel, k_graphy)"
},
{
"docstring": "实体总体处理流程 输入:text 文本串 输出:list[(head entity, rel, tail entity)]",
"name": "handle",
"signature": "def handl... | 2 | null | Implement the Python class `EntityMaster` described below.
Class description:
Implement the EntityMaster class.
Method signatures and docstrings:
- def __init__(self, e_ner, e_link, e_rel, k_graphy): e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储
- def handle(self, text): 实体总体处理流程 输入:text 文本串 输出:list[(he... | Implement the Python class `EntityMaster` described below.
Class description:
Implement the EntityMaster class.
Method signatures and docstrings:
- def __init__(self, e_ner, e_link, e_rel, k_graphy): e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储
- def handle(self, text): 实体总体处理流程 输入:text 文本串 输出:list[(he... | 606623bf41fd1741541f2ef4a6aa75404663e353 | <|skeleton|>
class EntityMaster:
def __init__(self, e_ner, e_link, e_rel, k_graphy):
"""e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储"""
<|body_0|>
def handle(self, text):
"""实体总体处理流程 输入:text 文本串 输出:list[(head entity, rel, tail entity)]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityMaster:
def __init__(self, e_ner, e_link, e_rel, k_graphy):
"""e_ner :实体识别,抽取 e_link : 实体链接 e_rel : 实体关系 k_graphy : 知识图谱存储"""
self.e_ner = e_ner
self.e_link = e_link
self.e_rel = e_rel
self.k_graphy = k_graphy
def handle(self, text):
"""实体总体处理流程 输入:te... | the_stack_v2_python_sparse | knowledge graphy/lib/entity/entity_main.py | linshaoxin-maker/myproject | train | 0 | |
141af823bbc459f86c8522375ad450a9df1fa58c | [
"self.eggForms = forms\nself.FormCls = FormCls\nself.conceptIdToForm = {}\nself.languageWrapper = languageWrapper",
"for eggForm in self.eggForms:\n if eggForm.conceptId not in self.conceptIdToForm:\n form = self.FormCls(text=eggForm.text, concept=concepts[eggForm.conceptId], language=self.languageWrapp... | <|body_start_0|>
self.eggForms = forms
self.FormCls = FormCls
self.conceptIdToForm = {}
self.languageWrapper = languageWrapper
<|end_body_0|>
<|body_start_1|>
for eggForm in self.eggForms:
if eggForm.conceptId not in self.conceptIdToForm:
form = self.... | Wrapper to handle properly loading the various concept forms | FormsWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormsWrapper:
"""Wrapper to handle properly loading the various concept forms"""
def __init__(self, forms, FormCls, languageWrapper):
"""Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class"""
<|body_0|>
def load(self, concepts):
... | stack_v2_sparse_classes_36k_train_000762 | 1,219 | no_license | [
{
"docstring": "Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class",
"name": "__init__",
"signature": "def __init__(self, forms, FormCls, languageWrapper)"
},
{
"docstring": "Load the forms",
"name": "load",
"signature": "def load(self, concepts)"
... | 3 | stack_v2_sparse_classes_30k_train_004181 | Implement the Python class `FormsWrapper` described below.
Class description:
Wrapper to handle properly loading the various concept forms
Method signatures and docstrings:
- def __init__(self, forms, FormCls, languageWrapper): Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class... | Implement the Python class `FormsWrapper` described below.
Class description:
Wrapper to handle properly loading the various concept forms
Method signatures and docstrings:
- def __init__(self, forms, FormCls, languageWrapper): Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class... | f08dc4465b7e4fb32235e1647c46edd4472f9093 | <|skeleton|>
class FormsWrapper:
"""Wrapper to handle properly loading the various concept forms"""
def __init__(self, forms, FormCls, languageWrapper):
"""Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class"""
<|body_0|>
def load(self, concepts):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormsWrapper:
"""Wrapper to handle properly loading the various concept forms"""
def __init__(self, forms, FormCls, languageWrapper):
"""Initialize the Forms Wrapper with the forms from the egg and the corresponding Model Class"""
self.eggForms = forms
self.FormCls = FormCls
... | the_stack_v2_python_sparse | src/Import/forms_wrapper.py | cloew/VocabTester | train | 0 |
9bf54eef59b4b12877faecb3ec547b55a51d2e11 | [
"queryset = super(CalendarView, self).get_queryset()\nqueryset = queryset.filter(author=self.request.user)\nmonth = self.get_month()\nreturn queryset.filter(date__month=month.month, date__year=month.year)",
"try:\n today = date.today()\n month = int(self.request.GET.get('month', today.month))\n year = in... | <|body_start_0|>
queryset = super(CalendarView, self).get_queryset()
queryset = queryset.filter(author=self.request.user)
month = self.get_month()
return queryset.filter(date__month=month.month, date__year=month.year)
<|end_body_0|>
<|body_start_1|>
try:
today = date... | CalendarView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarView:
def get_queryset(self):
"""Filter entries by currently logged in user."""
<|body_0|>
def get_month(self):
"""Get the month requested from the query string using today as defaults"""
<|body_1|>
def get_weeks(self):
"""Gets the weeks ... | stack_v2_sparse_classes_36k_train_000763 | 6,544 | permissive | [
{
"docstring": "Filter entries by currently logged in user.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Get the month requested from the query string using today as defaults",
"name": "get_month",
"signature": "def get_month(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_000113 | Implement the Python class `CalendarView` described below.
Class description:
Implement the CalendarView class.
Method signatures and docstrings:
- def get_queryset(self): Filter entries by currently logged in user.
- def get_month(self): Get the month requested from the query string using today as defaults
- def get... | Implement the Python class `CalendarView` described below.
Class description:
Implement the CalendarView class.
Method signatures and docstrings:
- def get_queryset(self): Filter entries by currently logged in user.
- def get_month(self): Get the month requested from the query string using today as defaults
- def get... | 4591d26c097513d67e11916583ed043e78e87816 | <|skeleton|>
class CalendarView:
def get_queryset(self):
"""Filter entries by currently logged in user."""
<|body_0|>
def get_month(self):
"""Get the month requested from the query string using today as defaults"""
<|body_1|>
def get_weeks(self):
"""Gets the weeks ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarView:
def get_queryset(self):
"""Filter entries by currently logged in user."""
queryset = super(CalendarView, self).get_queryset()
queryset = queryset.filter(author=self.request.user)
month = self.get_month()
return queryset.filter(date__month=month.month, date... | the_stack_v2_python_sparse | diary/views.py | bbengfort/memoro | train | 1 | |
81bf0379ccf15947a700624b315a0a3a832386bb | [
"if self.triggers == None:\n raise RuntimeError('This object has not been initialized')\nreturn self.get()",
"if len(triggers) == 0:\n raise ValueError('No Triggers have been passed in!')\nfor trigger in triggers:\n if not callable(trigger):\n raise ValueError('A trigger passed into this custom bu... | <|body_start_0|>
if self.triggers == None:
raise RuntimeError('This object has not been initialized')
return self.get()
<|end_body_0|>
<|body_start_1|>
if len(triggers) == 0:
raise ValueError('No Triggers have been passed in!')
for trigger in triggers:
... | This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked. | CustomButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomButton:
"""This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked."""
def __call__(self):
"""Calls get() on this object. :returns: value of get()"""
<|body_0|>
def __init__(s... | stack_v2_sparse_classes_36k_train_000764 | 1,098 | no_license | [
{
"docstring": "Calls get() on this object. :returns: value of get()",
"name": "__call__",
"signature": "def __call__(self)"
},
{
"docstring": "Creates a CustomButton with the triggers that are checked. :param *triggers: comma separated callables to check for",
"name": "__init__",
"signa... | 3 | stack_v2_sparse_classes_30k_train_020092 | Implement the Python class `CustomButton` described below.
Class description:
This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked.
Method signatures and docstrings:
- def __call__(self): Calls get() on this object. :returns:... | Implement the Python class `CustomButton` described below.
Class description:
This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked.
Method signatures and docstrings:
- def __call__(self): Calls get() on this object. :returns:... | f8ff2071787f10c5e75b91190ba70f6569984209 | <|skeleton|>
class CustomButton:
"""This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked."""
def __call__(self):
"""Calls get() on this object. :returns: value of get()"""
<|body_0|>
def __init__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomButton:
"""This class provides a way to create a custom button with any bool function. You can pass in more than one trigger and all of them will be checked."""
def __call__(self):
"""Calls get() on this object. :returns: value of get()"""
if self.triggers == None:
raise... | the_stack_v2_python_sparse | customcontroller/custom_button.py | CtrlZ-FRC4096/Robot-2019-Public | train | 0 |
ba88320c6a86bb3bd777b983742f28d802264643 | [
"if not l1:\n return l2\nelif not l2:\n return l2\nelif l1.val < l2.val:\n l1.next = self.merge_(l1.next, l2)\n return l1\nelse:\n l2.next = self.merge_(l1, l2.next)\n return l2",
"prehead = ListNode(-1)\nnew_head = prehead\nwhile l1 and l2:\n if l1.val <= l2.val:\n new_head.next = l1\... | <|body_start_0|>
if not l1:
return l2
elif not l2:
return l2
elif l1.val < l2.val:
l1.next = self.merge_(l1.next, l2)
return l1
else:
l2.next = self.merge_(l1, l2.next)
return l2
<|end_body_0|>
<|body_start_1|>
... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:"""
<|body_0|>
def merge(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_36k_train_000765 | 1,168 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:",
"name": "merge_",
"signature": "def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode'"
},
{
"docstring": "Approach: Iteration Time Complexity: O(M + N) Space Complex... | 2 | null | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:
- def ... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:
- def ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:"""
<|body_0|>
def merge(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Appr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkedList:
def merge_(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(M + N) Space Complexity: O(M + N) :param l1: :param l2: :return:"""
if not l1:
return l2
elif not l2:
return l2
elif l1.val < l2.val:
... | the_stack_v2_python_sparse | revisited/linked_list/merge_two_sorted_lists.py | Shiv2157k/leet_code | train | 1 | |
1ad7362123486d4cb6207ac67af7ddd1953bc711 | [
"n = len(nums)\nnow, maxIndex, step = (0, 0, 0)\nfor i in range(n - 1):\n if i + nums[i] >= n - 1:\n step += 1\n break\n if i + nums[i] > maxIndex:\n maxIndex = i + nums[i]\n if i == now:\n step += 1\n now = maxIndex\nreturn step",
"n = len(nums)\nnow, maxIndex, step = ... | <|body_start_0|>
n = len(nums)
now, maxIndex, step = (0, 0, 0)
for i in range(n - 1):
if i + nums[i] >= n - 1:
step += 1
break
if i + nums[i] > maxIndex:
maxIndex = i + nums[i]
if i == now:
step +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:"""
<|body_0|>
def jump2(self, nums: List[int]) -> int:
"""执行用时 :36 ms, 在所有 Python3 提交中击败了99.82%的用户 内存消耗 :15 ... | stack_v2_sparse_classes_36k_train_000766 | 2,959 | no_license | [
{
"docstring": "执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:",
"name": "jump",
"signature": "def jump(self, nums: List[int]) -> int"
},
{
"docstring": "执行用时 :36 ms, 在所有 Python3 提交中击败了99.82%的用户 内存消耗 :15 MB, 在所有 Python3 提交中击败了12.50%的用户 思... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: 执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:
- def jump2(self, nums: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums: List[int]) -> int: 执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:
- def jump2(self, nums: List[int... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def jump(self, nums: List[int]) -> int:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:"""
<|body_0|>
def jump2(self, nums: List[int]) -> int:
"""执行用时 :36 ms, 在所有 Python3 提交中击败了99.82%的用户 内存消耗 :15 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums: List[int]) -> int:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了48.97%的用户 内存消耗 :15.2 MB, 在所有 Python3 提交中击败了12.50%的用户 :param nums: :return:"""
n = len(nums)
now, maxIndex, step = (0, 0, 0)
for i in range(n - 1):
if i + nums[i] >= n - 1:
... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/45. Jump Game II.py | yiming1012/MyLeetCode | train | 2 | |
ed4d203f1280e83c28174b377e8ee105d0a8926e | [
"self.rule = {}\nself.winner_paid = winner_paid\nfor symbol, minimum_occurrence in rule.iteritems():\n self.rule[str(symbol)] = minimum_occurrence",
"candidate_dict = defaultdict(int)\nfor symbol in candidate:\n candidate_dict[str(symbol)] += 1\nmatch = True\nfor symbol in self.rule:\n if candidate_dict[... | <|body_start_0|>
self.rule = {}
self.winner_paid = winner_paid
for symbol, minimum_occurrence in rule.iteritems():
self.rule[str(symbol)] = minimum_occurrence
<|end_body_0|>
<|body_start_1|>
candidate_dict = defaultdict(int)
for symbol in candidate:
candi... | A winning combination! | Payline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Payline:
"""A winning combination!"""
def __init__(self, rule, winner_paid):
"""Pass rule as a dict with the symbol and required number of occurrences"""
<|body_0|>
def is_match(self, candidate):
"""Candidate is a list of symbols. Check if they match this payout ... | stack_v2_sparse_classes_36k_train_000767 | 782 | no_license | [
{
"docstring": "Pass rule as a dict with the symbol and required number of occurrences",
"name": "__init__",
"signature": "def __init__(self, rule, winner_paid)"
},
{
"docstring": "Candidate is a list of symbols. Check if they match this payout rule",
"name": "is_match",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_020210 | Implement the Python class `Payline` described below.
Class description:
A winning combination!
Method signatures and docstrings:
- def __init__(self, rule, winner_paid): Pass rule as a dict with the symbol and required number of occurrences
- def is_match(self, candidate): Candidate is a list of symbols. Check if th... | Implement the Python class `Payline` described below.
Class description:
A winning combination!
Method signatures and docstrings:
- def __init__(self, rule, winner_paid): Pass rule as a dict with the symbol and required number of occurrences
- def is_match(self, candidate): Candidate is a list of symbols. Check if th... | 35ef4d55155d7d60ab15113ff068276c29ace510 | <|skeleton|>
class Payline:
"""A winning combination!"""
def __init__(self, rule, winner_paid):
"""Pass rule as a dict with the symbol and required number of occurrences"""
<|body_0|>
def is_match(self, candidate):
"""Candidate is a list of symbols. Check if they match this payout ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Payline:
"""A winning combination!"""
def __init__(self, rule, winner_paid):
"""Pass rule as a dict with the symbol and required number of occurrences"""
self.rule = {}
self.winner_paid = winner_paid
for symbol, minimum_occurrence in rule.iteritems():
self.rule... | the_stack_v2_python_sparse | liberty_bell/slot_machines/components/payline.py | mattgrogan/liberty_bell | train | 0 |
de5046c3c097aa3d4113f44fb92654c9c4a67e9a | [
"vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\nleft = 0\ns = list(s)\nright = len(s) - 1\nwhile left < right:\n if s[left] in vowerls:\n if s[right] in vowerls:\n s[left], s[right] = (s[right], s[left])\n left += 1\n right -= 1\n else:\n r... | <|body_start_0|>
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
if s[left] in vowerls:
if s[right] in vowerls:
s[left], s[right] = (s[right], s[left])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels1(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
... | stack_v2_sparse_classes_36k_train_000768 | 1,824 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels1",
"signature": "def reverseVowels1(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels1(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels1(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseVowels(self, s):
... | 70b7a0f031ef4bc1b04ae787ac1fd78f2f25a04d | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels1(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
vowerls = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
left = 0
s = list(s)
right = len(s) - 1
while left < right:
if s[left] in vowerls:
if s[right] in vowerl... | the_stack_v2_python_sparse | doubleHand/345reverseVowels.py | tzhou2018/LeetCode | train | 6 | |
cb20137b7a6a3e2891263aacd7c460ed9fceab87 | [
"if not head or not head.next:\n return head\ndummy = ListNode(0)\ndummy.next = head\nsize = 0\nwhile head:\n head = head.next\n size += 1\nstep = 1\nwhile step < size:\n curr, tail = (dummy.next, dummy)\n while curr:\n left = curr\n right = self.split_list(left, step)\n curr = s... | <|body_start_0|>
if not head or not head.next:
return head
dummy = ListNode(0)
dummy.next = head
size = 0
while head:
head = head.next
size += 1
step = 1
while step < size:
curr, tail = (dummy.next, dummy)
... | SortList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SortList:
def get_sorted_list(self, head: ListNode) -> ListNode:
"""Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:"""
<|body_0|>
def merge_lists(self, left: ListNode, right: ListNode, head: ListNode) -> ListNode:
"""Merge... | stack_v2_sparse_classes_36k_train_000769 | 2,005 | no_license | [
{
"docstring": "Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:",
"name": "get_sorted_list",
"signature": "def get_sorted_list(self, head: ListNode) -> ListNode"
},
{
"docstring": "Merges left and right given list. :param left: :param right: :param he... | 3 | stack_v2_sparse_classes_30k_train_020634 | Implement the Python class `SortList` described below.
Class description:
Implement the SortList class.
Method signatures and docstrings:
- def get_sorted_list(self, head: ListNode) -> ListNode: Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:
- def merge_lists(self, left: ... | Implement the Python class `SortList` described below.
Class description:
Implement the SortList class.
Method signatures and docstrings:
- def get_sorted_list(self, head: ListNode) -> ListNode: Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:
- def merge_lists(self, left: ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class SortList:
def get_sorted_list(self, head: ListNode) -> ListNode:
"""Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:"""
<|body_0|>
def merge_lists(self, left: ListNode, right: ListNode, head: ListNode) -> ListNode:
"""Merge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SortList:
def get_sorted_list(self, head: ListNode) -> ListNode:
"""Gets the sorted list. Time Complexity: O(log n) Space Complexity: O(1) :param head: :return:"""
if not head or not head.next:
return head
dummy = ListNode(0)
dummy.next = head
size = 0
... | the_stack_v2_python_sparse | data_structures/linked_list/sort_list.py | Shiv2157k/leet_code | train | 1 | |
cd7efce2fad4f02515726771e0790f882b19bece | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"Label(self, text='Fill out the blanks and check the boxes to start ').grid(row=0, column=0, columnspan=2, sticky=W)\nLabel(self, text='Name: ').grid(row=1, column=0, sticky=W)\nself.name_ent = Entry(self)\nself.name_ent.grid(row=1, ... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Fill out the blanks and check the boxes to start ').grid(row=0, column=0, columnspan=2, sticky=W)
Label(self, text='Name: ').grid(row=1,... | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
def __init__(self, master):
"""A GUI Application that creates a story based on user imput"""
<|body_0|>
def create_widgets(self):
"""Create widgets to get story"""
<|body_1|>
def tell_story(self):
"""Fill text box with new text based... | stack_v2_sparse_classes_36k_train_000770 | 4,775 | no_license | [
{
"docstring": "A GUI Application that creates a story based on user imput",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create widgets to get story",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "Fill te... | 3 | null | Implement the Python class `Application` described below.
Class description:
Implement the Application class.
Method signatures and docstrings:
- def __init__(self, master): A GUI Application that creates a story based on user imput
- def create_widgets(self): Create widgets to get story
- def tell_story(self): Fill ... | Implement the Python class `Application` described below.
Class description:
Implement the Application class.
Method signatures and docstrings:
- def __init__(self, master): A GUI Application that creates a story based on user imput
- def create_widgets(self): Create widgets to get story
- def tell_story(self): Fill ... | 4dbb438ebea00c083194ffcd6d285dc43ebe554b | <|skeleton|>
class Application:
def __init__(self, master):
"""A GUI Application that creates a story based on user imput"""
<|body_0|>
def create_widgets(self):
"""Create widgets to get story"""
<|body_1|>
def tell_story(self):
"""Fill text box with new text based... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
def __init__(self, master):
"""A GUI Application that creates a story based on user imput"""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create widgets to get story"""
Label(self, tex... | the_stack_v2_python_sparse | Python 31 Programs/Ch 10 Challenges/Mad Success.py | kayyali18/Python | train | 0 | |
7bee45b7307e3cb215cab80a536e3a6115f603cc | [
"geo_from_db = Geolocations.find_by_ip(ip)\nif not geo_from_db:\n return ({'message': 'Record with ip {} not found in the db.'.format(ip)}, 404)\nreturn ({'IP: {}'.format(ip): '{}'.format(geo_from_db.json())}, 200)",
"record = Geolocations.find_by_ip(ip)\nif not record:\n return ({'message': 'Item with the ... | <|body_start_0|>
geo_from_db = Geolocations.find_by_ip(ip)
if not geo_from_db:
return ({'message': 'Record with ip {} not found in the db.'.format(ip)}, 404)
return ({'IP: {}'.format(ip): '{}'.format(geo_from_db.json())}, 200)
<|end_body_0|>
<|body_start_1|>
record = Geoloca... | This class is called with /geolocation/<string:ip> endpoint. | GeolocationIP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeolocationIP:
"""This class is called with /geolocation/<string:ip> endpoint."""
def get(self, ip):
"""Return a record from 'geolocations' table where ip=ip"""
<|body_0|>
def delete(self, ip):
"""Delete a record from 'geolocations' table where ip=ip"""
<... | stack_v2_sparse_classes_36k_train_000771 | 1,332 | no_license | [
{
"docstring": "Return a record from 'geolocations' table where ip=ip",
"name": "get",
"signature": "def get(self, ip)"
},
{
"docstring": "Delete a record from 'geolocations' table where ip=ip",
"name": "delete",
"signature": "def delete(self, ip)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009014 | Implement the Python class `GeolocationIP` described below.
Class description:
This class is called with /geolocation/<string:ip> endpoint.
Method signatures and docstrings:
- def get(self, ip): Return a record from 'geolocations' table where ip=ip
- def delete(self, ip): Delete a record from 'geolocations' table whe... | Implement the Python class `GeolocationIP` described below.
Class description:
This class is called with /geolocation/<string:ip> endpoint.
Method signatures and docstrings:
- def get(self, ip): Return a record from 'geolocations' table where ip=ip
- def delete(self, ip): Delete a record from 'geolocations' table whe... | b6dcc199df0f7572ac71af88f7eb05293063ca2f | <|skeleton|>
class GeolocationIP:
"""This class is called with /geolocation/<string:ip> endpoint."""
def get(self, ip):
"""Return a record from 'geolocations' table where ip=ip"""
<|body_0|>
def delete(self, ip):
"""Delete a record from 'geolocations' table where ip=ip"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeolocationIP:
"""This class is called with /geolocation/<string:ip> endpoint."""
def get(self, ip):
"""Return a record from 'geolocations' table where ip=ip"""
geo_from_db = Geolocations.find_by_ip(ip)
if not geo_from_db:
return ({'message': 'Record with ip {} not fou... | the_stack_v2_python_sparse | resources/geolocation_ip.py | JoNowakowska/Geolocation_RESTful_API | train | 0 |
581b4545b1ecc60b756adea3486c6b03c95fb0d3 | [
"super().__init__()\nself.han = HANLayer(num_metapaths, in_dim, hidden_dim, num_heads, dropout)\nself.predict = nn.Linear(num_heads * hidden_dim, out_dim)",
"h = self.han(gs, h)\nout = self.predict(h)\nreturn out"
] | <|body_start_0|>
super().__init__()
self.han = HANLayer(num_metapaths, in_dim, hidden_dim, num_heads, dropout)
self.predict = nn.Linear(num_heads * hidden_dim, out_dim)
<|end_body_0|>
<|body_start_1|>
h = self.han(gs, h)
out = self.predict(h)
return out
<|end_body_1|>
| HAN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HAN:
def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_heads, dropout):
"""HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param dropout: float Dropout概率"""
<|b... | stack_v2_sparse_classes_36k_train_000772 | 3,582 | no_license | [
{
"docstring": "HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param dropout: float Dropout概率",
"name": "__init__",
"signature": "def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_hea... | 2 | null | Implement the Python class `HAN` described below.
Class description:
Implement the HAN class.
Method signatures and docstrings:
- def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_heads, dropout): HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out... | Implement the Python class `HAN` described below.
Class description:
Implement the HAN class.
Method signatures and docstrings:
- def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_heads, dropout): HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out... | b40071dc9f9fb20f081f4ed4944a7b65de919c18 | <|skeleton|>
class HAN:
def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_heads, dropout):
"""HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param dropout: float Dropout概率"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HAN:
def __init__(self, num_metapaths, in_dim, hidden_dim, out_dim, num_heads, dropout):
"""HAN模型 :param num_metapaths: int 元路径个数 :param in_dim: int 输入特征维数 :param hidden_dim: int 隐含特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param dropout: float Dropout概率"""
super().__init__(... | the_stack_v2_python_sparse | gnn/han/model.py | deepdumbo/pytorch-tutorial-1 | train | 0 | |
de8eae67e75addc5df5a513a283c116ed9e78e41 | [
"if not isinstance(prior, dict):\n raise TypeError(\"Prior must be dict not '{0}'\".format(type(prior)))\nmean_mean = prior.get('mean_mean', np.zeros(self.num_dim))\nmean_sd = prior.get('mean_sd', np.ones(self.num_dim))\ncov_psi = prior.get('cov_psi', np.eye(self.num_dim))\ncov_nu = prior.get('cov_nu', self.num_... | <|body_start_0|>
if not isinstance(prior, dict):
raise TypeError("Prior must be dict not '{0}'".format(type(prior)))
mean_mean = prior.get('mean_mean', np.zeros(self.num_dim))
mean_sd = prior.get('mean_sd', np.ones(self.num_dim))
cov_psi = prior.get('cov_psi', np.eye(self.num... | GaussianComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianComponent:
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double): df parameter for ... | stack_v2_sparse_classes_36k_train_000773 | 16,562 | permissive | [
{
"docstring": "Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double): df parameter for inverse Wishart",
"name": "sample_parameters",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_019828 | Implement the Python class `GaussianComponent` described below.
Class description:
Implement the GaussianComponent class.
Method signatures and docstrings:
- def sample_parameters(self, prior={}): Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation... | Implement the Python class `GaussianComponent` described below.
Class description:
Implement the GaussianComponent class.
Method signatures and docstrings:
- def sample_parameters(self, prior={}): Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation... | 3b2e8c3addeab2343837b9e86e9cb57b00798b9a | <|skeleton|>
class GaussianComponent:
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double): df parameter for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianComponent:
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double): df parameter for inverse Wishar... | the_stack_v2_python_sparse | ep_clustering/data/_mixture_data.py | PeiKaLunCi/EP_Collapsed_Gibbs | train | 0 | |
0f3c4d09b7dcc6b293fa1e0701c12a1a6c5fc585 | [
"super().__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.pe = None\nself.dtype = dtype\nself.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)))",
"if self.pe is not None:\n if paddle.shape(self.pe)[1] >= paddle.shape(x)[1] * 2 - ... | <|body_start_0|>
super().__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout_rate)
self.pe = None
self.dtype = dtype
self.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)))
<|end_body_0|>
<|body_start... | Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | RelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k_train_000774 | 9,302 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, dtype='float32')"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_015048 | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum inpu... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/transformer/embedding.py | anniyanvr/DeepSpeech-1 | train | 0 |
eaaf6cd5eb0f8eefbb0efe104b5714abf25adef3 | [
"inputSpecification = super().getInputSpecification()\ninputSpecification.addSubSimple('xmlNodeExample', InputTypes.StringType)\nreturn inputSpecification",
"super().__init__()\nself.setInputDataType('dict')\nself.keepInputMeta(True)\nself.outputMultipleRealizations = True\nself.validDataType = ['HistorySet']",
... | <|body_start_0|>
inputSpecification = super().getInputSpecification()
inputSpecification.addSubSimple('xmlNodeExample', InputTypes.StringType)
return inputSpecification
<|end_body_0|>
<|body_start_1|>
super().__init__()
self.setInputDataType('dict')
self.keepInputMeta(Tr... | This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run | testInterfacedPP | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_36k_train_000775 | 3,631 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 5 | stack_v2_sparse_classes_30k_train_020988 | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run
Method signatures and do... | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run
Method signatures and do... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get a reference ... | the_stack_v2_python_sparse | plugins/ExamplePlugin/src/testInterfacedPP.py | idaholab/raven | train | 201 |
a0719ad11359de436c274462ec373fe162a6023a | [
"self.fieldname = fieldname\nif callable(model):\n model = model(searcher, fieldname)\nself.model = model\nterm_reader = searcher.term_reader\nself.collection_freq = dict(((word, freq) for word, _, freq in term_reader.iter_field(fieldname)))\nself.topN_weight = defaultdict(float)\nself.top_total = 0",
"total_w... | <|body_start_0|>
self.fieldname = fieldname
if callable(model):
model = model(searcher, fieldname)
self.model = model
term_reader = searcher.term_reader
self.collection_freq = dict(((word, freq) for word, _, freq in term_reader.iter_field(fieldname)))
self.top... | Uses an ExpansionModel to expand the set of query terms based on the top N result documents. | Expander | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Expander:
"""Uses an ExpansionModel to expand the set of query terms based on the top N result documents."""
def __init__(self, searcher, fieldname, model=Bo1Model):
""":param searcher: A searching.Searcher object for the index. :param fieldname: The name of the field in which to sea... | stack_v2_sparse_classes_36k_train_000776 | 5,552 | permissive | [
{
"docstring": ":param searcher: A searching.Searcher object for the index. :param fieldname: The name of the field in which to search. :param model: (classify.ExpansionModel) The model to use for expanding the query terms. If you omit this parameter, the expander uses scoring.Bo1Model by default.",
"name":... | 3 | null | Implement the Python class `Expander` described below.
Class description:
Uses an ExpansionModel to expand the set of query terms based on the top N result documents.
Method signatures and docstrings:
- def __init__(self, searcher, fieldname, model=Bo1Model): :param searcher: A searching.Searcher object for the index... | Implement the Python class `Expander` described below.
Class description:
Uses an ExpansionModel to expand the set of query terms based on the top N result documents.
Method signatures and docstrings:
- def __init__(self, searcher, fieldname, model=Bo1Model): :param searcher: A searching.Searcher object for the index... | 48b48ef9acf8e3d0eb7d52601a122a01da82075c | <|skeleton|>
class Expander:
"""Uses an ExpansionModel to expand the set of query terms based on the top N result documents."""
def __init__(self, searcher, fieldname, model=Bo1Model):
""":param searcher: A searching.Searcher object for the index. :param fieldname: The name of the field in which to sea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Expander:
"""Uses an ExpansionModel to expand the set of query terms based on the top N result documents."""
def __init__(self, searcher, fieldname, model=Bo1Model):
""":param searcher: A searching.Searcher object for the index. :param fieldname: The name of the field in which to search. :param m... | the_stack_v2_python_sparse | portal/libs/whoosh/classify.py | hernan0216/utopia-cms | train | 1 |
8da7f8a42b07cb657c235fa38af23f70d203b439 | [
"super(TopologyStatistics, self).__init__()\nself.internalDict = {'bestFitness': 0.0, 'fitness': 0.0, 'bestPosition': [], 'bestPosDim:': 0.0, 'position': []}\nself.descriptions = {'bestFitness': 'Best Fitness of the best Particle', 'fitness': 'Fitness of the best Particle', 'bestPosition': 'Best Position of the bes... | <|body_start_0|>
super(TopologyStatistics, self).__init__()
self.internalDict = {'bestFitness': 0.0, 'fitness': 0.0, 'bestPosition': [], 'bestPosDim:': 0.0, 'position': []}
self.descriptions = {'bestFitness': 'Best Fitness of the best Particle', 'fitness': 'Fitness of the best Particle', 'bestPo... | Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle **bestPosDim** Best First Dimmension Position ... | TopologyStatistics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle ... | stack_v2_sparse_classes_36k_train_000777 | 5,204 | no_license | [
{
"docstring": "The Topology Statistics Class Creator",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a string representation of the statistics",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005432 | Implement the Python class `TopologyStatistics` described below.
Class description:
Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and ... | Implement the Python class `TopologyStatistics` described below.
Class description:
Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and ... | ea1ef4cba0b5bddf1b7bf858e53c32aeb859655d | <|skeleton|>
class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle **bestPosDim*... | the_stack_v2_python_sparse | 0.12/FloatStatistics.py | ItaloAP/pypso | train | 0 |
344c8802e726c4f34c1b44a5ca96b12f859fb2cc | [
"match = {}\ngenerator = xml_root.iter()\nfor key in generator:\n if 'key' in key.tag and key_name in key.text:\n value_key = generator.next()\n value = ''\n for subkey in value_key.iter():\n if 'string' in subkey.tag:\n value = subkey.text\n match[key.text] ... | <|body_start_0|>
match = {}
generator = xml_root.iter()
for key in generator:
if 'key' in key.tag and key_name in key.text:
value_key = generator.next()
value = ''
for subkey in value_key.iter():
if 'string' in subke... | Class that defines the Mac OS X XML plist preprocess plugin object. | MacXMLPlistPreprocess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacXMLPlistPreprocess:
"""Class that defines the Mac OS X XML plist preprocess plugin object."""
def _GetKeys(self, xml_root, key_name):
"""Return a dict with the requested keys."""
<|body_0|>
def ParseFile(self, file_entry, file_object):
"""Parse the file and re... | stack_v2_sparse_classes_36k_train_000778 | 17,383 | permissive | [
{
"docstring": "Return a dict with the requested keys.",
"name": "_GetKeys",
"signature": "def _GetKeys(self, xml_root, key_name)"
},
{
"docstring": "Parse the file and return parsed key. Args: file_entry: The file entry (instance of dfvfs.FileEntry). file_object: The file-like object. Returns: ... | 2 | stack_v2_sparse_classes_30k_train_019634 | Implement the Python class `MacXMLPlistPreprocess` described below.
Class description:
Class that defines the Mac OS X XML plist preprocess plugin object.
Method signatures and docstrings:
- def _GetKeys(self, xml_root, key_name): Return a dict with the requested keys.
- def ParseFile(self, file_entry, file_object): ... | Implement the Python class `MacXMLPlistPreprocess` described below.
Class description:
Class that defines the Mac OS X XML plist preprocess plugin object.
Method signatures and docstrings:
- def _GetKeys(self, xml_root, key_name): Return a dict with the requested keys.
- def ParseFile(self, file_entry, file_object): ... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class MacXMLPlistPreprocess:
"""Class that defines the Mac OS X XML plist preprocess plugin object."""
def _GetKeys(self, xml_root, key_name):
"""Return a dict with the requested keys."""
<|body_0|>
def ParseFile(self, file_entry, file_object):
"""Parse the file and re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacXMLPlistPreprocess:
"""Class that defines the Mac OS X XML plist preprocess plugin object."""
def _GetKeys(self, xml_root, key_name):
"""Return a dict with the requested keys."""
match = {}
generator = xml_root.iter()
for key in generator:
if 'key' in key.ta... | the_stack_v2_python_sparse | plaso/preprocessors/interface.py | iwm911/plaso | train | 0 |
c87ead78bd14ca7ec3d015fdaab4213591348bb9 | [
"ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])\nret['id'] = self.key().id_or_name()\nret['items'] = self.items\nreturn ret",
"if description is None or description == '':\n raise ValueError(' description not set')\nproduct = None\nif key is not None:\n product = Product.get_by_id(i... | <|body_start_0|>
ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
ret['id'] = self.key().id_or_name()
ret['items'] = self.items
return ret
<|end_body_0|>
<|body_start_1|>
if description is None or description == '':
raise ValueError(' descripti... | Model class for ShoppingList | ShoppingList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
<|body_0|>
def add_item(self, description, key, quantity):
"""Add an item to the list"""
<|body_1|>
def get_items(self):
"""Get all items"""
... | stack_v2_sparse_classes_36k_train_000779 | 3,485 | no_license | [
{
"docstring": "For JSON serialization",
"name": "to_dict",
"signature": "def to_dict(self)"
},
{
"docstring": "Add an item to the list",
"name": "add_item",
"signature": "def add_item(self, description, key, quantity)"
},
{
"docstring": "Get all items",
"name": "get_items",
... | 5 | stack_v2_sparse_classes_30k_train_010450 | Implement the Python class `ShoppingList` described below.
Class description:
Model class for ShoppingList
Method signatures and docstrings:
- def to_dict(self): For JSON serialization
- def add_item(self, description, key, quantity): Add an item to the list
- def get_items(self): Get all items
- def delete_item(self... | Implement the Python class `ShoppingList` described below.
Class description:
Model class for ShoppingList
Method signatures and docstrings:
- def to_dict(self): For JSON serialization
- def add_item(self, description, key, quantity): Add an item to the list
- def get_items(self): Get all items
- def delete_item(self... | 394b4821b65191df221d62f807ba2895f38e86a3 | <|skeleton|>
class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
<|body_0|>
def add_item(self, description, key, quantity):
"""Add an item to the list"""
<|body_1|>
def get_items(self):
"""Get all items"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
ret['id'] = self.key().id_or_name()
ret['items'] = self.items
return ret
def add_item(self,... | the_stack_v2_python_sparse | model/shoppinglist.py | szilardhuber/shopper | train | 1 |
344c8802e726c4f34c1b44a5ca96b12f859fb2cc | [
"file_entry = self._FindFileEntry(searcher, self.PLIST_PATH)\nif not file_entry:\n raise errors.PreProcessFail(u'Unable to open file: {0:s}'.format(self.PLIST_PATH))\nfile_object = file_entry.GetFileObject()\nvalue = self.ParseFile(file_entry, file_object)\nfile_object.close()\nreturn value",
"try:\n plist_... | <|body_start_0|>
file_entry = self._FindFileEntry(searcher, self.PLIST_PATH)
if not file_entry:
raise errors.PreProcessFail(u'Unable to open file: {0:s}'.format(self.PLIST_PATH))
file_object = file_entry.GetFileObject()
value = self.ParseFile(file_entry, file_object)
... | Class that defines the Mac OS X plist preprocess plugin object. | MacPlistPreprocess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacPlistPreprocess:
"""Class that defines the Mac OS X plist preprocess plugin object."""
def GetValue(self, searcher):
"""Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST_KEYS. Args: searcher: The file system searcher object (i... | stack_v2_sparse_classes_36k_train_000780 | 17,383 | permissive | [
{
"docstring": "Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST_KEYS. Args: searcher: The file system searcher object (instance of dfvfs.FileSystemSearcher). Returns: The value of the first key that is found. Raises: errors.PreProcessFail: if the preproce... | 3 | stack_v2_sparse_classes_30k_train_000127 | Implement the Python class `MacPlistPreprocess` described below.
Class description:
Class that defines the Mac OS X plist preprocess plugin object.
Method signatures and docstrings:
- def GetValue(self, searcher): Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST... | Implement the Python class `MacPlistPreprocess` described below.
Class description:
Class that defines the Mac OS X plist preprocess plugin object.
Method signatures and docstrings:
- def GetValue(self, searcher): Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class MacPlistPreprocess:
"""Class that defines the Mac OS X plist preprocess plugin object."""
def GetValue(self, searcher):
"""Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST_KEYS. Args: searcher: The file system searcher object (i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacPlistPreprocess:
"""Class that defines the Mac OS X plist preprocess plugin object."""
def GetValue(self, searcher):
"""Returns a value retrieved from keys within a plist file. Where the name of the keys are defined in PLIST_KEYS. Args: searcher: The file system searcher object (instance of df... | the_stack_v2_python_sparse | plaso/preprocessors/interface.py | iwm911/plaso | train | 0 |
d71dc2f1a3351639ea8c3e0b6aa5060781363e2d | [
"parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style')\nparser.add_argument('style', type=str, help='style, ggplot for exemple', default='ggplot')\nreturn parser",
"parser = self.get_parser(MagicGraph.mpl_style_parser, 'mpl_style')\nargs = self.get_args(line, parser)\nif args is no... | <|body_start_0|>
parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style')
parser.add_argument('style', type=str, help='style, ggplot for exemple', default='ggplot')
return parser
<|end_body_0|>
<|body_start_1|>
parser = self.get_parser(MagicGraph.mpl_style_p... | Defines magic commands about graphs .. versionadded:: 1.1 | MagicGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicGraph:
"""Defines magic commands about graphs .. versionadded:: 1.1"""
def mpl_style_parser():
"""defines the way to parse the magic command ``%mpl_style``"""
<|body_0|>
def mpl_style(self, line):
"""defines ``%mpl_style`` which changes the style of matplotl... | stack_v2_sparse_classes_36k_train_000781 | 1,955 | permissive | [
{
"docstring": "defines the way to parse the magic command ``%mpl_style``",
"name": "mpl_style_parser",
"signature": "def mpl_style_parser()"
},
{
"docstring": "defines ``%mpl_style`` which changes the style of matplotlib graphs, example: ``%mpl_style ggplot`` .. nbref:: :title: mpl_style This m... | 2 | stack_v2_sparse_classes_30k_train_004329 | Implement the Python class `MagicGraph` described below.
Class description:
Defines magic commands about graphs .. versionadded:: 1.1
Method signatures and docstrings:
- def mpl_style_parser(): defines the way to parse the magic command ``%mpl_style``
- def mpl_style(self, line): defines ``%mpl_style`` which changes ... | Implement the Python class `MagicGraph` described below.
Class description:
Defines magic commands about graphs .. versionadded:: 1.1
Method signatures and docstrings:
- def mpl_style_parser(): defines the way to parse the magic command ``%mpl_style``
- def mpl_style(self, line): defines ``%mpl_style`` which changes ... | 33af98adb093f525df7fac7c86613fa7cd181b44 | <|skeleton|>
class MagicGraph:
"""Defines magic commands about graphs .. versionadded:: 1.1"""
def mpl_style_parser():
"""defines the way to parse the magic command ``%mpl_style``"""
<|body_0|>
def mpl_style(self, line):
"""defines ``%mpl_style`` which changes the style of matplotl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagicGraph:
"""Defines magic commands about graphs .. versionadded:: 1.1"""
def mpl_style_parser():
"""defines the way to parse the magic command ``%mpl_style``"""
parser = MagicCommandParser(description='changes matplotlib style', prog='mpl_style')
parser.add_argument('style', ty... | the_stack_v2_python_sparse | src/pyensae/graphhelper/magic_graph.py | sdpython/pyensae | train | 33 |
f1c9c63a6772bda35746e2885fdfc74470b03d63 | [
"for k, v in kwargs.items():\n if not hasattr(self, k):\n warnings.warn('\\nWarning: opt has not attribut %s' % k)\n setattr(self, k, v)\nif self.print_config == True:\n print('user config:')\n for k, v in self.__class__.__dict__.items():\n if not k.startswith('__'):\n print(k, ... | <|body_start_0|>
for k, v in kwargs.items():
if not hasattr(self, k):
warnings.warn('\nWarning: opt has not attribut %s' % k)
setattr(self, k, v)
if self.print_config == True:
print('user config:')
for k, v in self.__class__.__dict__.items(... | TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root) | Configuration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config ... | stack_v2_sparse_classes_36k_train_000782 | 5,691 | no_license | [
{
"docstring": "根据字典kwargs 更新 config 参数 config = Configuration() new_config = {'lr':0.1,'use_gpu':False} config.update_config(new_config) config.lr == 0.1",
"name": "update_config",
"signature": "def update_config(self, kwargs)"
},
{
"docstring": "自动检测config配置是否合理",
"name": "check_config",
... | 2 | stack_v2_sparse_classes_30k_train_020030 | Implement the Python class `Configuration` described below.
Class description:
TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)
Method signatures and docstrings:
- def upd... | Implement the Python class `Configuration` described below.
Class description:
TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)
Method signatures and docstrings:
- def upd... | 2d34ec72c2358a5bf4dd0b2855a7900fbb8feae7 | <|skeleton|>
class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configuration:
"""TODO 舍弃此类直接传args 使用范例: import models from config import Configuration config = Configuration() lr = config.lr model = getattr(models, config.arch) dataset = DogCat_dataset(config.train_data_root)"""
def update_config(self, kwargs):
"""根据字典kwargs 更新 config 参数 config = Configurati... | the_stack_v2_python_sparse | utils/config.py | meetsiyuan/MCTS | train | 0 |
accc97c0608a76a93dd8942a07ba74b2d946ff43 | [
"if n < 1:\n return 0\nif n < 2:\n return 1\ndp = [1] * m\nfor _ in range(2, n):\n for i in range(1, m):\n dp[i] += dp[i - 1]\nreturn sum(dp)",
"def combination(n, k):\n ret = 1\n while k > 0:\n ret *= n / k\n n -= 1\n k -= 1\n return ret\nif n < 1:\n return 0\nif ... | <|body_start_0|>
if n < 1:
return 0
if n < 2:
return 1
dp = [1] * m
for _ in range(2, n):
for i in range(1, m):
dp[i] += dp[i - 1]
return sum(dp)
<|end_body_0|>
<|body_start_1|>
def combination(n, k):
ret = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths_1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
def uniquePaths_2(self, m, n):
""":type m: int :type n: int :rtype... | stack_v2_sparse_classes_36k_train_000783 | 1,946 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths_1",
"signature": "def uniquePaths_1(self, m, n)"
},
{
"docstring": ":type m: i... | 3 | stack_v2_sparse_classes_30k_train_015703 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_1(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_2(self, m, n): :type m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_1(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths_2(self, m, n): :type m... | 9fa6f81d8968dea51c255a6f92708cfc6bafb057 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths_1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
def uniquePaths_2(self, m, n):
""":type m: int :type n: int :rtype... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
if n < 1:
return 0
if n < 2:
return 1
dp = [1] * m
for _ in range(2, n):
for i in range(1, m):
dp[i] += dp[i - 1]
return sum(dp... | the_stack_v2_python_sparse | 62. Unique Paths.py | ChihaoFeng/Leetcode | train | 0 | |
5892b812a1567363c1e04a041948d8a1f91997f9 | [
"self.pq = nums\nself.k = k\nheapify(self.pq)\nwhile len(self.pq) > k:\n heappop(self.pq)",
"heappush(self.pq, val)\nwhile len(self.pq) > self.k:\n heappop(self.pq)\nreturn self.pq[0]"
] | <|body_start_0|>
self.pq = nums
self.k = k
heapify(self.pq)
while len(self.pq) > k:
heappop(self.pq)
<|end_body_0|>
<|body_start_1|>
heappush(self.pq, val)
while len(self.pq) > self.k:
heappop(self.pq)
return self.pq[0]
<|end_body_1|>
| KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pq = nums
self.k = k
heapify(self.pq)... | stack_v2_sparse_classes_36k_train_000784 | 936 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018345 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 76d767ec001649b2df07aac211ac4b43b415ebdd | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.pq = nums
self.k = k
heapify(self.pq)
while len(self.pq) > k:
heappop(self.pq)
def add(self, val):
""":type val: int :rtype: int"""
heappush(self.pq, ... | the_stack_v2_python_sparse | leetcode703 Kth Largest Element in a Stream.py | whglamrock/leetcode_series | train | 2 | |
ba46b2f01f4abecdb95c16af0c9daf99f98fa17d | [
"super(MutanFusion, self).__init__()\nself.mm_hidden_size = mm_hidden_size\nself.R = R\nself.linear_v = nn.Linear(I_input_hidden, I_core_hidden)\nself.linear_q = nn.Linear(T_input_hidden, T_core_hidden)\nself.list_linear_hv = nn.ModuleList([nn.Linear(I_core_hidden, mm_hidden_size) for _ in range(R)])\nself.list_lin... | <|body_start_0|>
super(MutanFusion, self).__init__()
self.mm_hidden_size = mm_hidden_size
self.R = R
self.linear_v = nn.Linear(I_input_hidden, I_core_hidden)
self.linear_q = nn.Linear(T_input_hidden, T_core_hidden)
self.list_linear_hv = nn.ModuleList([nn.Linear(I_core_hid... | MutanFusion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MutanFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=510, T_core_hidden=310, I_core_hidden=310, T_activate_func=gelu, I_activate_func=gelu, T_core_activate=gelu, I_core_activate=gelu, mm_activate=gelu, dropout_T=0.5, dropout_I=0.5, dropout_core_T=0, dropout_core_I=0, R=... | stack_v2_sparse_classes_36k_train_000785 | 5,761 | no_license | [
{
"docstring": ":param T_input_hidden: Text input hidden size :param I_input_hidden: Image input hidden size :param mm_hidden_size: output multi-modal feature size :param T_core_hidden: Text core hidden size :param I_core_hidden: Image core hidden size :param T_activate_func: Text activate function, should be c... | 2 | stack_v2_sparse_classes_30k_train_003242 | Implement the Python class `MutanFusion` described below.
Class description:
Implement the MutanFusion class.
Method signatures and docstrings:
- def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=510, T_core_hidden=310, I_core_hidden=310, T_activate_func=gelu, I_activate_func=gelu, T_core_activate=gel... | Implement the Python class `MutanFusion` described below.
Class description:
Implement the MutanFusion class.
Method signatures and docstrings:
- def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=510, T_core_hidden=310, I_core_hidden=310, T_activate_func=gelu, I_activate_func=gelu, T_core_activate=gel... | 6209dc7a9f17e52dd570bbcbd1c9829a2b14f52c | <|skeleton|>
class MutanFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=510, T_core_hidden=310, I_core_hidden=310, T_activate_func=gelu, I_activate_func=gelu, T_core_activate=gelu, I_core_activate=gelu, mm_activate=gelu, dropout_T=0.5, dropout_I=0.5, dropout_core_T=0, dropout_core_I=0, R=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MutanFusion:
def __init__(self, T_input_hidden, I_input_hidden, mm_hidden_size=510, T_core_hidden=310, I_core_hidden=310, T_activate_func=gelu, I_activate_func=gelu, T_core_activate=gelu, I_core_activate=gelu, mm_activate=gelu, dropout_T=0.5, dropout_I=0.5, dropout_core_T=0, dropout_core_I=0, R=5):
""... | the_stack_v2_python_sparse | models/base/modal_fusion.py | yiranyyu/Phrase-Grounding | train | 2 | |
cb6b044cd157acc45f2cd6807f1f8d5f258d7837 | [
"from clubs.club_service import ClubService\nclub_service: ClubService = services.get_club_service()\nif club_service is None:\n return tuple()\nfor club in club_service.clubs_to_gatherings_map.keys():\n if club is None or not include_club_callback(club):\n continue\n yield club",
"from sims4commu... | <|body_start_0|>
from clubs.club_service import ClubService
club_service: ClubService = services.get_club_service()
if club_service is None:
return tuple()
for club in club_service.clubs_to_gatherings_map.keys():
if club is None or not include_club_callback(club):... | Utilities for manipulating Clubs. | CommonClubUtils | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonClubUtils:
"""Utilities for manipulating Clubs."""
def get_clubs_currently_gathering_gen(include_club_callback: Callable[[Club], bool]=CommonFunctionUtils.noop_true) -> Iterator[Club]:
"""get_clubs_currently_gathering_gen(include_club_callback=CommonFunctionUtils.noop_true) Ret... | stack_v2_sparse_classes_36k_train_000786 | 3,719 | permissive | [
{
"docstring": "get_clubs_currently_gathering_gen(include_club_callback=CommonFunctionUtils.noop_true) Retrieve all Clubs that are currently hosting a gathering. :param include_club_callback: If the result of this callback is True, the Club will be included in the results. The default callback will allow all. :... | 3 | null | Implement the Python class `CommonClubUtils` described below.
Class description:
Utilities for manipulating Clubs.
Method signatures and docstrings:
- def get_clubs_currently_gathering_gen(include_club_callback: Callable[[Club], bool]=CommonFunctionUtils.noop_true) -> Iterator[Club]: get_clubs_currently_gathering_gen... | Implement the Python class `CommonClubUtils` described below.
Class description:
Utilities for manipulating Clubs.
Method signatures and docstrings:
- def get_clubs_currently_gathering_gen(include_club_callback: Callable[[Club], bool]=CommonFunctionUtils.noop_true) -> Iterator[Club]: get_clubs_currently_gathering_gen... | 58e7beb30b9c818b294d35abd2436a0192cd3e82 | <|skeleton|>
class CommonClubUtils:
"""Utilities for manipulating Clubs."""
def get_clubs_currently_gathering_gen(include_club_callback: Callable[[Club], bool]=CommonFunctionUtils.noop_true) -> Iterator[Club]:
"""get_clubs_currently_gathering_gen(include_club_callback=CommonFunctionUtils.noop_true) Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonClubUtils:
"""Utilities for manipulating Clubs."""
def get_clubs_currently_gathering_gen(include_club_callback: Callable[[Club], bool]=CommonFunctionUtils.noop_true) -> Iterator[Club]:
"""get_clubs_currently_gathering_gen(include_club_callback=CommonFunctionUtils.noop_true) Retrieve all Clu... | the_stack_v2_python_sparse | Scripts/sims4communitylib/utils/resources/common_club_utils.py | ColonolNutty/Sims4CommunityLibrary | train | 183 |
7765417b154295436de374aebf9f67ad1befcddb | [
"LogTool.info(f'网络get发包:url:【{url}】, payload:【{payload}】')\nauth_header = request.headers.get('Authorization')\nappCode = request.headers.get('Application')\nif headers is None:\n headers = {}\nif not headers.__contains__('Authorization'):\n headers['Authorization'] = auth_header\nif not headers.__contains__(... | <|body_start_0|>
LogTool.info(f'网络get发包:url:【{url}】, payload:【{payload}】')
auth_header = request.headers.get('Authorization')
appCode = request.headers.get('Application')
if headers is None:
headers = {}
if not headers.__contains__('Authorization'):
header... | HttpTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpTool:
def request_get(url, payload, headers=None):
"""请求get :param url: :param payload: :return:"""
<|body_0|>
def request_post(url, payload, headers=None):
"""请求post :param url: :param payload: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000787 | 2,179 | no_license | [
{
"docstring": "请求get :param url: :param payload: :return:",
"name": "request_get",
"signature": "def request_get(url, payload, headers=None)"
},
{
"docstring": "请求post :param url: :param payload: :return:",
"name": "request_post",
"signature": "def request_post(url, payload, headers=Non... | 2 | stack_v2_sparse_classes_30k_val_000150 | Implement the Python class `HttpTool` described below.
Class description:
Implement the HttpTool class.
Method signatures and docstrings:
- def request_get(url, payload, headers=None): 请求get :param url: :param payload: :return:
- def request_post(url, payload, headers=None): 请求post :param url: :param payload: :return... | Implement the Python class `HttpTool` described below.
Class description:
Implement the HttpTool class.
Method signatures and docstrings:
- def request_get(url, payload, headers=None): 请求get :param url: :param payload: :return:
- def request_post(url, payload, headers=None): 请求post :param url: :param payload: :return... | 4bb0ab793c119153e9ee476274d8908c23e33a30 | <|skeleton|>
class HttpTool:
def request_get(url, payload, headers=None):
"""请求get :param url: :param payload: :return:"""
<|body_0|>
def request_post(url, payload, headers=None):
"""请求post :param url: :param payload: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpTool:
def request_get(url, payload, headers=None):
"""请求get :param url: :param payload: :return:"""
LogTool.info(f'网络get发包:url:【{url}】, payload:【{payload}】')
auth_header = request.headers.get('Authorization')
appCode = request.headers.get('Application')
if headers i... | the_stack_v2_python_sparse | python_wheel/lbj_flask/lbj_flask/http_tool.py | libaojie/python_package | train | 0 | |
eab742be4efa01cb84f5fa858663c70b9d639534 | [
"now_date = datetime.now(timezone.utc)\nif object.aktif:\n pub_date = object.yaratilma_tarihi\n return timesince(pub_date, now_date)\nelse:\n return 'Makale aktif değil, lütfen ilk önce makaleyi aktif ediniz.'",
"if pub_date > date.today():\n raise serializers.ValidationError('Yayımlanma tarihi ileri ... | <|body_start_0|>
now_date = datetime.now(timezone.utc)
if object.aktif:
pub_date = object.yaratilma_tarihi
return timesince(pub_date, now_date)
else:
return 'Makale aktif değil, lütfen ilk önce makaleyi aktif ediniz.'
<|end_body_0|>
<|body_start_1|>
i... | ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz. | MakaleSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakaleSerializer:
"""ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz."""
def get_time_pub(self, object):
"""Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplayıp json içerisinde yeni bir attribute olarak gösterebildi... | stack_v2_sparse_classes_36k_train_000788 | 4,989 | no_license | [
{
"docstring": "Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplayıp json içerisinde yeni bir attribute olarak gösterebildiğimiz fonksiyon.",
"name": "get_time_pub",
"signature": "def get_time_pub(self, object)"
},
{
"docstring": "Field Validation. Ileri bir yayım... | 2 | null | Implement the Python class `MakaleSerializer` described below.
Class description:
ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz.
Method signatures and docstrings:
- def get_time_pub(self, object): Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplay... | Implement the Python class `MakaleSerializer` described below.
Class description:
ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz.
Method signatures and docstrings:
- def get_time_pub(self, object): Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplay... | 3c055f8698ac777bf44c294046ed8c0aa59ee247 | <|skeleton|>
class MakaleSerializer:
"""ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz."""
def get_time_pub(self, object):
"""Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplayıp json içerisinde yeni bir attribute olarak gösterebildi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MakaleSerializer:
"""ModelSerializer ile daha kolay ve hızlı bir biçimde serializer'ımızı oluşturabiliriz."""
def get_time_pub(self, object):
"""Object Validation. Yaratılma tarihinin üzerinden ne kadar zaman geçtiğini hesaplayıp json içerisinde yeni bir attribute olarak gösterebildiğimiz fonksiy... | the_stack_v2_python_sparse | Django Apps/haber_djangorest/main/api/serializers.py | uysalserkan/Python-Topics | train | 4 |
77d92deed2a32c6d004bb4c144cdd0398f6afdad | [
"self.__n = N - len(blacklist)\nblacklist.sort()\nself.__blacklist = blacklist",
"index = random.randint(0, self.__n - 1)\nleft, right = (0, len(self.__blacklist) - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n if index + mid < self.__blacklist[mid]:\n right = mid - 1\n else:\n ... | <|body_start_0|>
self.__n = N - len(blacklist)
blacklist.sort()
self.__blacklist = blacklist
<|end_body_0|>
<|body_start_1|>
index = random.randint(0, self.__n - 1)
left, right = (0, len(self.__blacklist) - 1)
while left <= right:
mid = left + (right - left) ... | Solution2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.__n = N - len(blacklist)
blacklist.sort()
self.... | stack_v2_sparse_classes_36k_train_000789 | 1,375 | permissive | [
{
"docstring": ":type N: int :type blacklist: List[int]",
"name": "__init__",
"signature": "def __init__(self, N, blacklist)"
},
{
"docstring": ":rtype: int",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int
<|skeleton|>
class Solution2:
def __init__(self, N, blacklist):
... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class Solution2:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
self.__n = N - len(blacklist)
blacklist.sort()
self.__blacklist = blacklist
def pick(self):
""":rtype: int"""
index = random.randint(0, self.__n - 1)
left, ri... | the_stack_v2_python_sparse | Python/random-pick-with-blacklist.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
971732a3eb9197bc8edc5506f5308d2615bd7cea | [
"max_count = 0\ninvalid_index = -1\nstack = []\nfor i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n elif stack:\n stack.pop()\n start_index = stack[-1] if stack else invalid_index\n max_count = max(max_count, i - start_index)\n else:\n invalid_index = i\nreturn ... | <|body_start_0|>
max_count = 0
invalid_index = -1
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif stack:
stack.pop()
start_index = stack[-1] if stack else invalid_index
max_cou... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses_failed(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_count = 0
invalid_index = ... | stack_v2_sparse_classes_36k_train_000790 | 2,271 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses_failed",
"signature": "def longestValidParentheses_failed(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016412 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses_failed(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses_failed(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def long... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses_failed(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
max_count = 0
invalid_index = -1
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif stack:
stack.pop()
... | the_stack_v2_python_sparse | src/lt_32.py | oxhead/CodingYourWay | train | 0 | |
bbd3b6ad755f33ed2fd310cae77d4a60e7a53ff4 | [
"if period is not None and permutation_table is not None:\n raise ValueError('Can specify either period or permutation_table, not both')\nif period is not None:\n self.randomize(period)\nelif permutation_table is not None:\n self.permutation = tuple(permutation_table) * 2\n self.period = len(permutation... | <|body_start_0|>
if period is not None and permutation_table is not None:
raise ValueError('Can specify either period or permutation_table, not both')
if period is not None:
self.randomize(period)
elif permutation_table is not None:
self.permutation = tuple(pe... | Noise abstract base class | BaseNoise | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseNoise:
"""Noise abstract base class"""
def __init__(self, period=None, permutation_table=None):
"""Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each... | stack_v2_sparse_classes_36k_train_000791 | 15,176 | permissive | [
{
"docstring": "Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each time. An integer period can be specified, to generate a random permutation table with period elements. The period ... | 2 | null | Implement the Python class `BaseNoise` described below.
Class description:
Noise abstract base class
Method signatures and docstrings:
- def __init__(self, period=None, permutation_table=None): Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default perm... | Implement the Python class `BaseNoise` described below.
Class description:
Noise abstract base class
Method signatures and docstrings:
- def __init__(self, period=None, permutation_table=None): Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default perm... | ba6ab0264dcb6833173042a37b1b5ae878d75113 | <|skeleton|>
class BaseNoise:
"""Noise abstract base class"""
def __init__(self, period=None, permutation_table=None):
"""Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseNoise:
"""Noise abstract base class"""
def __init__(self, period=None, permutation_table=None):
"""Initialize the noise generator. With no arguments, the default period and permutation table are used (256). The default permutation table generates the exact same noise pattern each time. An int... | the_stack_v2_python_sparse | src/ezdxf/math/perlin.py | mozman/ezdxf | train | 750 |
ac24a5e6b8ee0cf2779c92c0cae2db5a021dca16 | [
"if not email:\n raise ValueError('Users must have an email address')\nfull_name = kwargs.get('full_name', None)\nuser = self.model(email=self.normalize_email(email), cell_phone_number=cell_phone_number, is_student=is_student, full_name=full_name)\nexisting = retrieve_existing_hackerspace_member(email)\nuser.is_... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
full_name = kwargs.get('full_name', None)
user = self.model(email=self.normalize_email(email), cell_phone_number=cell_phone_number, is_student=is_student, full_name=full_name)
existing = retri... | HsUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HsUserManager:
def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, cell_phone_number, is_student, passwo... | stack_v2_sparse_classes_36k_train_000792 | 4,995 | permissive | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs)"
},
{
"docstring": "Creates and saves a superuser with the given email... | 2 | stack_v2_sparse_classes_30k_train_011495 | Implement the Python class `HsUserManager` described below.
Class description:
Implement the HsUserManager class.
Method signatures and docstrings:
- def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs): Creates and saves a User with the given email, date of birth and passwo... | Implement the Python class `HsUserManager` described below.
Class description:
Implement the HsUserManager class.
Method signatures and docstrings:
- def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs): Creates and saves a User with the given email, date of birth and passwo... | 24f9b4959873e1f662d07759925a0a59f4912512 | <|skeleton|>
class HsUserManager:
def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, cell_phone_number, is_student, passwo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HsUserManager:
def create_user(self, email, cell_phone_number, is_student, full_name, password=None, **kwargs):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
full_name = kw... | the_stack_v2_python_sparse | src/members/models.py | sanfx/Hackerhane | train | 0 | |
22421d3003c3fc1ed5bfa4d216d290d17e15fb48 | [
"index_array = []\nrc_arr = []\nfor ind in range(0, len(A)):\n index_array.append(ind)\n rc_arr.append(0)\nself.sort(A, index_array, 0, len(index_array) - 1, rc_arr)\nreturn rc_arr",
"left = ind[p:q + 1]\nright = ind[q + 1:r + 1]\ni = 0\nj = 0\nic = 0\nk = p\nwhile i < len(left) and j < len(right):\n if ... | <|body_start_0|>
index_array = []
rc_arr = []
for ind in range(0, len(A)):
index_array.append(ind)
rc_arr.append(0)
self.sort(A, index_array, 0, len(index_array) - 1, rc_arr)
return rc_arr
<|end_body_0|>
<|body_start_1|>
left = ind[p:q + 1]
... | InversionCount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
<|body_0|>
def merge(self, A, ind, p, q, r, rc_array):
"""This method does the same work as mergeSort but we will be checking for the inversion a... | stack_v2_sparse_classes_36k_train_000793 | 1,753 | permissive | [
{
"docstring": "Count and return the array containing the count of each element",
"name": "count",
"signature": "def count(self, A: [int]) -> [int]"
},
{
"docstring": "This method does the same work as mergeSort but we will be checking for the inversion and increase the count",
"name": "merg... | 3 | stack_v2_sparse_classes_30k_train_009877 | Implement the Python class `InversionCount` described below.
Class description:
Implement the InversionCount class.
Method signatures and docstrings:
- def count(self, A: [int]) -> [int]: Count and return the array containing the count of each element
- def merge(self, A, ind, p, q, r, rc_array): This method does the... | Implement the Python class `InversionCount` described below.
Class description:
Implement the InversionCount class.
Method signatures and docstrings:
- def count(self, A: [int]) -> [int]: Count and return the array containing the count of each element
- def merge(self, A, ind, p, q, r, rc_array): This method does the... | a30008a7fa8ba15ee241bd7fc5df94cd68c80003 | <|skeleton|>
class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
<|body_0|>
def merge(self, A, ind, p, q, r, rc_array):
"""This method does the same work as mergeSort but we will be checking for the inversion a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InversionCount:
def count(self, A: [int]) -> [int]:
"""Count and return the array containing the count of each element"""
index_array = []
rc_arr = []
for ind in range(0, len(A)):
index_array.append(ind)
rc_arr.append(0)
self.sort(A, index_array,... | the_stack_v2_python_sparse | InversionCount.py | vinayakasg18/algorithms | train | 0 | |
819674d5e05cf27fe2231226df71d5dab1ba776d | [
"s.replace(' ', '')\nmatch = {'(': ')', '[': ']', '{': '}'}\nun_match = []\nfor i in s:\n if un_match:\n u = un_match[-1]\n if u not in match.keys():\n return False\n if match[u] == i:\n un_match = un_match[0:-1]\n else:\n un_match.append(i)\n else:... | <|body_start_0|>
s.replace(' ', '')
match = {'(': ')', '[': ']', '{': '}'}
un_match = []
for i in s:
if un_match:
u = un_match[-1]
if u not in match.keys():
return False
if match[u] == i:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s.replace(' ', '')
match = {'(': ')', '[': ']', '{': '}'}
... | stack_v2_sparse_classes_36k_train_000794 | 1,259 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid2",
"signature": "def isValid2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s): :type s: str :rtype: bool
- def isValid2(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, s): :type s: str :rtype: bool
- def isValid2(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isValid(self, s):
""":type s: st... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid2(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid(self, s):
""":type s: str :rtype: bool"""
s.replace(' ', '')
match = {'(': ')', '[': ']', '{': '}'}
un_match = []
for i in s:
if un_match:
u = un_match[-1]
if u not in match.keys():
re... | the_stack_v2_python_sparse | 初级算法/isValid.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
1a89821dfb9c81a24c2a14bbe5c1ab3db20ab1d9 | [
"app_label, model_name = get_app_label_and_model_name(self.data.model)\nmodel = get_model(app_label, model_name)\nqueryset = model._default_manager.all()\nfield_kwargs = {'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'queryset': queryset, '... | <|body_start_0|>
app_label, model_name = get_app_label_and_model_name(self.data.model)
model = get_model(app_label, model_name)
queryset = model._default_manager.all()
field_kwargs = {'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': se... | Select multiple MPTT model object field plugin. | SelectMultipleMPTTModelObjectsInputPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
<|body_0|>
def submit_plugin_form_data... | stack_v2_sparse_classes_36k_train_000795 | 3,976 | permissive | [
{
"docstring": "Get form field instances.",
"name": "get_form_field_instances",
"signature": "def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs)"
},
{
"docstring": "Submit plugin form data/process. :param fobi.models.FormEntry form_entry: Insta... | 2 | stack_v2_sparse_classes_30k_train_020606 | Implement the Python class `SelectMultipleMPTTModelObjectsInputPlugin` described below.
Class description:
Select multiple MPTT model object field plugin.
Method signatures and docstrings:
- def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): Get form field instance... | Implement the Python class `SelectMultipleMPTTModelObjectsInputPlugin` described below.
Class description:
Select multiple MPTT model object field plugin.
Method signatures and docstrings:
- def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): Get form field instance... | 4f6ca37bc600dcba3f74400d299826882d53b7d2 | <|skeleton|>
class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
<|body_0|>
def submit_plugin_form_data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelectMultipleMPTTModelObjectsInputPlugin:
"""Select multiple MPTT model object field plugin."""
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs):
"""Get form field instances."""
app_label, model_name = get_app_label_and_model_name(sel... | the_stack_v2_python_sparse | events/contrib/plugins/form_elements/fields/select_multiple_mptt_model_objects/base.py | mansonul/events | train | 0 |
c7b0111fe1e8c6915cc8c2ff851ea1e75bbcd7d9 | [
"self.objClsMqttManager = objClsMqttManagerPar\nself.objClsProcessing = clsProcessing(E_WEBMM_PROCESSES.I_MAIN_PROCESS.value)\nself.objClsMqttManager.vSubscribe(self.objClsProcessing.lstGetSubMqttTopic(acMsgKeyPar), self)",
"try:\n self.objClsMqttManager.vSend(acTopicPar, lstPayloadPar)\nexcept Exception as E:... | <|body_start_0|>
self.objClsMqttManager = objClsMqttManagerPar
self.objClsProcessing = clsProcessing(E_WEBMM_PROCESSES.I_MAIN_PROCESS.value)
self.objClsMqttManager.vSubscribe(self.objClsProcessing.lstGetSubMqttTopic(acMsgKeyPar), self)
<|end_body_0|>
<|body_start_1|>
try:
se... | This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml | clsMqttComms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class clsMqttComms:
"""This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml"""
def __init__(self, objClsMqttManagerPar, acMsgKeyPar):
"""Constructor: get all message t... | stack_v2_sparse_classes_36k_train_000796 | 2,301 | no_license | [
{
"docstring": "Constructor: get all message topics of the xml and subscribe.",
"name": "__init__",
"signature": "def __init__(self, objClsMqttManagerPar, acMsgKeyPar)"
},
{
"docstring": "This method is called when sending data. Args: topic (string: message topic. lstPayloadPar (list): message p... | 3 | stack_v2_sparse_classes_30k_train_001883 | Implement the Python class `clsMqttComms` described below.
Class description:
This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml
Method signatures and docstrings:
- def __init__(self, objClsMqt... | Implement the Python class `clsMqttComms` described below.
Class description:
This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml
Method signatures and docstrings:
- def __init__(self, objClsMqt... | dfea990cda5553de5c95c03f4c157934dbd00d19 | <|skeleton|>
class clsMqttComms:
"""This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml"""
def __init__(self, objClsMqttManagerPar, acMsgKeyPar):
"""Constructor: get all message t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class clsMqttComms:
"""This is a class is used for MQTT comms and inherits from the clsCommsManager Args: objClsMqttManagerPar (mqtt class object): acMsgKeyPar (string): any message key from the xml"""
def __init__(self, objClsMqttManagerPar, acMsgKeyPar):
"""Constructor: get all message topics of the ... | the_stack_v2_python_sparse | webmms/Source/BackEnd/Comms/comms_manager.py | Tee-kay125/homeAppUsers | train | 0 |
725e4d0467b321246204125762617869a830bbbd | [
"if not self.is_empty():\n for p in self._subtree_preorder(self.root()):\n yield p",
"for c in self.children(p):\n for other in self._subtree_preorder(c):\n yield other\nyield p"
] | <|body_start_0|>
if not self.is_empty():
for p in self._subtree_preorder(self.root()):
yield p
<|end_body_0|>
<|body_start_1|>
for c in self.children(p):
for other in self._subtree_preorder(c):
yield other
yield p
<|end_body_1|>
| TreeTraversals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
<|body_0|>
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positions in subtree rooted at p."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_000797 | 740 | permissive | [
{
"docstring": "Generate a postorder iteration of positions in the tree.",
"name": "postorder",
"signature": "def postorder(self)"
},
{
"docstring": "Generate a postorder iteration of positions in subtree rooted at p.",
"name": "_subtre_postorder",
"signature": "def _subtre_postorder(sel... | 2 | stack_v2_sparse_classes_30k_train_020204 | Implement the Python class `TreeTraversals` described below.
Class description:
Implement the TreeTraversals class.
Method signatures and docstrings:
- def postorder(self): Generate a postorder iteration of positions in the tree.
- def _subtre_postorder(self, p): Generate a postorder iteration of positions in subtree... | Implement the Python class `TreeTraversals` described below.
Class description:
Implement the TreeTraversals class.
Method signatures and docstrings:
- def postorder(self): Generate a postorder iteration of positions in the tree.
- def _subtre_postorder(self, p): Generate a postorder iteration of positions in subtree... | fc18b54128cd5bc7639a14999d8f990190b524eb | <|skeleton|>
class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
<|body_0|>
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positions in subtree rooted at p."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeTraversals:
def postorder(self):
"""Generate a postorder iteration of positions in the tree."""
if not self.is_empty():
for p in self._subtree_preorder(self.root()):
yield p
def _subtre_postorder(self, p):
"""Generate a postorder iteration of positi... | the_stack_v2_python_sparse | CHAPTER 08 (trees)/postorder_traversals.py | ahammadshawki8/DSA-Implementations-in-Python | train | 2 | |
cc3be8d2a9ea2dca8a18b73e2bc5a7ad924053cd | [
"self.se = None\nself.angle = angle\nse = np.zeros((m, n), dtype=int)\nxc, yc = (n // 2, m // 2)\nif angle >= 0 and angle < 45:\n b = np.tan(np.deg2rad(angle))\nelif angle >= 45 and angle < 90:\n b = np.tan(np.deg2rad(90 - angle))\nelif angle >= 90 and angle < 135:\n b = np.tan(np.deg2rad(angle - 90))\neli... | <|body_start_0|>
self.se = None
self.angle = angle
se = np.zeros((m, n), dtype=int)
xc, yc = (n // 2, m // 2)
if angle >= 0 and angle < 45:
b = np.tan(np.deg2rad(angle))
elif angle >= 45 and angle < 90:
b = np.tan(np.deg2rad(90 - angle))
el... | Define a selection element for morphological binary image processing. | LinearSelectionElement | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearSelectionElement:
"""Define a selection element for morphological binary image processing."""
def __init__(self, n, m, angle):
"""This will produce an n x m selection element with a line going through the center according to some angle. Parameters ---------- n : int Number of r... | stack_v2_sparse_classes_36k_train_000798 | 10,228 | permissive | [
{
"docstring": "This will produce an n x m selection element with a line going through the center according to some angle. Parameters ---------- n : int Number of rows in selection element. m : int Number of columns in selection element. angle : float Angle of line through center, in deg [0,180].",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_002168 | Implement the Python class `LinearSelectionElement` described below.
Class description:
Define a selection element for morphological binary image processing.
Method signatures and docstrings:
- def __init__(self, n, m, angle): This will produce an n x m selection element with a line going through the center according... | Implement the Python class `LinearSelectionElement` described below.
Class description:
Define a selection element for morphological binary image processing.
Method signatures and docstrings:
- def __init__(self, n, m, angle): This will produce an n x m selection element with a line going through the center according... | d75d0540cd07df1bf46130338a33c2ced51fbead | <|skeleton|>
class LinearSelectionElement:
"""Define a selection element for morphological binary image processing."""
def __init__(self, n, m, angle):
"""This will produce an n x m selection element with a line going through the center according to some angle. Parameters ---------- n : int Number of r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearSelectionElement:
"""Define a selection element for morphological binary image processing."""
def __init__(self, n, m, angle):
"""This will produce an n x m selection element with a line going through the center according to some angle. Parameters ---------- n : int Number of rows in select... | the_stack_v2_python_sparse | py/desispec/joincosmics.py | desihub/desispec | train | 33 |
f0c842f71926f58aad3f2622f4b321d0548122d2 | [
"super().__init__(name=name)\nself._embed = embed\nself._reward_prediction = RewardPrediction(hidden_size=hidden_size, activation=activation)",
"embeddings = snt.BatchApply(self._embed)(inputs)\nembeddings = snt.flatten(embeddings)\nlogits = self._reward_prediction(embeddings)\nreturn logits"
] | <|body_start_0|>
super().__init__(name=name)
self._embed = embed
self._reward_prediction = RewardPrediction(hidden_size=hidden_size, activation=activation)
<|end_body_0|>
<|body_start_1|>
embeddings = snt.BatchApply(self._embed)(inputs)
embeddings = snt.flatten(embeddings)
... | Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, its output is a logits tensor, representing the log-probabilities for the 3 categories to pr... | RewardPredictionNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardPredictionNetwork:
"""Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, its output is a logits tensor, representi... | stack_v2_sparse_classes_36k_train_000799 | 10,989 | no_license | [
{
"docstring": "Initializes the RewardPredictionNetwork module. Args: embed: Embedding module (of type sonnet.Module) to transform observations into an embedding, e.g. FtwTorso. hidden_size: size of hidden linear layer activation: activation function to be used in RewardPrediction module (between linear and log... | 2 | stack_v2_sparse_classes_30k_train_010572 | Implement the Python class `RewardPredictionNetwork` described below.
Class description:
Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, it... | Implement the Python class `RewardPredictionNetwork` described below.
Class description:
Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, it... | 1c2b2768f2c5996c8cc998d0271f3857949bdaeb | <|skeleton|>
class RewardPredictionNetwork:
"""Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, its output is a logits tensor, representi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RewardPredictionNetwork:
"""Module that produces a reward prediction output from an observations input. This module implements the Reward prediction module from the FTW paper and wraps it together with a (possibly shared) embedding module (= embed). Thus, its output is a logits tensor, representing the log-pr... | the_stack_v2_python_sparse | ftw/tf/networks/auxiliary.py | RaoulDrake/ftw | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.