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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0d16aed31e0c7fd3471d26d640ecc5a720dc494 | [
"if logging_config_path is not None:\n config_path = logging_config_path\nelse:\n config_path = DEFAULT_LOGGING_CONFIG_PATH\nlog_config = load_resource(config_path, 'utf-8')\nif log_config:\n with log_config:\n fileConfig(log_config, disable_existing_loggers=False)\nelse:\n logging.basicConfig(le... | <|body_start_0|>
if logging_config_path is not None:
config_path = logging_config_path
else:
config_path = DEFAULT_LOGGING_CONFIG_PATH
log_config = load_resource(config_path, 'utf-8')
if log_config:
with log_config:
fileConfig(log_confi... | Utility class used to configure logging and print an informative start banner. | LoggingConfigurator | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional ... | stack_v2_sparse_classes_36k_train_027500 | 21,957 | permissive | [
{
"docstring": "Configure logger. :param logging_config_path: str: (Default value = None) Optional path to custom logging config :param log_level: str: (Default value = None)",
"name": "configure",
"signature": "def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None)"
... | 3 | stack_v2_sparse_classes_30k_train_006971 | Implement the Python class `LoggingConfigurator` described below.
Class description:
Utility class used to configure logging and print an informative start banner.
Method signatures and docstrings:
- def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None): Configure logger. :param l... | Implement the Python class `LoggingConfigurator` described below.
Class description:
Utility class used to configure logging and print an informative start banner.
Method signatures and docstrings:
- def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None): Configure logger. :param l... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggingConfigurator:
"""Utility class used to configure logging and print an informative start banner."""
def configure(cls, logging_config_path: str=None, log_level: str=None, log_file: str=None):
"""Configure logger. :param logging_config_path: str: (Default value = None) Optional path to custo... | the_stack_v2_python_sparse | aries_cloudagent/config/logging.py | hyperledger/aries-cloudagent-python | train | 370 |
cdfbf5e8b614f4709b2b35703a562c839c88df4f | [
"logging.info('Validando os dados para atualização do usuário na plataforma ALMA.')\nif 'user' not in data.keys():\n raise ParseError('Objeto user é obrigatório.')\nreturn data",
"logging.info(f'Instancia para atualização na plataforma ALMA: {instance}')\nlogging.info(f'Dados para atualização na plataforma ALM... | <|body_start_0|>
logging.info('Validando os dados para atualização do usuário na plataforma ALMA.')
if 'user' not in data.keys():
raise ParseError('Objeto user é obrigatório.')
return data
<|end_body_0|>
<|body_start_1|>
logging.info(f'Instancia para atualização na plataform... | O serializado para pegar os dados do usuário | AlmaUserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlmaUserSerializer:
"""O serializado para pegar os dados do usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
<|body_0|>
def update(self, instance, validated_data):
"""A... | stack_v2_sparse_classes_36k_train_027501 | 3,343 | no_license | [
{
"docstring": "Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Atualiza os dados do usuário",
"name": "update",
"signature": "def update(self, instance, ... | 2 | stack_v2_sparse_classes_30k_train_020716 | Implement the Python class `AlmaUserSerializer` described below.
Class description:
O serializado para pegar os dados do usuário
Method signatures and docstrings:
- def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.
- def update(self, instanc... | Implement the Python class `AlmaUserSerializer` described below.
Class description:
O serializado para pegar os dados do usuário
Method signatures and docstrings:
- def validate(self, data): Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde.
- def update(self, instanc... | 3a8009b17518384c269dfee3c8fe44cbe2567cc0 | <|skeleton|>
class AlmaUserSerializer:
"""O serializado para pegar os dados do usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
<|body_0|>
def update(self, instance, validated_data):
"""A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlmaUserSerializer:
"""O serializado para pegar os dados do usuário"""
def validate(self, data):
"""Valide se existe outro usuário com o mesmo endereço de email e verifique se a senha não corresponde."""
logging.info('Validando os dados para atualização do usuário na plataforma ALMA.')
... | the_stack_v2_python_sparse | project/alma/accounts/serializers.py | VWApplications/VWAlmaAPI | train | 1 |
b133c56cf98e9d4f7e465bc3f2c70c422d0961a6 | [
"alen, blen = (len(a), len(b))\nif alen == blen:\n return self.handle_same_length(a, b)\nif alen == blen + 1:\n return self.handle_one_off(b, a)\nelif blen == alen + 1:\n return self.handle_one_off(a, b)\nreturn False",
"found = False\nfor n, c in enumerate(shorter):\n if shorter[n] == longer[n]:\n ... | <|body_start_0|>
alen, blen = (len(a), len(b))
if alen == blen:
return self.handle_same_length(a, b)
if alen == blen + 1:
return self.handle_one_off(b, a)
elif blen == alen + 1:
return self.handle_one_off(a, b)
return False
<|end_body_0|>
<|bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def oneaway(self, a, b):
"""Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permissible edits are as follows: single leter inserts, deletions and replacements."""
<|body_... | stack_v2_sparse_classes_36k_train_027502 | 2,592 | no_license | [
{
"docstring": "Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permissible edits are as follows: single leter inserts, deletions and replacements.",
"name": "oneaway",
"signature": "def oneaway(self, a, ... | 3 | stack_v2_sparse_classes_30k_train_011515 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def oneaway(self, a, b): Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def oneaway(self, a, b): Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permi... | acad7283f4af301539c621b4b50268208509d38f | <|skeleton|>
class Solution:
def oneaway(self, a, b):
"""Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permissible edits are as follows: single leter inserts, deletions and replacements."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def oneaway(self, a, b):
"""Given two strings and the set of three rules of string changes, return whether the 2 strings are one edit or zero edits away from each other. Three permissible edits are as follows: single leter inserts, deletions and replacements."""
alen, blen = (len(a),... | the_stack_v2_python_sparse | ctci/one-away.py | arijort/prep | train | 2 | |
52ece4c97166a0325852f5589c321c3a39c46019 | [
"self.id = Customer.id_counter\nCustomer.id_counter += 1\nself.behave_per_month = behavior_rates\nself.behave_per_day = 1.0 / 30.0 * self.behave_per_month\nself.channel = channel_name\nif start_of_month:\n self.age = random.uniform(Customer.MIN_AGE, Customer.MAX_AGE)\n self.date_of_birth = start_of_month + re... | <|body_start_0|>
self.id = Customer.id_counter
Customer.id_counter += 1
self.behave_per_month = behavior_rates
self.behave_per_day = 1.0 / 30.0 * self.behave_per_month
self.channel = channel_name
if start_of_month:
self.age = random.uniform(Customer.MIN_AGE, C... | Customer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the ... | stack_v2_sparse_classes_36k_train_027503 | 3,713 | permissive | [
{
"docstring": "Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the account_id in the database, and holds its own subscriptions and events. :param behavior_rates: ndarray of behavior rates, which ar... | 2 | stack_v2_sparse_classes_30k_train_012456 | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None): Creates a customer for simulation, given an ndarray of behavior rates... | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None): Creates a customer for simulation, given an ndarray of behavior rates... | 9d9bfec7bbcb97e60ad8d1f614ae58d13b81ee16 | <|skeleton|>
class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the account_id in ... | the_stack_v2_python_sparse | data-generation/py/customer.py | karthiks/fight-churn | train | 1 | |
9ea14454ad8c2dc49997910b6e08dce754bc878f | [
"self.metric = metric\nself.shrink_threshold = shrink_threshold\nself.ranking_size = ranking_size\nself.clf = NearestCentroid(metric=metric, shrink_threshold=shrink_threshold)",
"check_is_fitted(self, ['X_', 'y_'])\nX = check_array(X)\nall_distances = pairwise_distances(X, self.clf.centroids_, metric=self.metric,... | <|body_start_0|>
self.metric = metric
self.shrink_threshold = shrink_threshold
self.ranking_size = ranking_size
self.clf = NearestCentroid(metric=metric, shrink_threshold=shrink_threshold)
<|end_body_0|>
<|body_start_1|>
check_is_fitted(self, ['X_', 'y_'])
X = check_arra... | Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however, suffer on non-convex classes, as well as when classes have drastically different varia... | NearestCentroidModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NearestCentroidModel:
"""Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however, suffer on non-convex classes, as well ... | stack_v2_sparse_classes_36k_train_027504 | 4,470 | no_license | [
{
"docstring": ":param metric: The metric to use when calculating distance between instances. The default metric is Euclidean. Choices are: - 'euclidean' for standard Euclidean distance - 'manhattan': for the Manhattan distance - 'haversine' for distances between (latitude,longitude) points only - 'cosine': for... | 2 | stack_v2_sparse_classes_30k_val_000593 | Implement the Python class `NearestCentroidModel` described below.
Class description:
Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however,... | Implement the Python class `NearestCentroidModel` described below.
Class description:
Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however,... | c4ac7ef707ddfe90ed65f4e15785414c716cefa2 | <|skeleton|>
class NearestCentroidModel:
"""Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however, suffer on non-convex classes, as well ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NearestCentroidModel:
"""Simple classifier that represents each class by the centroid of its members. Query example are classified to the class with the nearest centroid. It has no parameters to choose, making it a good baseline classifier. It does, however, suffer on non-convex classes, as well as when class... | the_stack_v2_python_sparse | models/nearest_centroid_model.py | jules-brc/geolifeclef | train | 1 |
1dcbd7a3b9fcf0442467512abb69e6a5d70cf61c | [
"super(LinearStrategy, self).onXminBar(bar)\nif not self.trading:\n return\nif not self.am.inited:\n return\nif self.trading:\n direction = self.getSignalPos()\n if self.pos == 0:\n self.filterTrade(direction)\n elif self.direction * direction < 0:\n self.clearOrder()",
"if direction ... | <|body_start_0|>
super(LinearStrategy, self).onXminBar(bar)
if not self.trading:
return
if not self.am.inited:
return
if self.trading:
direction = self.getSignalPos()
if self.pos == 0:
self.filterTrade(direction)
... | 残差周期交叉策略 | LinearStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearStrategy:
"""残差周期交叉策略"""
def onXminBar(self, bar):
"""收到X分钟K线"""
<|body_0|>
def filterTrade(self, direction):
"""按规则过滤交易"""
<|body_1|>
def getSignalPos(self):
"""计算指标数据"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_027505 | 2,180 | permissive | [
{
"docstring": "收到X分钟K线",
"name": "onXminBar",
"signature": "def onXminBar(self, bar)"
},
{
"docstring": "按规则过滤交易",
"name": "filterTrade",
"signature": "def filterTrade(self, direction)"
},
{
"docstring": "计算指标数据",
"name": "getSignalPos",
"signature": "def getSignalPos(se... | 3 | stack_v2_sparse_classes_30k_train_008221 | Implement the Python class `LinearStrategy` described below.
Class description:
残差周期交叉策略
Method signatures and docstrings:
- def onXminBar(self, bar): 收到X分钟K线
- def filterTrade(self, direction): 按规则过滤交易
- def getSignalPos(self): 计算指标数据 | Implement the Python class `LinearStrategy` described below.
Class description:
残差周期交叉策略
Method signatures and docstrings:
- def onXminBar(self, bar): 收到X分钟K线
- def filterTrade(self, direction): 按规则过滤交易
- def getSignalPos(self): 计算指标数据
<|skeleton|>
class LinearStrategy:
"""残差周期交叉策略"""
def onXminBar(self, ba... | 863ce7b12a61059b7f7bb482b1dede54c10aa3b9 | <|skeleton|>
class LinearStrategy:
"""残差周期交叉策略"""
def onXminBar(self, bar):
"""收到X分钟K线"""
<|body_0|>
def filterTrade(self, direction):
"""按规则过滤交易"""
<|body_1|>
def getSignalPos(self):
"""计算指标数据"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearStrategy:
"""残差周期交叉策略"""
def onXminBar(self, bar):
"""收到X分钟K线"""
super(LinearStrategy, self).onXminBar(bar)
if not self.trading:
return
if not self.am.inited:
return
if self.trading:
direction = self.getSignalPos()
... | the_stack_v2_python_sparse | vnpy/app/cta_strategy/strategies/strategyLinear.py | bigdig/vnpy | train | 0 |
a6fe174c99fcd417755167f97fcddc8b3f87413e | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DirectoryRole()",
"from .directory_object import DirectoryObject\nfrom .scoped_role_membership import ScopedRoleMembership\nfrom .directory_object import DirectoryObject\nfrom .scoped_role_membership import ScopedRoleMembership\nfields... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DirectoryRole()
<|end_body_0|>
<|body_start_1|>
from .directory_object import DirectoryObject
from .scoped_role_membership import ScopedRoleMembership
from .directory_object impo... | DirectoryRole | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryRole:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryRole:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_027506 | 3,845 | 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: DirectoryRole",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_019590 | Implement the Python class `DirectoryRole` described below.
Class description:
Implement the DirectoryRole class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryRole: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `DirectoryRole` described below.
Class description:
Implement the DirectoryRole class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryRole: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DirectoryRole:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryRole:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryRole:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DirectoryRole:
"""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: DirectoryRol... | the_stack_v2_python_sparse | msgraph/generated/models/directory_role.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c3df887ed0171ba0af20ce0b54ad51a525a843a7 | [
"try:\n cls.create(Rating=rating, TextComment=text_comment, CID=cid, InvoiceNo=inv_no)\nexcept IntegrityError:\n raise ValueError('Review already exists')",
"try:\n cls.create(Rating=rating, TextComment=text_comment, CID=cid, InvoiceNo=inv_no)\nexcept IntegrityError:\n raise ValueError('Review already... | <|body_start_0|>
try:
cls.create(Rating=rating, TextComment=text_comment, CID=cid, InvoiceNo=inv_no)
except IntegrityError:
raise ValueError('Review already exists')
<|end_body_0|>
<|body_start_1|>
try:
cls.create(Rating=rating, TextComment=text_comment, CID=... | writes_Review | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class writes_Review:
def create_review(cls, rating, text_comment, cid, inv_no):
"""writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment : textual description customer gives CID : customer identification Returns: N/A Raises: ValueError: Whe... | stack_v2_sparse_classes_36k_train_027507 | 2,573 | no_license | [
{
"docstring": "writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment : textual description customer gives CID : customer identification Returns: N/A Raises: ValueError: When cid already exists",
"name": "create_review",
"signature": "def create_revi... | 2 | stack_v2_sparse_classes_30k_train_008955 | Implement the Python class `writes_Review` described below.
Class description:
Implement the writes_Review class.
Method signatures and docstrings:
- def create_review(cls, rating, text_comment, cid, inv_no): writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment :... | Implement the Python class `writes_Review` described below.
Class description:
Implement the writes_Review class.
Method signatures and docstrings:
- def create_review(cls, rating, text_comment, cid, inv_no): writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment :... | 90879bbec3109b0d6f9b8a9c6c922d4683afe4f1 | <|skeleton|>
class writes_Review:
def create_review(cls, rating, text_comment, cid, inv_no):
"""writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment : textual description customer gives CID : customer identification Returns: N/A Raises: ValueError: Whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class writes_Review:
def create_review(cls, rating, text_comment, cid, inv_no):
"""writes a review Args: reviewID : Identification of the review rating : score the customer gives TextComment : textual description customer gives CID : customer identification Returns: N/A Raises: ValueError: When cid already ... | the_stack_v2_python_sparse | asst/models/review.py | kelbaum/CS336 | train | 0 | |
4e3c8e809c8e27e7a7e3a66fd252759063d857ba | [
"if not prices:\n return 0\nprofit = 0\nminPrice = prices[0]\nfor i in range(len(prices)):\n profit = max(profit, prices[i] - minPrice)\n minPrice = min(prices[i], minPrice)\nreturn profit",
"if not prices:\n return 0\nprofit = 0\nfor i in range(len(prices) - 1):\n profit += max(prices[i + 1] - pri... | <|body_start_0|>
if not prices:
return 0
profit = 0
minPrice = prices[0]
for i in range(len(prices)):
profit = max(profit, prices[i] - minPrice)
minPrice = min(prices[i], minPrice)
return profit
<|end_body_0|>
<|body_start_1|>
if not p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfitMulti(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfitTwice(self, prices):
""":type prices: List[int] :rtype... | stack_v2_sparse_classes_36k_train_027508 | 5,151 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfitMulti",
"signature": "def maxProfitMulti(self, prices)"
},
{
"docstring": ":type prices... | 4 | stack_v2_sparse_classes_30k_train_015800 | 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 maxProfitMulti(self, prices): :type prices: List[int] :rtype: int
- def maxProfitTwice(self, prices): :type... | 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 maxProfitMulti(self, prices): :type prices: List[int] :rtype: int
- def maxProfitTwice(self, prices): :type... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfitMulti(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfitTwice(self, prices):
""":type prices: List[int] :rtype... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
profit = 0
minPrice = prices[0]
for i in range(len(prices)):
profit = max(profit, prices[i] - minPrice)
minPrice = min(prices[i],... | the_stack_v2_python_sparse | python_solution/121_130/BuyAndSellStock.py | CescWang1991/LeetCode-Python | train | 1 | |
1cc14bf69f611220fa5776f8fd7349435778e3e6 | [
"self.size = size\nself.queue = []\nself.sum = 0",
"if len(self.queue) < self.size:\n self.queue.append(val)\nelse:\n self.sum -= self.queue[0]\n del self.queue[0]\n self.queue.append(val)\nself.sum += val\nreturn float(self.sum) / len(self.queue)"
] | <|body_start_0|>
self.size = size
self.queue = []
self.sum = 0
<|end_body_0|>
<|body_start_1|>
if len(self.queue) < self.size:
self.queue.append(val)
else:
self.sum -= self.queue[0]
del self.queue[0]
self.queue.append(val)
... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.queue =... | stack_v2_sparse_classes_36k_train_027509 | 1,199 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001971 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 36c584e8f92a0725bab7a567dfd10b918408627b | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.queue = []
self.sum = 0
def next(self, val):
""":type val: int :rtype: float"""
if len(self.queue) < self.size:
self.queue.... | the_stack_v2_python_sparse | 346. Moving Average from Data Stream.py | Huijuan2015/leetcode_Python_2019 | train | 0 | |
7eb5228489c179de6cfc753f5b89162f8d1d4be0 | [
"sorted_rl_ids = [veh_id for veh_id in self.sorted_ids if veh_id in self.k.vehicle.get_rl_ids()]\nav_action = rl_actions['av']\nadv_action = rl_actions['adversary']\nperturb_weight = self.env_params.additional_params['perturb_weight']\nrl_action = av_action + perturb_weight * adv_action\nself.k.vehicle.apply_accele... | <|body_start_0|>
sorted_rl_ids = [veh_id for veh_id in self.sorted_ids if veh_id in self.k.vehicle.get_rl_ids()]
av_action = rl_actions['av']
adv_action = rl_actions['adversary']
perturb_weight = self.env_params.additional_params['perturb_weight']
rl_action = av_action + perturb_... | Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * AV: The action space of the AV agent consists of a vector of bounded accelerations for... | AdversarialAccelEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdversarialAccelEnv:
"""Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * AV: The action space of the AV agent co... | stack_v2_sparse_classes_36k_train_027510 | 8,617 | permissive | [
{
"docstring": "See class definition.",
"name": "_apply_rl_actions",
"signature": "def _apply_rl_actions(self, rl_actions)"
},
{
"docstring": "Compute opposing rewards for agents. The agent receives the class definition reward, the adversary receives the negative of the agent reward",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000017 | Implement the Python class `AdversarialAccelEnv` described below.
Class description:
Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * ... | Implement the Python class `AdversarialAccelEnv` described below.
Class description:
Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * ... | badac3da17f04d8d8ae5691ee8ba2af9d56fac35 | <|skeleton|>
class AdversarialAccelEnv:
"""Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * AV: The action space of the AV agent co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdversarialAccelEnv:
"""Adversarial multi-agent acceleration env. States The observation of both the AV and adversary agent consist of the velocities and absolute position of all vehicles in the network. This assumes a constant number of vehicles. Actions * AV: The action space of the AV agent consists of a v... | the_stack_v2_python_sparse | flow/envs/multiagent/ring/accel.py | parthjaggi/flow | train | 6 |
a03cd982f5436d13782f5a2d3b37244184747250 | [
"q = Queue(maxsize=0)\nq.put(root)\nserial_list = []\nwhile not q.empty():\n e = q.get()\n if e is not None:\n serial_list.append(str(e.val))\n q.put(e.left)\n q.put(e.right)\n else:\n serial_list.append(str(None))\n pass\nreturn ','.join(serial_list)",
"e_li = data.split('... | <|body_start_0|>
q = Queue(maxsize=0)
q.put(root)
serial_list = []
while not q.empty():
e = q.get()
if e is not None:
serial_list.append(str(e.val))
q.put(e.left)
q.put(e.right)
else:
seri... | 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_027511 | 2,319 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 2a29426be1d690b6f90bc45b437900deee46d832 | <|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"""
q = Queue(maxsize=0)
q.put(root)
serial_list = []
while not q.empty():
e = q.get()
if e is not None:
serial_list.append(st... | the_stack_v2_python_sparse | src/leet/Serialize and Deserialize Binary Tree.py | sevenseablue/leetcode | train | 0 | |
c20430017048bf664cb8c49e07af5cd325b76708 | [
"super().__init__()\nself.optimizer = optimizer\nself.problem = problem\nself.current_profile = current_profile\nself.global_opt = global_opt\nself.create_next_guess = create_next_guess\nself.i_par = i_par\nself.options = options",
"logger.debug(f'Executing task {self.i_par}.')\nfor par_direction in [-1, 1]:\n ... | <|body_start_0|>
super().__init__()
self.optimizer = optimizer
self.problem = problem
self.current_profile = current_profile
self.global_opt = global_opt
self.create_next_guess = create_next_guess
self.i_par = i_par
self.options = options
<|end_body_0|>
<... | A parameter likelihood profiling task. | ProfilerTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilerTask:
"""A parameter likelihood profiling task."""
def __init__(self, current_profile: ProfilerResult, problem: Problem, options: ProfileOptions, i_par: int, global_opt: float, optimizer: 'pypesto.optimize.Optimizer', create_next_guess: Callable):
"""Create the task object. P... | stack_v2_sparse_classes_36k_train_027512 | 2,453 | permissive | [
{
"docstring": "Create the task object. Parameters ---------- current_profile: The profile which should be computed problem: The problem to be solved. optimizer: The optimizer to be used along each profile. global_opt: log-posterior value of the global optimum options: Various options applied to the profile opt... | 2 | stack_v2_sparse_classes_30k_train_021399 | Implement the Python class `ProfilerTask` described below.
Class description:
A parameter likelihood profiling task.
Method signatures and docstrings:
- def __init__(self, current_profile: ProfilerResult, problem: Problem, options: ProfileOptions, i_par: int, global_opt: float, optimizer: 'pypesto.optimize.Optimizer'... | Implement the Python class `ProfilerTask` described below.
Class description:
A parameter likelihood profiling task.
Method signatures and docstrings:
- def __init__(self, current_profile: ProfilerResult, problem: Problem, options: ProfileOptions, i_par: int, global_opt: float, optimizer: 'pypesto.optimize.Optimizer'... | 9a754573a7b77d30d5dc1f67a8dc1be6c29f1640 | <|skeleton|>
class ProfilerTask:
"""A parameter likelihood profiling task."""
def __init__(self, current_profile: ProfilerResult, problem: Problem, options: ProfileOptions, i_par: int, global_opt: float, optimizer: 'pypesto.optimize.Optimizer', create_next_guess: Callable):
"""Create the task object. P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfilerTask:
"""A parameter likelihood profiling task."""
def __init__(self, current_profile: ProfilerResult, problem: Problem, options: ProfileOptions, i_par: int, global_opt: float, optimizer: 'pypesto.optimize.Optimizer', create_next_guess: Callable):
"""Create the task object. Parameters ---... | the_stack_v2_python_sparse | pypesto/profile/task.py | ICB-DCM/pyPESTO | train | 174 |
de2494c75afcec40520057a5768fadc735aa89d6 | [
"shortcut = inputs\noutputs = tf_utils.conv2d_fixed_padding(inputs, filters, 1)\noutputs = tf_utils.conv2d_fixed_padding(outputs, filters * 2, 3)\noutputs = shortcut + outputs\nreturn outputs",
"outputs = tf_utils.conv2d_fixed_padding(inputs, 32, 3)\noutputs = tf_utils.conv2d_fixed_padding(outputs, 64, 3, strides... | <|body_start_0|>
shortcut = inputs
outputs = tf_utils.conv2d_fixed_padding(inputs, filters, 1)
outputs = tf_utils.conv2d_fixed_padding(outputs, filters * 2, 3)
outputs = shortcut + outputs
return outputs
<|end_body_0|>
<|body_start_1|>
outputs = tf_utils.conv2d_fixed_pad... | The Darknet-53 framework. Reference: https://pjreddie.com/darknet/ | Darknet53 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Darknet53:
"""The Darknet-53 framework. Reference: https://pjreddie.com/darknet/"""
def _block(inputs, filters):
"""A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :return: The output tensor."""
<|body_0|>
def buil... | stack_v2_sparse_classes_36k_train_027513 | 1,717 | permissive | [
{
"docstring": "A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :return: The output tensor.",
"name": "_block",
"signature": "def _block(inputs, filters)"
},
{
"docstring": "Build the Darknet-53 model. :param inputs: The input tensor. :ret... | 2 | stack_v2_sparse_classes_30k_train_009478 | Implement the Python class `Darknet53` described below.
Class description:
The Darknet-53 framework. Reference: https://pjreddie.com/darknet/
Method signatures and docstrings:
- def _block(inputs, filters): A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :retur... | Implement the Python class `Darknet53` described below.
Class description:
The Darknet-53 framework. Reference: https://pjreddie.com/darknet/
Method signatures and docstrings:
- def _block(inputs, filters): A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :retur... | 20864f88adc2fe52c25538ebb11c5947a85debd3 | <|skeleton|>
class Darknet53:
"""The Darknet-53 framework. Reference: https://pjreddie.com/darknet/"""
def _block(inputs, filters):
"""A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :return: The output tensor."""
<|body_0|>
def buil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Darknet53:
"""The Darknet-53 framework. Reference: https://pjreddie.com/darknet/"""
def _block(inputs, filters):
"""A convolution block. :param inputs: The input tensor. :param filters: The number of convolution filters. :return: The output tensor."""
shortcut = inputs
outputs = t... | the_stack_v2_python_sparse | python/ImageCatcher/models/darknet53.py | gana-chocolate/Doodles_Become_Paintings | train | 2 |
87bc492dc9a862b09ab5aae90029e5b7f6795c1a | [
"mongo = MongoDBConnection()\ndatabase_name = database_name or DBCls.DATABASE_NAME\ndirectory = pathlib.Path(directory)\nwith mongo:\n db = mongo.connection.get_database(name=database_name)\n files = [product_file, customer_file, rental_file]\n count = []\n error = []\n for file in files:\n wi... | <|body_start_0|>
mongo = MongoDBConnection()
database_name = database_name or DBCls.DATABASE_NAME
directory = pathlib.Path(directory)
with mongo:
db = mongo.connection.get_database(name=database_name)
files = [product_file, customer_file, rental_file]
... | DBCls | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBCls:
def import_data(directory, product_file, customer_file, rental_file, connection=None, database_name=None):
"""creates and populates a new MongoDB database with these csv data file, :param product_file: :param customer_file: :param rentals_file: :return: 2 tuples: numbers of record... | stack_v2_sparse_classes_36k_train_027514 | 6,751 | no_license | [
{
"docstring": "creates and populates a new MongoDB database with these csv data file, :param product_file: :param customer_file: :param rentals_file: :return: 2 tuples: numbers of record count product, customers, and rentals added, and count of any error that occurred.",
"name": "import_data",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_020340 | Implement the Python class `DBCls` described below.
Class description:
Implement the DBCls class.
Method signatures and docstrings:
- def import_data(directory, product_file, customer_file, rental_file, connection=None, database_name=None): creates and populates a new MongoDB database with these csv data file, :param... | Implement the Python class `DBCls` described below.
Class description:
Implement the DBCls class.
Method signatures and docstrings:
- def import_data(directory, product_file, customer_file, rental_file, connection=None, database_name=None): creates and populates a new MongoDB database with these csv data file, :param... | 7b5dab79ab34f708d10ab04385203157855bbde5 | <|skeleton|>
class DBCls:
def import_data(directory, product_file, customer_file, rental_file, connection=None, database_name=None):
"""creates and populates a new MongoDB database with these csv data file, :param product_file: :param customer_file: :param rentals_file: :return: 2 tuples: numbers of record... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBCls:
def import_data(directory, product_file, customer_file, rental_file, connection=None, database_name=None):
"""creates and populates a new MongoDB database with these csv data file, :param product_file: :param customer_file: :param rentals_file: :return: 2 tuples: numbers of record count product... | the_stack_v2_python_sparse | students/HABTAMU/lesson10/assigment/database.py | dtingg/PythonCert220Assign | train | 1 | |
ecfb0eae13917f06e82e05d1f9ba2506cbac0aed | [
"n = len(nums)\nfor num in nums:\n key = abs(num)\n val = abs(num)\n if nums[key] < 0:\n return val\n else:\n nums[key] = -nums[key]\nreturn -1",
"\"\"\"Treat index as node, value as address of next node\"\"\"\n'There is a duplicate number in array <=> There is a cycle in this linked lis... | <|body_start_0|>
n = len(nums)
for num in nums:
key = abs(num)
val = abs(num)
if nums[key] < 0:
return val
else:
nums[key] = -nums[key]
return -1
<|end_body_0|>
<|body_start_1|>
"""Treat index as node, value... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""Time: O(n), Space: O(1), But we modify the nums"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""2 pointer linklist cycle detection, Time: O(n), Space: O(1)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_027515 | 2,183 | no_license | [
{
"docstring": "Time: O(n), Space: O(1), But we modify the nums",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums: List[int]) -> int"
},
{
"docstring": "2 pointer linklist cycle detection, Time: O(n), Space: O(1)",
"name": "findDuplicate",
"signature": "def findDuplic... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: Time: O(n), Space: O(1), But we modify the nums
- def findDuplicate(self, nums: List[int]) -> int: 2 pointer linklist cycle detec... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: Time: O(n), Space: O(1), But we modify the nums
- def findDuplicate(self, nums: List[int]) -> int: 2 pointer linklist cycle detec... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""Time: O(n), Space: O(1), But we modify the nums"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""2 pointer linklist cycle detection, Time: O(n), Space: O(1)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""Time: O(n), Space: O(1), But we modify the nums"""
n = len(nums)
for num in nums:
key = abs(num)
val = abs(num)
if nums[key] < 0:
return val
else:
... | the_stack_v2_python_sparse | python/287-Find the Duplicate Number.py | cwza/leetcode | train | 0 | |
7adc5ca8d0c1c27494a4cd031a4b9f98ed1f341e | [
"nodes = deque()\nnodes.append(root)\nserial = []\nwhile len(nodes) != 0:\n curnode = nodes.popleft()\n serial.append(curnode.val)\n if curnode.left:\n nodes.append(curnode.left)\n if curnode.right:\n nodes.append(curnode.right)\nwhile serial[-1] == 0:\n serial.pop()\nreturn serial",
... | <|body_start_0|>
nodes = deque()
nodes.append(root)
serial = []
while len(nodes) != 0:
curnode = nodes.popleft()
serial.append(curnode.val)
if curnode.left:
nodes.append(curnode.left)
if curnode.right:
nodes.... | 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_027516 | 1,652 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 1f7af97bf2e42fc1fe87f31bf0af159dc76486fa | <|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"""
nodes = deque()
nodes.append(root)
serial = []
while len(nodes) != 0:
curnode = nodes.popleft()
serial.append(curnode.val)
if ... | the_stack_v2_python_sparse | 链表/二叉树的序列化.py | zhangler1/leetcodepractice | train | 2 | |
4477298cab0656c2197b1e224c8392b77378711d | [
"curboard = response.selector.xpath('//h2[contains(@class, \"forum-title\")]/a/text()').extract()\nif curboard[0].lower() == 'Fishing Session Reports'.lower():\n last_link = 5430\nelse:\n last_link = 3420\nposts_per_page = 30\nurls = [response.url]\nif _ini.WirralSeaFishingReportsIni.RUN_FIX:\n print('\\n*... | <|body_start_0|>
curboard = response.selector.xpath('//h2[contains(@class, "forum-title")]/a/text()').extract()
if curboard[0].lower() == 'Fishing Session Reports'.lower():
last_link = 5430
else:
last_link = 3420
posts_per_page = 30
urls = [response.url]
... | scrape reports from angling addicts forum | WirralSeaFishingReportsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WirralSeaFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=3... | stack_v2_sparse_classes_36k_train_027517 | 9,325 | no_license | [
{
"docstring": "generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=30 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=3420 assert isinstance(response, scra... | 3 | null | Implement the Python class `WirralSeaFishingReportsSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://... | Implement the Python class `WirralSeaFishingReportsSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class WirralSeaFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WirralSeaFishingReportsSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33 https://www.wirralseafishing.co.uk/forum/phpBB2/viewforum.php?f=33&start=30 ht... | the_stack_v2_python_sparse | imgscrape/spiders/wirralseafishing.py | gmonkman/python | train | 0 |
86779baf5c60f884580f9bd4ad0b16f3eff85afc | [
"try:\n data = fits.open(path)\nexcept FileNotFoundError:\n data = None\nreturn data",
"if not isinstance(inMemoryDataset, fits.HDUList):\n raise NotImplementedError('Unable to write this representation of FITS into a file.')\ninMemoryDataset.writeto(self.fileDescriptor.location.path)"
] | <|body_start_0|>
try:
data = fits.open(path)
except FileNotFoundError:
data = None
return data
<|end_body_0|>
<|body_start_1|>
if not isinstance(inMemoryDataset, fits.HDUList):
raise NotImplementedError('Unable to write this representation of FITS int... | Interface for reading and writing astropy image objects to and from FITS files. | AstropyImageFormatter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JS... | stack_v2_sparse_classes_36k_train_027518 | 1,661 | no_license | [
{
"docstring": "Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JSON format file. pytype : `class`, optional Not used by this implementation. Returns ------- data : `object` Either data as Python object read from JSON file, or None if the file could not be opened... | 2 | stack_v2_sparse_classes_30k_train_000032 | Implement the Python class `AstropyImageFormatter` described below.
Class description:
Interface for reading and writing astropy image objects to and from FITS files.
Method signatures and docstrings:
- def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any: Read a file from the path in FITS format. ... | Implement the Python class `AstropyImageFormatter` described below.
Class description:
Interface for reading and writing astropy image objects to and from FITS files.
Method signatures and docstrings:
- def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any: Read a file from the path in FITS format. ... | 4a292c3c42a094c87bb62a9afd97cff68878d2d2 | <|skeleton|>
class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JSON format fil... | the_stack_v2_python_sparse | python/spherex/formatters/astropy_image.py | Caltech-IPAC/spherex_butler_poc | train | 0 |
b5b7abb21cd9a9155ed575c82c70f5e1f8d6cd17 | [
"counter = memcache.incr('FileVaultAccessLogCounter', initial_value=0)\nself.paginate_mtime = '%s_%s' % (self.mtime, counter)\nsuper(FileVaultAccessLog, self).put()",
"log = FileVaultAccessLog()\nfor p in log.properties():\n if p in kwargs:\n setattr(log, p, kwargs[p])\nif request:\n log.query = '%s?... | <|body_start_0|>
counter = memcache.incr('FileVaultAccessLogCounter', initial_value=0)
self.paginate_mtime = '%s_%s' % (self.mtime, counter)
super(FileVaultAccessLog, self).put()
<|end_body_0|>
<|body_start_1|>
log = FileVaultAccessLog()
for p in log.properties():
if... | Model for logging access to FileVault passphrases. | FileVaultAccessLog | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileVaultAccessLog:
"""Model for logging access to FileVault passphrases."""
def put(self):
"""Override put to automatically calculate pagination properties."""
<|body_0|>
def Log(cls, request=None, **kwargs):
"""Puts a new FileVaultAccessLog entity into Datastor... | stack_v2_sparse_classes_36k_train_027519 | 7,979 | permissive | [
{
"docstring": "Override put to automatically calculate pagination properties.",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "Puts a new FileVaultAccessLog entity into Datastore. Args: request: a webapp Request object to fetch obtain details from. **kwargs: any key/value pair w... | 2 | stack_v2_sparse_classes_30k_train_001369 | Implement the Python class `FileVaultAccessLog` described below.
Class description:
Model for logging access to FileVault passphrases.
Method signatures and docstrings:
- def put(self): Override put to automatically calculate pagination properties.
- def Log(cls, request=None, **kwargs): Puts a new FileVaultAccessLog... | Implement the Python class `FileVaultAccessLog` described below.
Class description:
Model for logging access to FileVault passphrases.
Method signatures and docstrings:
- def put(self): Override put to automatically calculate pagination properties.
- def Log(cls, request=None, **kwargs): Puts a new FileVaultAccessLog... | a9bc209b610a927083bf16274d8451c6c45227bf | <|skeleton|>
class FileVaultAccessLog:
"""Model for logging access to FileVault passphrases."""
def put(self):
"""Override put to automatically calculate pagination properties."""
<|body_0|>
def Log(cls, request=None, **kwargs):
"""Puts a new FileVaultAccessLog entity into Datastor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileVaultAccessLog:
"""Model for logging access to FileVault passphrases."""
def put(self):
"""Override put to automatically calculate pagination properties."""
counter = memcache.incr('FileVaultAccessLogCounter', initial_value=0)
self.paginate_mtime = '%s_%s' % (self.mtime, count... | the_stack_v2_python_sparse | src/cauliflowervest/server/models.py | cooljeanius/cauliflowervest | train | 1 |
05e142b9b8a0f08ac300d38452372120fee7d482 | [
"EasyFrame.__init__(self, 'Text Editor')\nself.file_name = ''\nself.outputArea = self.addTextArea('', row=0, column=0, columnspan=3, width=80, height=15)\nself.newButton = self.addButton(text='New', row=1, column=0, command=self.newFile)\nself.openButton = self.addButton(text='Open', row=1, column=1, command=self.o... | <|body_start_0|>
EasyFrame.__init__(self, 'Text Editor')
self.file_name = ''
self.outputArea = self.addTextArea('', row=0, column=0, columnspan=3, width=80, height=15)
self.newButton = self.addButton(text='New', row=1, column=0, command=self.newFile)
self.openButton = self.addBut... | Demonstrates the use of a file dialog. | TextEditor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextEditor:
"""Demonstrates the use of a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def newFile(self):
"""Clears the text area and the title bar."""
<|body_1|>
def openFile(self):
"""Pops up an open f... | stack_v2_sparse_classes_36k_train_027520 | 2,994 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clears the text area and the title bar.",
"name": "newFile",
"signature": "def newFile(self)"
},
{
"docstring": "Pops up an open file dialog, and if a file i... | 4 | stack_v2_sparse_classes_30k_train_014802 | Implement the Python class `TextEditor` described below.
Class description:
Demonstrates the use of a file dialog.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def newFile(self): Clears the text area and the title bar.
- def openFile(self): Pops up an open file dialog, and... | Implement the Python class `TextEditor` described below.
Class description:
Demonstrates the use of a file dialog.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def newFile(self): Clears the text area and the title bar.
- def openFile(self): Pops up an open file dialog, and... | 30375264cf0103e3455fdf92c35a2c5c15b5d7ef | <|skeleton|>
class TextEditor:
"""Demonstrates the use of a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def newFile(self):
"""Clears the text area and the title bar."""
<|body_1|>
def openFile(self):
"""Pops up an open f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextEditor:
"""Demonstrates the use of a file dialog."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, 'Text Editor')
self.file_name = ''
self.outputArea = self.addTextArea('', row=0, column=0, columnspan=3, width=80, height=15)
... | the_stack_v2_python_sparse | Ch8 exercises/texteditor.py | davelpat/Fundamentals_of_Python | train | 1 |
7c863243a5a9ed111e9608454bd4a01b3e818afc | [
"self.veh_id = veh_id\nself.lane_change_params = lane_change_params\nif 'min_gap' in lane_change_params:\n self.min_gap = lane_change_params['min_gap']\nelse:\n self.min_gap = 0.1",
"current_lane = env.vehicles[self.veh_id]['lane']\nif current_lane == target_lane:\n return target_lane\nif target_lane < 0... | <|body_start_0|>
self.veh_id = veh_id
self.lane_change_params = lane_change_params
if 'min_gap' in lane_change_params:
self.min_gap = lane_change_params['min_gap']
else:
self.min_gap = 0.1
<|end_body_0|>
<|body_start_1|>
current_lane = env.vehicles[self.v... | BaseLaneChangingController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLaneChangingController:
def __init__(self, veh_id, lane_change_params):
"""Base class for lane-changing controllers. Instantiates a controller and forces the user to pass a lane_changing duration to the controller. Provides the method get_safe_lane_change_action to ensure that lane-c... | stack_v2_sparse_classes_36k_train_027521 | 3,335 | permissive | [
{
"docstring": "Base class for lane-changing controllers. Instantiates a controller and forces the user to pass a lane_changing duration to the controller. Provides the method get_safe_lane_change_action to ensure that lane-changes do not cause crashes. Attributes ---------- veh_id: string ID of the vehicle thi... | 2 | stack_v2_sparse_classes_30k_train_018191 | Implement the Python class `BaseLaneChangingController` described below.
Class description:
Implement the BaseLaneChangingController class.
Method signatures and docstrings:
- def __init__(self, veh_id, lane_change_params): Base class for lane-changing controllers. Instantiates a controller and forces the user to pas... | Implement the Python class `BaseLaneChangingController` described below.
Class description:
Implement the BaseLaneChangingController class.
Method signatures and docstrings:
- def __init__(self, veh_id, lane_change_params): Base class for lane-changing controllers. Instantiates a controller and forces the user to pas... | f3f6d7e9c64f6b641a464a716c7f38ca00388805 | <|skeleton|>
class BaseLaneChangingController:
def __init__(self, veh_id, lane_change_params):
"""Base class for lane-changing controllers. Instantiates a controller and forces the user to pass a lane_changing duration to the controller. Provides the method get_safe_lane_change_action to ensure that lane-c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseLaneChangingController:
def __init__(self, veh_id, lane_change_params):
"""Base class for lane-changing controllers. Instantiates a controller and forces the user to pass a lane_changing duration to the controller. Provides the method get_safe_lane_change_action to ensure that lane-changes do not ... | the_stack_v2_python_sparse | flow/controllers/base_lane_changing_controller.py | mark-koren/flow | train | 0 | |
a4abc0cdc95169ebcc7f11d9ed7760ba3fd61f4b | [
"import math\nfinal_ans = max(piles)\nstart, end = (1, max(piles))\nwhile start <= end:\n mid = (start + end) // 2\n ans = 0\n for pile in piles:\n ans += math.ceil(pile / mid)\n if ans > H:\n start = mid + 1\n else:\n final_ans = min(mid, final_ans)\n end = mid - 1\nretur... | <|body_start_0|>
import math
final_ans = max(piles)
start, end = (1, max(piles))
while start <= end:
mid = (start + end) // 2
ans = 0
for pile in piles:
ans += math.ceil(pile / mid)
if ans > H:
start = mid + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 560 ms"""
<|body_0|>
def minEatingSpeed_1(self, piles, H):
"""252ms :param piles: :param H: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
imp... | stack_v2_sparse_classes_36k_train_027522 | 2,186 | no_license | [
{
"docstring": ":type piles: List[int] :type H: int :rtype: int 560 ms",
"name": "minEatingSpeed",
"signature": "def minEatingSpeed(self, piles, H)"
},
{
"docstring": "252ms :param piles: :param H: :return:",
"name": "minEatingSpeed_1",
"signature": "def minEatingSpeed_1(self, piles, H)"... | 2 | stack_v2_sparse_classes_30k_train_013885 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 560 ms
- def minEatingSpeed_1(self, piles, H): 252ms :param piles: :param H: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: int 560 ms
- def minEatingSpeed_1(self, piles, H): 252ms :param piles: :param H: :return:
<|skele... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 560 ms"""
<|body_0|>
def minEatingSpeed_1(self, piles, H):
"""252ms :param piles: :param H: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minEatingSpeed(self, piles, H):
""":type piles: List[int] :type H: int :rtype: int 560 ms"""
import math
final_ans = max(piles)
start, end = (1, max(piles))
while start <= end:
mid = (start + end) // 2
ans = 0
for pile i... | the_stack_v2_python_sparse | KokoEatingBananas_MID_875.py | 953250587/leetcode-python | train | 2 | |
66eacbfe8a7a267f3d601242b1fac10253f943d1 | [
"if 'ssh' not in self.conn_cmd:\n raise Exception('ssh connection string is not found. Check inventory server or inventory.json')\nself._spawn(self.conn_cmd + f' -l {self.username} -o StrictHostKeyChecking=No -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=60 -o ServerAliveCountMax=5')\ntry:\n self.dev... | <|body_start_0|>
if 'ssh' not in self.conn_cmd:
raise Exception('ssh connection string is not found. Check inventory server or inventory.json')
self._spawn(self.conn_cmd + f' -l {self.username} -o StrictHostKeyChecking=No -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=60 -o ServerAli... | Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board. | AuthenticatedSshConnection | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticatedSshConnection:
"""Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board."""
def connect(self) -> None:
"""Connect to... | stack_v2_sparse_classes_36k_train_027523 | 4,580 | permissive | [
{
"docstring": "Connect to the board/station using telnet. This method spawn a pexpect session with telnet command. The ssh port must be as per the ser2net configuration file in order to connect to serial ports of the board. :raises: Exception Board is in use (connection refused).",
"name": "connect",
"... | 2 | null | Implement the Python class `AuthenticatedSshConnection` described below.
Class description:
Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board.
Method signature... | Implement the Python class `AuthenticatedSshConnection` described below.
Class description:
Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board.
Method signature... | e722e35f937656efaa43dfd29b49df5c38795243 | <|skeleton|>
class AuthenticatedSshConnection:
"""Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board."""
def connect(self) -> None:
"""Connect to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticatedSshConnection:
"""Allow authenticated ssh sessions to be established with a unit's serial ports by OpenGear server. If a board is connected serially to a OpenGear terminal server, this class can be used to connect to the board."""
def connect(self) -> None:
"""Connect to the board/st... | the_stack_v2_python_sparse | boardfarm/devices/authenticated_serial_connections.py | lgirdk/boardfarm | train | 20 |
d3bb5604136417b90dbf69a8270a1978d3517b2c | [
"username_count = User.objects.filter(username=value).count()\nif username_count > 0:\n raise serializers.ValidationError('该用户名已注册')\nreturn value",
"mobile_count = User.objects.filter(mobile=value).count()\nif mobile_count > 0:\n raise serializers.ValidationError('该号码已注册')\nif not re.match('^1[3-9]\\\\d{9}... | <|body_start_0|>
username_count = User.objects.filter(username=value).count()
if username_count > 0:
raise serializers.ValidationError('该用户名已注册')
return value
<|end_body_0|>
<|body_start_1|>
mobile_count = User.objects.filter(mobile=value).count()
if mobile_count > 0... | 用户序列化器类 | UserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""用户序列化器类"""
def validate_username(self, value):
"""校验用户名是否重复"""
<|body_0|>
def validate_mobile(self, value):
"""校验电话号码"""
<|body_1|>
def validate_allow(self, value):
"""校验是否同意用户协议"""
<|body_2|>
def validate(self... | stack_v2_sparse_classes_36k_train_027524 | 6,087 | no_license | [
{
"docstring": "校验用户名是否重复",
"name": "validate_username",
"signature": "def validate_username(self, value)"
},
{
"docstring": "校验电话号码",
"name": "validate_mobile",
"signature": "def validate_mobile(self, value)"
},
{
"docstring": "校验是否同意用户协议",
"name": "validate_allow",
"sig... | 5 | stack_v2_sparse_classes_30k_train_008033 | Implement the Python class `UserSerializer` described below.
Class description:
用户序列化器类
Method signatures and docstrings:
- def validate_username(self, value): 校验用户名是否重复
- def validate_mobile(self, value): 校验电话号码
- def validate_allow(self, value): 校验是否同意用户协议
- def validate(self, data): 1、校验两次密码是否一致 2、校验验证码
- def crea... | Implement the Python class `UserSerializer` described below.
Class description:
用户序列化器类
Method signatures and docstrings:
- def validate_username(self, value): 校验用户名是否重复
- def validate_mobile(self, value): 校验电话号码
- def validate_allow(self, value): 校验是否同意用户协议
- def validate(self, data): 1、校验两次密码是否一致 2、校验验证码
- def crea... | deb4deab281021305f5d6ad026539b933d2b014f | <|skeleton|>
class UserSerializer:
"""用户序列化器类"""
def validate_username(self, value):
"""校验用户名是否重复"""
<|body_0|>
def validate_mobile(self, value):
"""校验电话号码"""
<|body_1|>
def validate_allow(self, value):
"""校验是否同意用户协议"""
<|body_2|>
def validate(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSerializer:
"""用户序列化器类"""
def validate_username(self, value):
"""校验用户名是否重复"""
username_count = User.objects.filter(username=value).count()
if username_count > 0:
raise serializers.ValidationError('该用户名已注册')
return value
def validate_mobile(self, value)... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/users/serializers.py | Zhusea/duomei | train | 0 |
ad163d3a8e61fddc80a5e27edff15e7305566f16 | [
"if save_format.startswith(PTExportFormat.ONNX):\n split_format = save_format.split('_')\n opset = None\n if len(split_format) == 1:\n opset = PTExporter._ONNX_DEFAULT_OPSET\n elif len(split_format) == 2:\n opset = int(split_format[1])\n if opset is not None and opset <= 0:\n rai... | <|body_start_0|>
if save_format.startswith(PTExportFormat.ONNX):
split_format = save_format.split('_')
opset = None
if len(split_format) == 1:
opset = PTExporter._ONNX_DEFAULT_OPSET
elif len(split_format) == 2:
opset = int(split_for... | This class provides export of the compressed model to the ONNX format. | PTExporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_for... | stack_v2_sparse_classes_36k_train_027525 | 7,785 | permissive | [
{
"docstring": "Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_format dict: additional arguments for exporter",
"name": "parse_format",
"signature": "def parse_format(save_format: str) -> Tuple[str, dict]"
},
{
... | 4 | null | Implement the Python class `PTExporter` described below.
Class description:
This class provides export of the compressed model to the ONNX format.
Method signatures and docstrings:
- def parse_format(save_format: str) -> Tuple[str, dict]: Parse saving format to a short form and additional arguments. :param save_forma... | Implement the Python class `PTExporter` described below.
Class description:
This class provides export of the compressed model to the ONNX format.
Method signatures and docstrings:
- def parse_format(save_format: str) -> Tuple[str, dict]: Parse saving format to a short form and additional arguments. :param save_forma... | c027c8b43c4865d46b8de01d8350dd338ec5a874 | <|skeleton|>
class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_format dict: add... | the_stack_v2_python_sparse | nncf/torch/exporter.py | openvinotoolkit/nncf | train | 558 |
227c18d20e30a32f2ba104ad4b8b58a52db03fac | [
"with self.schema.table('practitest') as table:\n table.string('test_status', 20).default('No Run').change()\n pass",
"with self.schema.table('practitest') as table:\n table.string('test_status', 20).default('No Run').change()\n pass"
] | <|body_start_0|>
with self.schema.table('practitest') as table:
table.string('test_status', 20).default('No Run').change()
pass
<|end_body_0|>
<|body_start_1|>
with self.schema.table('practitest') as table:
table.string('test_status', 20).default('No Run').change()
... | AlterTestStatusPractitestDefaultValue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlterTestStatusPractitestDefaultValue:
def up(self):
"""Run the migrations."""
<|body_0|>
def down(self):
"""Revert the migrations."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with self.schema.table('practitest') as table:
table.stri... | stack_v2_sparse_classes_36k_train_027526 | 531 | no_license | [
{
"docstring": "Run the migrations.",
"name": "up",
"signature": "def up(self)"
},
{
"docstring": "Revert the migrations.",
"name": "down",
"signature": "def down(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005511 | Implement the Python class `AlterTestStatusPractitestDefaultValue` described below.
Class description:
Implement the AlterTestStatusPractitestDefaultValue class.
Method signatures and docstrings:
- def up(self): Run the migrations.
- def down(self): Revert the migrations. | Implement the Python class `AlterTestStatusPractitestDefaultValue` described below.
Class description:
Implement the AlterTestStatusPractitestDefaultValue class.
Method signatures and docstrings:
- def up(self): Run the migrations.
- def down(self): Revert the migrations.
<|skeleton|>
class AlterTestStatusPractitest... | 8033c98d7dc13cf5b53e5e4293083db8419809d1 | <|skeleton|>
class AlterTestStatusPractitestDefaultValue:
def up(self):
"""Run the migrations."""
<|body_0|>
def down(self):
"""Revert the migrations."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlterTestStatusPractitestDefaultValue:
def up(self):
"""Run the migrations."""
with self.schema.table('practitest') as table:
table.string('test_status', 20).default('No Run').change()
pass
def down(self):
"""Revert the migrations."""
with self.sche... | the_stack_v2_python_sparse | migrations/2017_12_25_132031_alter_test_status_practitest_default_value.py | nuraizatif/pavoGUI | train | 0 | |
d4da7eeb40a48b19e67553355b0f326528993243 | [
"_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)\nif not is_no_python_compiled_callable(compute_derivative):\n raise f'The derivative callable must be no_python compiled. The nameof the callable that must be compiled is {compute_derivative.__name__}'\nif return_cost_m... | <|body_start_0|>
_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)
if not is_no_python_compiled_callable(compute_derivative):
raise f'The derivative callable must be no_python compiled. The nameof the callable that must be compiled is {compute_deriv... | Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance) | _DdtwDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray,... | stack_v2_sparse_classes_36k_train_027527 | 9,863 | permissive | [
{
"docstring": "Create a no_python compiled ddtw distance alignment path callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Series can be different lengths. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array ... | 2 | stack_v2_sparse_classes_30k_train_017709 | Implement the Python class `_DdtwDistance` described below.
Class description:
Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)
Method signatures and docstrings:
- def ... | Implement the Python class `_DdtwDistance` described below.
Class description:
Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)
Method signatures and docstrings:
- def ... | fbe4af4d8419a01ada1e82da1aa63c0218d13edb | <|skeleton|>
class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _DdtwDistance:
"""Derivative dynamic time warping (ddtw) between two time series. Takes the slope based derivative of the series (using compute_derivative), then applies DTW (using the _cost_matrix from _DtwDistance)"""
def _distance_alignment_path_factory(self, x: np.ndarray, y: np.ndarray, return_cost_... | the_stack_v2_python_sparse | sktime/distances/_ddtw.py | jattenberg/sktime | train | 0 |
2c0818f89d9e4e49bc7563f18b5ce8e14b6baa14 | [
"if form_class is None:\n form_class = self.get_form_class()\nreturn form_class(**self.get_form_kwargs(form_class, empty=empty))",
"kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()}\nif not empty and self.request.method in ('POST', 'PUT'):\n kwargs.update({'data': self.request.POST, 'fil... | <|body_start_0|>
if form_class is None:
form_class = self.get_form_class()
return form_class(**self.get_form_kwargs(form_class, empty=empty))
<|end_body_0|>
<|body_start_1|>
kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()}
if not empty and self.request.m... | This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'form_fieldname_trigger' attributes. The firs... | MultiFormView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'for... | stack_v2_sparse_classes_36k_train_027528 | 5,377 | permissive | [
{
"docstring": "Returns an instance of the form to be used in this view. Modified to give the 'form_class' to 'get_form_kwargs' and accept 'empty' arg",
"name": "get_form",
"signature": "def get_form(self, form_class=None, empty=False)"
},
{
"docstring": "Returns the keyword arguments for instan... | 6 | stack_v2_sparse_classes_30k_train_012232 | Implement the Python class `MultiFormView` described below.
Class description:
This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms ... | Implement the Python class `MultiFormView` described below.
Class description:
This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms ... | 239326bbdad1e3ff58e7e9b503fbb7b75c8713f8 | <|skeleton|>
class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'form_fieldname_t... | the_stack_v2_python_sparse | project/manager_frontend/utils/views.py | RetroPie/RetroPie-Manager | train | 67 |
0518b552a4faa6d011c8a12dc5848a8000a9fa08 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) == 0:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"if list_objs is None:\n list_objs = []\ndicts = []\nfor elements in ra... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) == 0:
return '[]'
else:
return jso... | Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string rep... | stack_v2_sparse_classes_36k_train_027529 | 2,883 | no_license | [
{
"docstring": "Constructor method Args: id (int): id argument",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "returns the JSON string representation of list_dictionaries Args: list_dictonaries (list): list of dictionaries",
"name": "to_json_string",
"... | 6 | stack_v2_sparse_classes_30k_train_004665 | Implement the Python class `Base` described below.
Class description:
Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method Args: id (int): id argument
- def to_json_string(list_dictionaries): return... | Implement the Python class `Base` described below.
Class description:
Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method Args: id (int): id argument
- def to_json_string(list_dictionaries): return... | 77311f452e8d62145b5e7afe151557ed7a6d210a | <|skeleton|>
class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
<|body_0|>
def to_json_string(list_dictionaries):
"""returns the JSON string rep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""Base class with constructor method Args: None. Attributes: __nb_objects(int): id counter"""
def __init__(self, id=None):
"""Constructor method Args: id (int): id argument"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
s... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | Matteo-lu/holbertonschool-higher_level_programming | train | 0 |
061e1fb9eb2dca58b24515d898aa0b96007710be | [
"if not root:\n return None\nif root.left:\n root.left = self.sufficientSubset(root.left, limit=limit - root.val)\nif root.right:\n root.right = self.sufficientSubset(root.right, limit=limit - root.val)\nif not root.left and (not root.right):\n if root.val < limit:\n return None\nreturn root",
... | <|body_start_0|>
if not root:
return None
if root.left:
root.left = self.sufficientSubset(root.left, limit=limit - root.val)
if root.right:
root.right = self.sufficientSubset(root.right, limit=limit - root.val)
if not root.left and (not root.right):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
"""报错"""
<|body_0|>
def sufficientSubset2(self, root, limit):
""":type root: TreeNode :type limit: int :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_027530 | 1,986 | no_license | [
{
"docstring": "报错",
"name": "sufficientSubset",
"signature": "def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode"
},
{
"docstring": ":type root: TreeNode :type limit: int :rtype: TreeNode",
"name": "sufficientSubset2",
"signature": "def sufficientSubset2(self, root, limi... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode: 报错
- def sufficientSubset2(self, root, limit): :type root: TreeNode :type limit: int :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode: 报错
- def sufficientSubset2(self, root, limit): :type root: TreeNode :type limit: int :rtype: TreeNode
<|skele... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
"""报错"""
<|body_0|>
def sufficientSubset2(self, root, limit):
""":type root: TreeNode :type limit: int :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
"""报错"""
if not root:
return None
if root.left:
root.left = self.sufficientSubset(root.left, limit=limit - root.val)
if root.right:
root.right = self.sufficientSubs... | the_stack_v2_python_sparse | sufficientSubset.py | NeilWangziyu/Leetcode_py | train | 2 | |
26f763a7bd1b31dc5c83e3398c8ba2c586b7503c | [
"if not self.instance.pk:\n return True\nelif field in self.saved_data:\n return self.previous(field) != self.get_field_value(field)\nelse:\n raise FieldError('field \"%s\" not tracked' % field)",
"if not self.instance.pk:\n return {}\nsaved = self.saved_data.items()\ncurrent = self.current()\nreturn ... | <|body_start_0|>
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else:
raise FieldError('field "%s" not tracked' % field)
<|end_body_0|>
<|body_start_1|>
if not self.instan... | ModelInstanceTracker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
<|body_0|>
def changed(self):
"""Returns dict of fields that changed since save (with old values)"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_027531 | 7,971 | permissive | [
{
"docstring": "Returns ``True`` if field has changed from currently saved value",
"name": "has_changed",
"signature": "def has_changed(self, field)"
},
{
"docstring": "Returns dict of fields that changed since save (with old values)",
"name": "changed",
"signature": "def changed(self)"
... | 2 | stack_v2_sparse_classes_30k_train_006666 | Implement the Python class `ModelInstanceTracker` described below.
Class description:
Implement the ModelInstanceTracker class.
Method signatures and docstrings:
- def has_changed(self, field): Returns ``True`` if field has changed from currently saved value
- def changed(self): Returns dict of fields that changed si... | Implement the Python class `ModelInstanceTracker` described below.
Class description:
Implement the ModelInstanceTracker class.
Method signatures and docstrings:
- def has_changed(self, field): Returns ``True`` if field has changed from currently saved value
- def changed(self): Returns dict of fields that changed si... | ce2558602ddad31873d7129f25b1cc61895b9939 | <|skeleton|>
class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
<|body_0|>
def changed(self):
"""Returns dict of fields that changed since save (with old values)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelInstanceTracker:
def has_changed(self, field):
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
else... | the_stack_v2_python_sparse | myenv/lib/python3.5/site-packages/model_utils/tracker.py | rupeshparab/techscan | train | 1 | |
a452167fe1f159a29648f4e30b4ee5bbad0d38bd | [
"target = (len(nums1) + len(nums2)) // 2\nmedian_index = self.get_index(nums1, nums2, target)\nif (len(nums1) + len(nums2)) % 2 == 1:\n return [nums1, nums2][median_index[0]][median_index[1]]\nelse:\n median_index1 = self.get_index(nums1, nums2, target - 1)\n return ([nums1, nums2][median_index[0]][median_... | <|body_start_0|>
target = (len(nums1) + len(nums2)) // 2
median_index = self.get_index(nums1, nums2, target)
if (len(nums1) + len(nums2)) % 2 == 1:
return [nums1, nums2][median_index[0]][median_index[1]]
else:
median_index1 = self.get_index(nums1, nums2, target - ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def get_index(self, nums1, nums2, target):
""":param nums1: list :param nums2: list :param target: int :return: list[int, int] 指明tar... | stack_v2_sparse_classes_36k_train_027532 | 2,657 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":param nums1: list :param nums2: list :param target: int :return: list[int, int] 指明target指出的索引位于哪个数组的哪个... | 3 | stack_v2_sparse_classes_30k_train_016398 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def get_index(self, nums1, nums2, target): :param nums1: list :param... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def get_index(self, nums1, nums2, target): :param nums1: list :param... | 2306c494ea8f754aa4b954732f1331f3922235c1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def get_index(self, nums1, nums2, target):
""":param nums1: list :param nums2: list :param target: int :return: list[int, int] 指明tar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
target = (len(nums1) + len(nums2)) // 2
median_index = self.get_index(nums1, nums2, target)
if (len(nums1) + len(nums2)) % 2 == 1:
return [num... | the_stack_v2_python_sparse | findMedianSortedArrays.py | ZhangNANPy/LeetCode | train | 0 | |
957af1f455c3986a871f29441c61d050dc21fe4c | [
"try:\n account_id = resource_utils.get_account_id(request)\n if account_id is None:\n return resource_utils.account_required_response()\n if not authorized(account_id, jwt):\n return resource_utils.unauthorized_error_response(account_id)\n username = 'anonymous'\n user = User.find_by_j... | <|body_start_0|>
try:
account_id = resource_utils.get_account_id(request)
if account_id is None:
return resource_utils.account_required_response()
if not authorized(account_id, jwt):
return resource_utils.unauthorized_error_response(account_id)... | Resource for executing draft statements. | DraftResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DraftResource:
"""Resource for executing draft statements."""
def get():
"""Get the list of draft statements belonging to the header account ID."""
<|body_0|>
def post():
"""Create a new draft statement."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027533 | 9,959 | permissive | [
{
"docstring": "Get the list of draft statements belonging to the header account ID.",
"name": "get",
"signature": "def get()"
},
{
"docstring": "Create a new draft statement.",
"name": "post",
"signature": "def post()"
}
] | 2 | stack_v2_sparse_classes_30k_train_020833 | Implement the Python class `DraftResource` described below.
Class description:
Resource for executing draft statements.
Method signatures and docstrings:
- def get(): Get the list of draft statements belonging to the header account ID.
- def post(): Create a new draft statement. | Implement the Python class `DraftResource` described below.
Class description:
Resource for executing draft statements.
Method signatures and docstrings:
- def get(): Get the list of draft statements belonging to the header account ID.
- def post(): Create a new draft statement.
<|skeleton|>
class DraftResource:
... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class DraftResource:
"""Resource for executing draft statements."""
def get():
"""Get the list of draft statements belonging to the header account ID."""
<|body_0|>
def post():
"""Create a new draft statement."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DraftResource:
"""Resource for executing draft statements."""
def get():
"""Get the list of draft statements belonging to the header account ID."""
try:
account_id = resource_utils.get_account_id(request)
if account_id is None:
return resource_utils... | the_stack_v2_python_sparse | ppr-api/src/ppr_api/resources/drafts.py | bcgov/ppr | train | 4 |
e7f73645d7fbd6c6c45a594b99c50a498023ec97 | [
"del params\n\ndef serving_input_receiver_fn():\n \"\"\"Create the ServingInputReceiver to export a saved model.\n\n Returns:\n An instance of ServingInputReceiver.\n \"\"\"\n flat_feature_spec = tensorspec_utils.flatten_spec_structure(self._get_input_features_for_receiver_fn())\n required... | <|body_start_0|>
del params
def serving_input_receiver_fn():
"""Create the ServingInputReceiver to export a saved model.
Returns:
An instance of ServingInputReceiver.
"""
flat_feature_spec = tensorspec_utils.flatten_spec_structure(sel... | Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-preprocessing. | DefaultExportGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultExportGenerator:
"""Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-preprocessing."""
def create_serving_in... | stack_v2_sparse_classes_36k_train_027534 | 5,195 | permissive | [
{
"docstring": "Create a serving input receiver for numpy. Args: params: An optional dict of hyper parameters that will be passed into input_fn and model_fn. Keys are names of parameters, values are basic python types. There are reserved keys for TPUEstimator, including 'batch_size'. Returns: serving_input_rece... | 2 | stack_v2_sparse_classes_30k_train_002749 | Implement the Python class `DefaultExportGenerator` described below.
Class description:
Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-prepr... | Implement the Python class `DefaultExportGenerator` described below.
Class description:
Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-prepr... | f93f378db3183cceaad1b96828b199cf40cad606 | <|skeleton|>
class DefaultExportGenerator:
"""Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-preprocessing."""
def create_serving_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultExportGenerator:
"""Class to manage assets related to exporting a model. Attributes: export_raw_receivers: Whether to export receiver_fns which do not have preprocessing enabled. This is useful for serving using Servo, in conjunction with client-preprocessing."""
def create_serving_input_receiver_... | the_stack_v2_python_sparse | export_generators/default_export_generator.py | google-research/tensor2robot | train | 539 |
f2f95dc784a313cf8dfa126ea23d817c2bddf86b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ObjectDefinition()",
"from .attribute_definition import AttributeDefinition\nfrom .object_definition_metadata_entry import ObjectDefinitionMetadataEntry\nfrom .attribute_definition import AttributeDefinition\nfrom .object_definition_me... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ObjectDefinition()
<|end_body_0|>
<|body_start_1|>
from .attribute_definition import AttributeDefinition
from .object_definition_metadata_entry import ObjectDefinitionMetadataEntry
... | ObjectDefinition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectDefinition:
"""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 R... | stack_v2_sparse_classes_36k_train_027535 | 3,884 | 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: ObjectDefinition",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `ObjectDefinition` described below.
Class description:
Implement the ObjectDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectDefinition: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ObjectDefinition` described below.
Class description:
Implement the ObjectDefinition class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectDefinition: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ObjectDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectDefinition:
"""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 R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectDefinition:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectDefinition:
"""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: Object... | the_stack_v2_python_sparse | msgraph/generated/models/object_definition.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
131112e81e163f00c063859972a8530cacee8fe3 | [
"def back_track(left=1, curr=[]):\n if len(curr) == k:\n output.append(curr[:])\n for i in range(left, n + 1):\n curr.append(i)\n back_track(i + 1, curr)\n curr.pop()\noutput = []\nback_track()\nreturn output",
"nums = list(range(1, k + 1)) + [n + 1]\nleft, output = (0, [])\nwhil... | <|body_start_0|>
def back_track(left=1, curr=[]):
if len(curr) == k:
output.append(curr[:])
for i in range(left, n + 1):
curr.append(i)
back_track(i + 1, curr)
curr.pop()
output = []
back_track()
retu... | Combination | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Combination:
def combine(self, n: int, k: int) -> List[List[int]]:
"""Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :return:"""
<|body_0|>
def combine_(self, n: int, k: int) -> List[List[int]]:
"""A... | stack_v2_sparse_classes_36k_train_027536 | 1,490 | no_license | [
{
"docstring": "Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :return:",
"name": "combine",
"signature": "def combine(self, n: int, k: int) -> List[List[int]]"
},
{
"docstring": "Approach: Lexicographic (binary) sorted combinat... | 2 | stack_v2_sparse_classes_30k_train_013328 | Implement the Python class `Combination` described below.
Class description:
Implement the Combination class.
Method signatures and docstrings:
- def combine(self, n: int, k: int) -> List[List[int]]: Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :re... | Implement the Python class `Combination` described below.
Class description:
Implement the Combination class.
Method signatures and docstrings:
- def combine(self, n: int, k: int) -> List[List[int]]: Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :re... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Combination:
def combine(self, n: int, k: int) -> List[List[int]]:
"""Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :return:"""
<|body_0|>
def combine_(self, n: int, k: int) -> List[List[int]]:
"""A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Combination:
def combine(self, n: int, k: int) -> List[List[int]]:
"""Approach: Back Tracking (Recursion) Time Complexity: O(k * c`k ,n) Space Complexity: O(C`k ,n) :param n: :param k: :return:"""
def back_track(left=1, curr=[]):
if len(curr) == k:
output.append(cur... | the_stack_v2_python_sparse | data_structures/combinations.py | Shiv2157k/leet_code | train | 1 | |
a8ba630c9895689b86cba7dd2a23f25c0217b478 | [
"self.attach_to_self: Set[str] = set()\nself.attach_to_first: Set[str] = set()\nself.attach_to_last: Set[str] = set()\nbehaviors = (self.attach_to_self, self.attach_to_first, self.attach_to_last)\nfor sample in samples:\n for word in sample.sentence:\n if not any((word in behavior for behavior in behavior... | <|body_start_0|>
self.attach_to_self: Set[str] = set()
self.attach_to_first: Set[str] = set()
self.attach_to_last: Set[str] = set()
behaviors = (self.attach_to_self, self.attach_to_first, self.attach_to_last)
for sample in samples:
for word in sample.sentence:
... | Construct arbitrary parse "trees" for all samples. | ControlDEPIndexer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlDEPIndexer:
"""Construct arbitrary parse "trees" for all samples."""
def __init__(self, samples: Sequence[ptb.Sample]):
"""Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Always attach word to itself. - Always attach word to first w... | stack_v2_sparse_classes_36k_train_027537 | 10,415 | permissive | [
{
"docstring": "Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Always attach word to itself. - Always attach word to first word in sentence. - Always attach word to last word in sentence. Args: samples (Sequence[ptb.PTBSample]): All samples for which to generate tag... | 2 | stack_v2_sparse_classes_30k_train_018620 | Implement the Python class `ControlDEPIndexer` described below.
Class description:
Construct arbitrary parse "trees" for all samples.
Method signatures and docstrings:
- def __init__(self, samples: Sequence[ptb.Sample]): Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Alwa... | Implement the Python class `ControlDEPIndexer` described below.
Class description:
Construct arbitrary parse "trees" for all samples.
Method signatures and docstrings:
- def __init__(self, samples: Sequence[ptb.Sample]): Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Alwa... | 3e4af6644a4db7fdf48bc40c5de4815f9db52a6e | <|skeleton|>
class ControlDEPIndexer:
"""Construct arbitrary parse "trees" for all samples."""
def __init__(self, samples: Sequence[ptb.Sample]):
"""Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Always attach word to itself. - Always attach word to first w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControlDEPIndexer:
"""Construct arbitrary parse "trees" for all samples."""
def __init__(self, samples: Sequence[ptb.Sample]):
"""Map each word type to a dependency arc behavior. We sample uniformly from three behaviors: - Always attach word to itself. - Always attach word to first word in senten... | the_stack_v2_python_sparse | ldp/tasks/dep.py | evandez/low-dimensional-probing | train | 3 |
a8c55b3ddd7df48597f06f47a0b647cc95e6dfdb | [
"pygame.sprite.Sprite.__init__(self)\nsprite_sheet = SpriteSheet('Golem.png')\nimage = sprite_sheet.get_image(262, 471, 272, 47)\nself.image = image\nself.rect = self.image.get_rect()\nself.rect.x = 400\nself.rect.y = -47\nself.change_y = 0\nself.bounce = 0\nself.count = 0\nself.beginCount = False",
"if self.rect... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
sprite_sheet = SpriteSheet('Golem.png')
image = sprite_sheet.get_image(262, 471, 272, 47)
self.image = image
self.rect = self.image.get_rect()
self.rect.x = 400
self.rect.y = -47
self.change_y = 0
... | win | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite ... | stack_v2_sparse_classes_36k_train_027538 | 2,788 | no_license | [
{
"docstring": "This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite self.rect.y: The y-position of the s... | 2 | stack_v2_sparse_classes_30k_train_009981 | Implement the Python class `win` described below.
Class description:
Implement the win class.
Method signatures and docstrings:
- def __init__(self): This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represen... | Implement the Python class `win` described below.
Class description:
Implement the win class.
Method signatures and docstrings:
- def __init__(self): This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represen... | 56fbcfc786dfc373f477270468f06e31b6271749 | <|skeleton|>
class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class win:
def __init__(self):
"""This initializes the boss Variables: sprite_sheet: The spritesheet to where the custom sprites came from image: Holds the custom self.image: The sprite used to represent self.rect: This creates the shape of the sprite self.rect.x: The x-position of the sprite self.rect.y: T... | the_stack_v2_python_sparse | Doki Doki Island/winning.py | cashpop5000/DokiProject | train | 0 | |
ef09edcd8877f4ccf17e1e13af43209a0e97b290 | [
"resource_path = '/submissions/{id}'\nmethod = 'GET'\nhost_params = {'id': _id}\nreturn self.api_client.call_api(resource_path, method, host_params)",
"if isinstance(ids, (list, int)) == False:\n raise ValueError('getSubmissions method accepts only list or integer.')\nif isinstance(ids, list):\n ids = ','.j... | <|body_start_0|>
resource_path = '/submissions/{id}'
method = 'GET'
host_params = {'id': _id}
return self.api_client.call_api(resource_path, method, host_params)
<|end_body_0|>
<|body_start_1|>
if isinstance(ids, (list, int)) == False:
raise ValueError('getSubmission... | ProblemsApiSubmissions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProblemsApiSubmissions:
def get(self, _id):
"""Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngineException: code 401 for invalid access token :raises SphereEngineException: code 404 for non existing submissi... | stack_v2_sparse_classes_36k_train_027539 | 23,159 | no_license | [
{
"docstring": "Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngineException: code 401 for invalid access token :raises SphereEngineException: code 404 for non existing submission",
"name": "get",
"signature": "def get(self,... | 3 | stack_v2_sparse_classes_30k_train_004114 | Implement the Python class `ProblemsApiSubmissions` described below.
Class description:
Implement the ProblemsApiSubmissions class.
Method signatures and docstrings:
- def get(self, _id): Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngin... | Implement the Python class `ProblemsApiSubmissions` described below.
Class description:
Implement the ProblemsApiSubmissions class.
Method signatures and docstrings:
- def get(self, _id): Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngin... | 2b9ddbea0f9173754dfeb4f4e651a7c5a275bf52 | <|skeleton|>
class ProblemsApiSubmissions:
def get(self, _id):
"""Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngineException: code 401 for invalid access token :raises SphereEngineException: code 404 for non existing submissi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProblemsApiSubmissions:
def get(self, _id):
"""Fetch submission details :param id: submission id :type _id: integer :returns: submission details :rtype: json :raises SphereEngineException: code 401 for invalid access token :raises SphereEngineException: code 404 for non existing submission"""
... | the_stack_v2_python_sparse | build/lib/sphere_engine/apis/problems.py | rucamedia/python-client | train | 1 | |
ef78abb356729777893a7098784676d3d922f8cd | [
"self.dicts = []\nif not root:\n return []\n\ndef dfs(root, count):\n if count >= len(self.dicts):\n self.dicts.append(root.val)\n else:\n self.dicts[count] = max(self.dicts[count], root.val)\n if root.left:\n dfs(root.left, count + 1)\n if root.right:\n dfs(root.right, co... | <|body_start_0|>
self.dicts = []
if not root:
return []
def dfs(root, count):
if count >= len(self.dicts):
self.dicts.append(root.val)
else:
self.dicts[count] = max(self.dicts[count], root.val)
if root.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int] 88ms"""
<|body_0|>
def largestValues_1(self, root):
""":type root: TreeNode :rtype: List[int] 72ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dicts = []
... | stack_v2_sparse_classes_36k_train_027540 | 1,948 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int] 88ms",
"name": "largestValues",
"signature": "def largestValues(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int] 72ms",
"name": "largestValues_1",
"signature": "def largestValues_1(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestValues(self, root): :type root: TreeNode :rtype: List[int] 88ms
- def largestValues_1(self, root): :type root: TreeNode :rtype: List[int] 72ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestValues(self, root): :type root: TreeNode :rtype: List[int] 88ms
- def largestValues_1(self, root): :type root: TreeNode :rtype: List[int] 72ms
<|skeleton|>
class Solu... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int] 88ms"""
<|body_0|>
def largestValues_1(self, root):
""":type root: TreeNode :rtype: List[int] 72ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestValues(self, root):
""":type root: TreeNode :rtype: List[int] 88ms"""
self.dicts = []
if not root:
return []
def dfs(root, count):
if count >= len(self.dicts):
self.dicts.append(root.val)
else:
... | the_stack_v2_python_sparse | FindLargestValueInEachTreeRow_MID_515.py | 953250587/leetcode-python | train | 2 | |
ce5ff41227402d99412c197b2dcfd4a113492449 | [
"super(FLAME, self).__init__(*args, **kwargs)\nself.keypoint_src = keypoint_src\nself.keypoint_dst = keypoint_dst\nself.keypoint_approximate = keypoint_approximate\nself.num_verts = self.get_num_verts()\nself.num_faces = self.get_num_faces()\nself.num_joints = get_keypoint_num(convention=self.keypoint_dst)",
"fla... | <|body_start_0|>
super(FLAME, self).__init__(*args, **kwargs)
self.keypoint_src = keypoint_src
self.keypoint_dst = keypoint_dst
self.keypoint_approximate = keypoint_approximate
self.num_verts = self.get_num_verts()
self.num_faces = self.get_num_faces()
self.num_jo... | Extension of the official FLAME implementation. | FLAME | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of ... | stack_v2_sparse_classes_36k_train_027541 | 6,673 | permissive | [
{
"docstring": "Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoints. This convention is used for keypoints obtained from joint regressors. Keypoints then undergo conversion into keypoint_dst convention. keypoint_dst: destination convention of keypoints. This conve... | 2 | stack_v2_sparse_classes_30k_train_021350 | Implement the Python class `FLAME` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments for ... | Implement the Python class `FLAME` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments for ... | 9431addec32f7fbeffa1786927a854c0ab79d9ea | <|skeleton|>
class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FLAME:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoints. Th... | the_stack_v2_python_sparse | mmhuman3d/models/body_models/flame.py | open-mmlab/mmhuman3d | train | 966 |
eed44eaaa3760bb655bc6ed9266cdae92e75ff17 | [
"logging.info('Getting: %s', path)\ncontent_type, _ = mimetypes.guess_type(path)\nif content_type:\n self.set_header('Content-Type', content_type)\ntry:\n self.write(package_manager.read_package(path, self.get_argument('user.name')))\nexcept (KeyError, IOError):\n logging.error(traceback.format_exc())\n ... | <|body_start_0|>
logging.info('Getting: %s', path)
content_type, _ = mimetypes.guess_type(path)
if content_type:
self.set_header('Content-Type', content_type)
try:
self.write(package_manager.read_package(path, self.get_argument('user.name')))
except (KeyEr... | PackageHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageHandler:
def get(self, path):
"""REST interface for getting packages from the repository :param path: :return:"""
<|body_0|>
def put(self, path):
"""REST interface for adding packages to the repository :param path: :return:"""
<|body_1|>
def delet... | stack_v2_sparse_classes_36k_train_027542 | 8,267 | permissive | [
{
"docstring": "REST interface for getting packages from the repository :param path: :return:",
"name": "get",
"signature": "def get(self, path)"
},
{
"docstring": "REST interface for adding packages to the repository :param path: :return:",
"name": "put",
"signature": "def put(self, pat... | 3 | stack_v2_sparse_classes_30k_train_018176 | Implement the Python class `PackageHandler` described below.
Class description:
Implement the PackageHandler class.
Method signatures and docstrings:
- def get(self, path): REST interface for getting packages from the repository :param path: :return:
- def put(self, path): REST interface for adding packages to the re... | Implement the Python class `PackageHandler` described below.
Class description:
Implement the PackageHandler class.
Method signatures and docstrings:
- def get(self, path): REST interface for getting packages from the repository :param path: :return:
- def put(self, path): REST interface for adding packages to the re... | 69af5e51f9effaafba599b5dc2ea4ff3988127dc | <|skeleton|>
class PackageHandler:
def get(self, path):
"""REST interface for getting packages from the repository :param path: :return:"""
<|body_0|>
def put(self, path):
"""REST interface for adding packages to the repository :param path: :return:"""
<|body_1|>
def delet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackageHandler:
def get(self, path):
"""REST interface for getting packages from the repository :param path: :return:"""
logging.info('Getting: %s', path)
content_type, _ = mimetypes.guess_type(path)
if content_type:
self.set_header('Content-Type', content_type)
... | the_stack_v2_python_sparse | api/src/main/resources/package_repository_rest_server.py | pndaproject/platform-package-repository | train | 1 | |
db526939a2429897c2a3006edbc6c6b135715c77 | [
"if not root:\n return '#'\nq = [root]\nserial = [str(root.val)]\nwhile q:\n newq = []\n for x in q:\n if not x.left:\n serial.append('#')\n else:\n serial.append(str(x.left.val))\n newq.append(x.left)\n if not x.right:\n serial.append('#')\n... | <|body_start_0|>
if not root:
return '#'
q = [root]
serial = [str(root.val)]
while q:
newq = []
for x in q:
if not x.left:
serial.append('#')
else:
serial.append(str(x.left.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_027543 | 3,922 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 752ac00bea40be1e3794d80aa7b2be58c0a548f6 | <|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 '#'
q = [root]
serial = [str(root.val)]
while q:
newq = []
for x in q:
if not x.left:
... | the_stack_v2_python_sparse | Code/Serialize and Deserialize Binary Tree.py | mws19901118/Leetcode | train | 0 | |
3c6b9405778e5c3d928822ad42ab3a0378c73b2d | [
"head_image = validated_data.get('head_image')\nis_upload, file_information = storage.upload(file=head_image)\nreturn (is_upload, file_information)",
"head_image = validated_data.get('head_image')\nis_update, file_information = storage.update(bytes(head_image.read()), remote_file_id)\nreturn is_update",
"try:\n... | <|body_start_0|>
head_image = validated_data.get('head_image')
is_upload, file_information = storage.upload(file=head_image)
return (is_upload, file_information)
<|end_body_0|>
<|body_start_1|>
head_image = validated_data.get('head_image')
is_update, file_information = storage.u... | 头像修改序列化器 | HeadImageSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeadImageSerializer:
"""头像修改序列化器"""
def _upload(validated_data, storage):
"""上传用户新的头像"""
<|body_0|>
def _update(validated_data, remote_file_id, storage):
"""存在问题!!! 更新用户头像, 在用户保存头像后"""
<|body_1|>
def update_head_image(self, instance, validated_data, ... | stack_v2_sparse_classes_36k_train_027544 | 5,759 | permissive | [
{
"docstring": "上传用户新的头像",
"name": "_upload",
"signature": "def _upload(validated_data, storage)"
},
{
"docstring": "存在问题!!! 更新用户头像, 在用户保存头像后",
"name": "_update",
"signature": "def _update(validated_data, remote_file_id, storage)"
},
{
"docstring": "同步更新FastDfs服务器和数据库的头像",
"n... | 3 | null | Implement the Python class `HeadImageSerializer` described below.
Class description:
头像修改序列化器
Method signatures and docstrings:
- def _upload(validated_data, storage): 上传用户新的头像
- def _update(validated_data, remote_file_id, storage): 存在问题!!! 更新用户头像, 在用户保存头像后
- def update_head_image(self, instance, validated_data, stor... | Implement the Python class `HeadImageSerializer` described below.
Class description:
头像修改序列化器
Method signatures and docstrings:
- def _upload(validated_data, storage): 上传用户新的头像
- def _update(validated_data, remote_file_id, storage): 存在问题!!! 更新用户头像, 在用户保存头像后
- def update_head_image(self, instance, validated_data, stor... | 13cb59130d15e782f78bc5148409bef0f1c516e0 | <|skeleton|>
class HeadImageSerializer:
"""头像修改序列化器"""
def _upload(validated_data, storage):
"""上传用户新的头像"""
<|body_0|>
def _update(validated_data, remote_file_id, storage):
"""存在问题!!! 更新用户头像, 在用户保存头像后"""
<|body_1|>
def update_head_image(self, instance, validated_data, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeadImageSerializer:
"""头像修改序列化器"""
def _upload(validated_data, storage):
"""上传用户新的头像"""
head_image = validated_data.get('head_image')
is_upload, file_information = storage.upload(file=head_image)
return (is_upload, file_information)
def _update(validated_data, remote... | the_stack_v2_python_sparse | user_app/serializers/individual_info_serializers.py | lmyfzx/Django-Mall | train | 0 |
c39112dc88eaf85969b92f02b681899a79b2b5c4 | [
"submission, submission_guids = submission\nif submission is None:\n raise werkzeug.exceptions.NotFound\nreturn submission",
"context = api.commit_or_abort(db.session, default_error_message='Failed to update Submission details.')\nwith context:\n parameters.PatchSubmissionDetailsParameters.perform_patch(arg... | <|body_start_0|>
submission, submission_guids = submission
if submission is None:
raise werkzeug.exceptions.NotFound
return submission
<|end_body_0|>
<|body_start_1|>
context = api.commit_or_abort(db.session, default_error_message='Failed to update Submission details.')
... | Manipulations with a specific Submission. | SubmissionByID | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubmissionByID:
"""Manipulations with a specific Submission."""
def get(self, submission):
"""Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, check SubmissionManager for remote Submission by UUID, if not... | stack_v2_sparse_classes_36k_train_027545 | 9,991 | permissive | [
{
"docstring": "Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, check SubmissionManager for remote Submission by UUID, if not found, throw 404 as intended",
"name": "get",
"signature": "def get(self, submission)"
},
{
... | 3 | null | Implement the Python class `SubmissionByID` described below.
Class description:
Manipulations with a specific Submission.
Method signatures and docstrings:
- def get(self, submission): Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, chec... | Implement the Python class `SubmissionByID` described below.
Class description:
Manipulations with a specific Submission.
Method signatures and docstrings:
- def get(self, submission): Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, chec... | 821c9cae985751a129b3be1ad08b8ad295d0a3d8 | <|skeleton|>
class SubmissionByID:
"""Manipulations with a specific Submission."""
def get(self, submission):
"""Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, check SubmissionManager for remote Submission by UUID, if not... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubmissionByID:
"""Manipulations with a specific Submission."""
def get(self, submission):
"""Get Submission details by ID. If submission is not found locally in database, a None submission will be returned. In this event, check SubmissionManager for remote Submission by UUID, if not found, throw... | the_stack_v2_python_sparse | app/modules/submissions/resources.py | Emily-Ke/houston | train | 0 |
25b428aed914a0383454d5c011f87eee65e8dd25 | [
"self.id = id\nself.request = request\nself.game = game",
"cards = []\nrelevantCards = self.request.relevantCards\nif relevantCards is not None:\n cards = GetCardListJSON(relevantCards, self.game, includeActions=includeActions)\nreturn {'type': 'CHOICE', 'id': self.id, 'options': [option.description for option... | <|body_start_0|>
self.id = id
self.request = request
self.game = game
<|end_body_0|>
<|body_start_1|>
cards = []
relevantCards = self.request.relevantCards
if relevantCards is not None:
cards = GetCardListJSON(relevantCards, self.game, includeActions=includeA... | A Wrapper for a Choose Option Request that handles its conversion to JSON | ChooseOptionRequestWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChooseOptionRequestWrapper:
"""A Wrapper for a Choose Option Request that handles its conversion to JSON"""
def __init__(self, id, request, game):
"""Initialize the Request Wrapper"""
<|body_0|>
def toJSON(self, includeActions=False):
"""Return the request as a J... | stack_v2_sparse_classes_36k_train_027546 | 892 | no_license | [
{
"docstring": "Initialize the Request Wrapper",
"name": "__init__",
"signature": "def __init__(self, id, request, game)"
},
{
"docstring": "Return the request as a JSON Dictionary",
"name": "toJSON",
"signature": "def toJSON(self, includeActions=False)"
}
] | 2 | null | Implement the Python class `ChooseOptionRequestWrapper` described below.
Class description:
A Wrapper for a Choose Option Request that handles its conversion to JSON
Method signatures and docstrings:
- def __init__(self, id, request, game): Initialize the Request Wrapper
- def toJSON(self, includeActions=False): Retu... | Implement the Python class `ChooseOptionRequestWrapper` described below.
Class description:
A Wrapper for a Choose Option Request that handles its conversion to JSON
Method signatures and docstrings:
- def __init__(self, id, request, game): Initialize the Request Wrapper
- def toJSON(self, includeActions=False): Retu... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class ChooseOptionRequestWrapper:
"""A Wrapper for a Choose Option Request that handles its conversion to JSON"""
def __init__(self, id, request, game):
"""Initialize the Request Wrapper"""
<|body_0|>
def toJSON(self, includeActions=False):
"""Return the request as a J... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChooseOptionRequestWrapper:
"""A Wrapper for a Choose Option Request that handles its conversion to JSON"""
def __init__(self, id, request, game):
"""Initialize the Request Wrapper"""
self.id = id
self.request = request
self.game = game
def toJSON(self, includeActions... | the_stack_v2_python_sparse | src/Server/Game/Requests/choose_option_request_wrapper.py | dfwarden/DeckBuilding | train | 0 |
4d733c4aefc460de5b36fbc0fb046509e030af71 | [
"alloy_type_set = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False)\ndata = {'alloy_type_set': alloy_type_set}\nreturn render(request, 'admin/alloy/alloy_edit.html', context=data)",
"alloy_query = alloy_model.Alloy.objects.only('name').filter(is_delete=False)\ntry:\n alloy_json_data = re... | <|body_start_0|>
alloy_type_set = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False)
data = {'alloy_type_set': alloy_type_set}
return render(request, 'admin/alloy/alloy_edit.html', context=data)
<|end_body_0|>
<|body_start_1|>
alloy_query = alloy_model.Alloy.object... | AlloyAdd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlloyAdd:
def get(self, request):
"""添加页面展示 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新合金添加 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
alloy_type_set = alloy_model.AlloyType.objects.only('id', '... | stack_v2_sparse_classes_36k_train_027547 | 11,849 | no_license | [
{
"docstring": "添加页面展示 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新合金添加 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019207 | Implement the Python class `AlloyAdd` described below.
Class description:
Implement the AlloyAdd class.
Method signatures and docstrings:
- def get(self, request): 添加页面展示 :param request: :return:
- def post(self, request): 新合金添加 :param request: :return: | Implement the Python class `AlloyAdd` described below.
Class description:
Implement the AlloyAdd class.
Method signatures and docstrings:
- def get(self, request): 添加页面展示 :param request: :return:
- def post(self, request): 新合金添加 :param request: :return:
<|skeleton|>
class AlloyAdd:
def get(self, request):
... | 063332d2a5e2ddabf800817f02074b4f5c162ade | <|skeleton|>
class AlloyAdd:
def get(self, request):
"""添加页面展示 :param request: :return:"""
<|body_0|>
def post(self, request):
"""新合金添加 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlloyAdd:
def get(self, request):
"""添加页面展示 :param request: :return:"""
alloy_type_set = alloy_model.AlloyType.objects.only('id', 'type').filter(is_delete=False)
data = {'alloy_type_set': alloy_type_set}
return render(request, 'admin/alloy/alloy_edit.html', context=data)
d... | the_stack_v2_python_sparse | sfs/apps/alloy/views.py | Hx-someone/sfs-1 | train | 0 | |
78919e373454defb7a466601f2df250c23758afc | [
"try:\n response = requests.post(token_validation_url, json=token)\n if 200 <= response.status_code <= 299:\n return (response.json(), response.status_code)\n elif 400 <= response.status_code <= 499:\n return (response.json(), response.status_code)\nexcept requests.exceptions.ConnectionError:... | <|body_start_0|>
try:
response = requests.post(token_validation_url, json=token)
if 200 <= response.status_code <= 299:
return (response.json(), response.status_code)
elif 400 <= response.status_code <= 499:
return (response.json(), response.st... | AuthService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthService:
def token_validation(token):
""":param token: :return:"""
<|body_0|>
def user_info_collection(request_data):
""":param request_data: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
response = requests.post(toke... | stack_v2_sparse_classes_36k_train_027548 | 1,510 | no_license | [
{
"docstring": ":param token: :return:",
"name": "token_validation",
"signature": "def token_validation(token)"
},
{
"docstring": ":param request_data: :return:",
"name": "user_info_collection",
"signature": "def user_info_collection(request_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018155 | Implement the Python class `AuthService` described below.
Class description:
Implement the AuthService class.
Method signatures and docstrings:
- def token_validation(token): :param token: :return:
- def user_info_collection(request_data): :param request_data: :return: | Implement the Python class `AuthService` described below.
Class description:
Implement the AuthService class.
Method signatures and docstrings:
- def token_validation(token): :param token: :return:
- def user_info_collection(request_data): :param request_data: :return:
<|skeleton|>
class AuthService:
def token_... | 98167fd813a9cdec2e8dbb01c86688856b969553 | <|skeleton|>
class AuthService:
def token_validation(token):
""":param token: :return:"""
<|body_0|>
def user_info_collection(request_data):
""":param request_data: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthService:
def token_validation(token):
""":param token: :return:"""
try:
response = requests.post(token_validation_url, json=token)
if 200 <= response.status_code <= 299:
return (response.json(), response.status_code)
elif 400 <= response.... | the_stack_v2_python_sparse | api_gateway/applibs/auth_service.py | vubon/micro-services | train | 2 | |
ebcffbf9dd917968fd195e6fbf4d98370e704ca5 | [
"distance = len(words)\nidx1 = idx2 = -1\nfor i, w in enumerate(words):\n if w == word1:\n idx1 = i\n if w == word2:\n idx2 = i\n if idx2 != -1 and idx1 != -1:\n distance = min(distance, abs(idx1 - idx2))\nreturn distance",
"distance = len(words)\nidx1 = idx2 = -1\nfor i, w in enumer... | <|body_start_0|>
distance = len(words)
idx1 = idx2 = -1
for i, w in enumerate(words):
if w == word1:
idx1 = i
if w == word2:
idx2 = i
if idx2 != -1 and idx1 != -1:
distance = min(distance, abs(idx1 - idx2))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: list[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistanceEqual(self, words, word1, word2):
""":type words: list[str] :type word1: str :type word2: str :rtype: ... | stack_v2_sparse_classes_36k_train_027549 | 2,113 | no_license | [
{
"docstring": ":type words: list[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistance",
"signature": "def shortestDistance(self, words, word1, word2)"
},
{
"docstring": ":type words: list[str] :type word1: str :type word2: str :rtype: int",
"name": "shortestDistanc... | 2 | stack_v2_sparse_classes_30k_train_008819 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: list[str] :type word1: str :type word2: str :rtype: int
- def shortestDistanceEqual(self, words, word1, word2): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestDistance(self, words, word1, word2): :type words: list[str] :type word1: str :type word2: str :rtype: int
- def shortestDistanceEqual(self, words, word1, word2): :typ... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: list[str] :type word1: str :type word2: str :rtype: int"""
<|body_0|>
def shortestDistanceEqual(self, words, word1, word2):
""":type words: list[str] :type word1: str :type word2: str :rtype: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestDistance(self, words, word1, word2):
""":type words: list[str] :type word1: str :type word2: str :rtype: int"""
distance = len(words)
idx1 = idx2 = -1
for i, w in enumerate(words):
if w == word1:
idx1 = i
if w == wor... | the_stack_v2_python_sparse | S/ShortestWordDistance.py | bssrdf/pyleet | train | 2 | |
a18ca877887a19a4bed1a48e2c24593a5a7d51c6 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | MessageExchangeServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageExchangeServicer:
"""Missing associated documentation comment in .proto file."""
def GetModel(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendModel(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_36k_train_027550 | 6,770 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetModel",
"signature": "def GetModel(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SendModel",
"signature": "def SendModel(self, request,... | 4 | null | Implement the Python class `MessageExchangeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetModel(self, request, context): Missing associated documentation comment in .proto file.
- def SendModel(self, request, context): ... | Implement the Python class `MessageExchangeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetModel(self, request, context): Missing associated documentation comment in .proto file.
- def SendModel(self, request, context): ... | f784cfd4cc2f34879abb287ef32c586243ee5b0c | <|skeleton|>
class MessageExchangeServicer:
"""Missing associated documentation comment in .proto file."""
def GetModel(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendModel(self, request, context):
"""Missing associated do... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageExchangeServicer:
"""Missing associated documentation comment in .proto file."""
def GetModel(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!... | the_stack_v2_python_sparse | tensorflow_impl/libs/garfield_pb2_grpc.py | yanlili1995/Garfield | train | 0 |
9d1c2795f0a9bf3d8a64e65dbf49753e00a56502 | [
"object_type = self.kwargs.get('object_type', 'posts')\nif object_type == 'comments':\n return CommentSerializer\nreturn PostListSerializer",
"object_type = self.kwargs.get('object_type', 'posts')\nusername = self.kwargs.get('username', None)\nUser = get_user_model()\nif not User.objects.filter(username=userna... | <|body_start_0|>
object_type = self.kwargs.get('object_type', 'posts')
if object_type == 'comments':
return CommentSerializer
return PostListSerializer
<|end_body_0|>
<|body_start_1|>
object_type = self.kwargs.get('object_type', 'posts')
username = self.kwargs.get('u... | Return list of user related objects (blogposts, comments). | UserObjects | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
<|body_0|>
def get_queryset(self):
"""Determine queryset for different object type."""
<|bo... | stack_v2_sparse_classes_36k_train_027551 | 19,438 | no_license | [
{
"docstring": "Determine serializer for different object type.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Determine queryset for different object type.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007659 | Implement the Python class `UserObjects` described below.
Class description:
Return list of user related objects (blogposts, comments).
Method signatures and docstrings:
- def get_serializer_class(self): Determine serializer for different object type.
- def get_queryset(self): Determine queryset for different object ... | Implement the Python class `UserObjects` described below.
Class description:
Return list of user related objects (blogposts, comments).
Method signatures and docstrings:
- def get_serializer_class(self): Determine serializer for different object type.
- def get_queryset(self): Determine queryset for different object ... | 3e77877d1805ae2b361c9b3f564e73f698a3f4c6 | <|skeleton|>
class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
<|body_0|>
def get_queryset(self):
"""Determine queryset for different object type."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserObjects:
"""Return list of user related objects (blogposts, comments)."""
def get_serializer_class(self):
"""Determine serializer for different object type."""
object_type = self.kwargs.get('object_type', 'posts')
if object_type == 'comments':
return CommentSeriali... | the_stack_v2_python_sparse | api/views.py | zagorboda/django-blog | train | 0 |
28c0c57fef07c94ff880fe00eabff1d62060c27c | [
"metadata = api.cinder.volume_type_extra_get(request, volume_type_id)\nresult = {x.key: x.value for x in metadata}\nreturn result",
"updated = request.DATA['updated']\nremoved = request.DATA['removed']\nif updated:\n api.cinder.volume_type_extra_set(request, volume_type_id, updated)\nif removed:\n api.cinde... | <|body_start_0|>
metadata = api.cinder.volume_type_extra_get(request, volume_type_id)
result = {x.key: x.value for x in metadata}
return result
<|end_body_0|>
<|body_start_1|>
updated = request.DATA['updated']
removed = request.DATA['removed']
if updated:
api... | API for getting snapshots metadata | VolumeTypeMetadata | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeTypeMetadata:
"""API for getting snapshots metadata"""
def get(self, request, volume_type_id):
"""Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata"""
<|body_0|>
def patch(self, request, volume_type_id):
"""Update metadata ... | stack_v2_sparse_classes_36k_train_027552 | 14,440 | permissive | [
{
"docstring": "Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata",
"name": "get",
"signature": "def get(self, request, volume_type_id)"
},
{
"docstring": "Update metadata for specific volume http://localhost/api/cinder/volumetypes/1/metadata",
"name": "patc... | 2 | stack_v2_sparse_classes_30k_train_020759 | Implement the Python class `VolumeTypeMetadata` described below.
Class description:
API for getting snapshots metadata
Method signatures and docstrings:
- def get(self, request, volume_type_id): Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata
- def patch(self, request, volume_type_... | Implement the Python class `VolumeTypeMetadata` described below.
Class description:
API for getting snapshots metadata
Method signatures and docstrings:
- def get(self, request, volume_type_id): Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata
- def patch(self, request, volume_type_... | 7896fd8c77a6766a1156a520946efaf792b76ca5 | <|skeleton|>
class VolumeTypeMetadata:
"""API for getting snapshots metadata"""
def get(self, request, volume_type_id):
"""Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata"""
<|body_0|>
def patch(self, request, volume_type_id):
"""Update metadata ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeTypeMetadata:
"""API for getting snapshots metadata"""
def get(self, request, volume_type_id):
"""Get a specific volume's metadata http://localhost/api/cinder/volumetypes/1/metadata"""
metadata = api.cinder.volume_type_extra_get(request, volume_type_id)
result = {x.key: x.va... | the_stack_v2_python_sparse | openstack_dashboard/api/rest/cinder.py | openstack/horizon | train | 1,060 |
ba771789fee5f3c7d7b96e969701b7d7ba62430f | [
"if excel_path == None:\n current_path = os.path.abspath(os.path.dirname(__file__))\n self.excel_path = current_path + '/../data/casedata.xlsx'\nelse:\n self.excel_path = excel_path\nif sheet_name == None:\n self.sheet_name = 'Sheet'\nelse:\n self.sheet_name = sheet_name\nself.data = load_workbook(se... | <|body_start_0|>
if excel_path == None:
current_path = os.path.abspath(os.path.dirname(__file__))
self.excel_path = current_path + '/../data/casedata.xlsx'
else:
self.excel_path = excel_path
if sheet_name == None:
self.sheet_name = 'Sheet'
... | ExcelUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelUtil:
def __init__(self, excel_path=None, sheet_name=None):
"""获取excel工作表"""
<|body_0|>
def get_data(self) -> object:
"""获取文件数据 每一行数据一个list,所有的数据一个大list :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if excel_path == None:
... | stack_v2_sparse_classes_36k_train_027553 | 1,323 | no_license | [
{
"docstring": "获取excel工作表",
"name": "__init__",
"signature": "def __init__(self, excel_path=None, sheet_name=None)"
},
{
"docstring": "获取文件数据 每一行数据一个list,所有的数据一个大list :return:",
"name": "get_data",
"signature": "def get_data(self) -> object"
}
] | 2 | stack_v2_sparse_classes_30k_train_013352 | Implement the Python class `ExcelUtil` described below.
Class description:
Implement the ExcelUtil class.
Method signatures and docstrings:
- def __init__(self, excel_path=None, sheet_name=None): 获取excel工作表
- def get_data(self) -> object: 获取文件数据 每一行数据一个list,所有的数据一个大list :return: | Implement the Python class `ExcelUtil` described below.
Class description:
Implement the ExcelUtil class.
Method signatures and docstrings:
- def __init__(self, excel_path=None, sheet_name=None): 获取excel工作表
- def get_data(self) -> object: 获取文件数据 每一行数据一个list,所有的数据一个大list :return:
<|skeleton|>
class ExcelUtil:
de... | 5f843531d413202f4f4e48ed0c3d510db21f4396 | <|skeleton|>
class ExcelUtil:
def __init__(self, excel_path=None, sheet_name=None):
"""获取excel工作表"""
<|body_0|>
def get_data(self) -> object:
"""获取文件数据 每一行数据一个list,所有的数据一个大list :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcelUtil:
def __init__(self, excel_path=None, sheet_name=None):
"""获取excel工作表"""
if excel_path == None:
current_path = os.path.abspath(os.path.dirname(__file__))
self.excel_path = current_path + '/../data/casedata.xlsx'
else:
self.excel_path = excel... | the_stack_v2_python_sparse | pycharm/digiin/common/ExcelUtil.py | yz9527-1/1YZ | train | 0 | |
613d0f42bb819c998dc4d6a5c3d8988133930c0e | [
"contato = get_a_contact(id)\nif not contato:\n api.abort(404)\nelse:\n return contato",
"contato = get_a_contact(id)\nif not contato:\n api.abort(404)\nelse:\n data = request.json\n return update_contact(contato, data=data)"
] | <|body_start_0|>
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
return contato
<|end_body_0|>
<|body_start_1|>
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
data = request.json
... | Contato | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
contato = get_a_co... | stack_v2_sparse_classes_36k_train_027554 | 2,424 | no_license | [
{
"docstring": "Obtem informações de um contato com base no seu id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Atualiza um contato Obs: para inativar, coloque 'ativo': false",
"name": "patch",
"signature": "def patch(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000947 | Implement the Python class `Contato` described below.
Class description:
Implement the Contato class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um contato com base no seu id
- def patch(self, id): Atualiza um contato Obs: para inativar, coloque 'ativo': false | Implement the Python class `Contato` described below.
Class description:
Implement the Contato class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um contato com base no seu id
- def patch(self, id): Atualiza um contato Obs: para inativar, coloque 'ativo': false
<|skeleton|>
class Cont... | a86fcb085af8567a661d47876f8b9f13d7b062a9 | <|skeleton|>
class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
return contato
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ati... | the_stack_v2_python_sparse | backend/app/main/controller/contato_controller.py | AnderSilva/ozomali | train | 1 | |
03c2b0d130c1097a6cf3101d75e5e811b36a600f | [
"super(LSALoss_deepSVDD, self).__init__()\nself.lam_rec = lam_rec\nself.lam_svdd = lam_svdd\nself.c = c\nself.R = R\nself.nu = nu\nself.objective = objective\nself.reconstruction_loss_fn = ReconstructionLoss()\nself.deepSVDD_loss_fn = DeepSVDDLoss(c, R, nu, objective)\nself.reconstruction_loss = None\nself.deepSVDD... | <|body_start_0|>
super(LSALoss_deepSVDD, self).__init__()
self.lam_rec = lam_rec
self.lam_svdd = lam_svdd
self.c = c
self.R = R
self.nu = nu
self.objective = objective
self.reconstruction_loss_fn = ReconstructionLoss()
self.deepSVDD_loss_fn = DeepS... | Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss. | LSALoss_deepSVDD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSALoss_deepSVDD:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary'):
"""Class constructor. :param cpd_channels: number of bins in which the... | stack_v2_sparse_classes_36k_train_027555 | 2,243 | permissive | [
{
"docstring": "Class constructor. :param cpd_channels: number of bins in which the multinomial works. :param lam: weight of the autoregression loss.",
"name": "__init__",
"signature": "def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary')"
},
{
"docstring": "Forwa... | 2 | stack_v2_sparse_classes_30k_train_015865 | Implement the Python class `LSALoss_deepSVDD` described below.
Class description:
Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss.
Method signatures and docstrings:
- def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary'): Class cons... | Implement the Python class `LSALoss_deepSVDD` described below.
Class description:
Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss.
Method signatures and docstrings:
- def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary'): Class cons... | b9843f34ecb59f908d78ddf977ee4670e0ed6cb4 | <|skeleton|>
class LSALoss_deepSVDD:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary'):
"""Class constructor. :param cpd_channels: number of bins in which the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSALoss_deepSVDD:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam_rec=1, lam_svdd=0, c=0, R=0, nu=0, objective='soft-boundary'):
"""Class constructor. :param cpd_channels: number of bins in which the multinomial ... | the_stack_v2_python_sparse | models/loss_functions/lsaloss_deepSVDD.py | hikaruzzz/AutoregressModel-AE_VAD_CVPR2019 | train | 0 |
1e355e32f09d4aaeb7f755e55e7c95da330b3f70 | [
"node = eqnNode.spotByNumber(0).spotChain()[0].nodeRef\ntry:\n return node.formatRef.fieldDict[self.fieldName].mathValue(node, zeroBlanks, noMarkup)\nexcept KeyError:\n return zeroValue if zeroBlanks else None",
"if 1 not in {len(spot.spotChain()) for spot in refNode.spotRefs}:\n return []\nrefs = [node ... | <|body_start_0|>
node = eqnNode.spotByNumber(0).spotChain()[0].nodeRef
try:
return node.formatRef.fieldDict[self.fieldName].mathValue(node, zeroBlanks, noMarkup)
except KeyError:
return zeroValue if zeroBlanks else None
<|end_body_0|>
<|body_start_1|>
if 1 not in... | Class to store and eval root node field references in a Math equation. | EquationRootRef | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquationRootRef:
"""Class to store and eval root node field references in a Math equation."""
def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0, noMarkup=True):
"""Return the root field value referenced from a given node. Return None if blank or doesn't exist and not zer... | stack_v2_sparse_classes_36k_train_027556 | 21,625 | no_license | [
{
"docstring": "Return the root field value referenced from a given node. Return None if blank or doesn't exist and not zeroBlanks, raise a ValueError if it isn't a number. Arguments: eqnNode -- the node containing the equation to evaluate zeroBlanks -- replace blank fields with zeroValue if True zeroValue -- t... | 2 | null | Implement the Python class `EquationRootRef` described below.
Class description:
Class to store and eval root node field references in a Math equation.
Method signatures and docstrings:
- def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0, noMarkup=True): Return the root field value referenced from a give... | Implement the Python class `EquationRootRef` described below.
Class description:
Class to store and eval root node field references in a Math equation.
Method signatures and docstrings:
- def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0, noMarkup=True): Return the root field value referenced from a give... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class EquationRootRef:
"""Class to store and eval root node field references in a Math equation."""
def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0, noMarkup=True):
"""Return the root field value referenced from a given node. Return None if blank or doesn't exist and not zer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquationRootRef:
"""Class to store and eval root node field references in a Math equation."""
def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0, noMarkup=True):
"""Return the root field value referenced from a given node. Return None if blank or doesn't exist and not zeroBlanks, rais... | the_stack_v2_python_sparse | source/matheval.py | doug-101/TreeLine | train | 121 |
875df98278fb71f41bb6aa9f3df078987e940478 | [
"if is_json is None or is_json:\n try:\n return (json.loads(data.decode()), True)\n except ValueError as e:\n if is_json:\n raise IPCError('Unable to decode json data') from e\ntry:\n assert len(data) >= HDRLEN\n size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]\n assert size... | <|body_start_0|>
if is_json is None or is_json:
try:
return (json.loads(data.decode()), True)
except ValueError as e:
if is_json:
raise IPCError('Unable to decode json data') from e
try:
assert len(data) >= HDRLEN
... | A helper class to handle properly packing and unpacking messages | _IPC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _IPC:
"""A helper class to handle properly packing and unpacking messages"""
def unpack(data: bytes, *, is_json: bool | None=None) -> tuple[Any, bool]:
"""Unpack the incoming message Parameters ---------- data: bytes The incoming message to unpack is_json: bool | None If the message ... | stack_v2_sparse_classes_36k_train_027557 | 9,252 | permissive | [
{
"docstring": "Unpack the incoming message Parameters ---------- data: bytes The incoming message to unpack is_json: bool | None If the message should be unpacked as json. By default, try to unpack json and fallback gracefully to marshalled bytes. Returns ------- tuple[Any, bool] A tuple of the unpacked object... | 3 | stack_v2_sparse_classes_30k_train_013339 | Implement the Python class `_IPC` described below.
Class description:
A helper class to handle properly packing and unpacking messages
Method signatures and docstrings:
- def unpack(data: bytes, *, is_json: bool | None=None) -> tuple[Any, bool]: Unpack the incoming message Parameters ---------- data: bytes The incomi... | Implement the Python class `_IPC` described below.
Class description:
A helper class to handle properly packing and unpacking messages
Method signatures and docstrings:
- def unpack(data: bytes, *, is_json: bool | None=None) -> tuple[Any, bool]: Unpack the incoming message Parameters ---------- data: bytes The incomi... | 3f8a00082ad880042d396477d9445954e8d29cf2 | <|skeleton|>
class _IPC:
"""A helper class to handle properly packing and unpacking messages"""
def unpack(data: bytes, *, is_json: bool | None=None) -> tuple[Any, bool]:
"""Unpack the incoming message Parameters ---------- data: bytes The incoming message to unpack is_json: bool | None If the message ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _IPC:
"""A helper class to handle properly packing and unpacking messages"""
def unpack(data: bytes, *, is_json: bool | None=None) -> tuple[Any, bool]:
"""Unpack the incoming message Parameters ---------- data: bytes The incoming message to unpack is_json: bool | None If the message should be unp... | the_stack_v2_python_sparse | libqtile/ipc.py | qtile/qtile | train | 4,203 |
a82b954550123140dc0dab113db482e303d3ecf6 | [
"self.initAlpha = initAlpha\nself.factor = factor\nself.dropEvery = dropEvery\npass",
"exp = np.floor((1 + epoch) / self.dropEvery)\nalpha = initAlpha * self.factor ** exp\nreturn float(alpha)"
] | <|body_start_0|>
self.initAlpha = initAlpha
self.factor = factor
self.dropEvery = dropEvery
pass
<|end_body_0|>
<|body_start_1|>
exp = np.floor((1 + epoch) / self.dropEvery)
alpha = initAlpha * self.factor ** exp
return float(alpha)
<|end_body_1|>
| StepDecay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepDecay:
def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10):
"""- initiate StepDecay class with initial lr, decay factor & decay period"""
<|body_0|>
def __call__(self, epoch):
"""- compute the learning rate for the current epoch using step-based decay f... | stack_v2_sparse_classes_36k_train_027558 | 2,358 | no_license | [
{
"docstring": "- initiate StepDecay class with initial lr, decay factor & decay period",
"name": "__init__",
"signature": "def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10)"
},
{
"docstring": "- compute the learning rate for the current epoch using step-based decay function - accept... | 2 | stack_v2_sparse_classes_30k_train_018124 | Implement the Python class `StepDecay` described below.
Class description:
Implement the StepDecay class.
Method signatures and docstrings:
- def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10): - initiate StepDecay class with initial lr, decay factor & decay period
- def __call__(self, epoch): - compute th... | Implement the Python class `StepDecay` described below.
Class description:
Implement the StepDecay class.
Method signatures and docstrings:
- def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10): - initiate StepDecay class with initial lr, decay factor & decay period
- def __call__(self, epoch): - compute th... | ebf5edb4d71f81dd9d8478c6251e97c097d189c3 | <|skeleton|>
class StepDecay:
def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10):
"""- initiate StepDecay class with initial lr, decay factor & decay period"""
<|body_0|>
def __call__(self, epoch):
"""- compute the learning rate for the current epoch using step-based decay f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StepDecay:
def __init__(self, initAlpha=0.01, factor=0.25, dropEvery=10):
"""- initiate StepDecay class with initial lr, decay factor & decay period"""
self.initAlpha = initAlpha
self.factor = factor
self.dropEvery = dropEvery
pass
def __call__(self, epoch):
... | the_stack_v2_python_sparse | callbacks/learning_rate_scheduler.py | zlyin/Orca | train | 0 | |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\nkeyID = read_length_and_key(fp)\nreturn cls(name, classID, keyID)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_length_and_key(fp, self.keyID)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
keyID = read_length_and_key(fp)
return cls(name, classID, keyID)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.class... | Property structure. .. py:attribute:: name | Property | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
"""Property structure. .. py:attribute:: name"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_36k_train_027559 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015231 | Implement the Python class `Property` described below.
Class description:
Property structure. .. py:attribute:: name
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: f... | Implement the Python class `Property` described below.
Class description:
Property structure. .. py:attribute:: name
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: f... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Property:
"""Property structure. .. py:attribute:: name"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Property:
"""Property structure. .. py:attribute:: name"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
keyID = read_length_and_key(fp)
return cls(nam... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
b68e305e86d1ada8e7f0a3a0c2aa3d634b2f24fb | [
"folder = os.path.dirname(input_path)\noutput_path = folder + '/nifti/'\nif not os.path.exists(output_path):\n os.mkdir(output_path)\noutput_path += os.path.basename(os.path.dirname(input_path)) + '.nii'\nopen(output_path, 'a').close()\ndicom_array = DICOMImporter.open_dicom_from_folder(input_path)\ndicom_array_... | <|body_start_0|>
folder = os.path.dirname(input_path)
output_path = folder + '/nifti/'
if not os.path.exists(output_path):
os.mkdir(output_path)
output_path += os.path.basename(os.path.dirname(input_path)) + '.nii'
open(output_path, 'a').close()
dicom_array = ... | DICOM_2_NIFTI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /... | stack_v2_sparse_classes_36k_train_027560 | 4,993 | no_license | [
{
"docstring": "Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /patient/date/dicom_raw/*.dcm will result in nifti file located a... | 2 | stack_v2_sparse_classes_30k_train_010431 | Implement the Python class `DICOM_2_NIFTI` described below.
Class description:
Implement the DICOM_2_NIFTI class.
Method signatures and docstrings:
- def convert_dicom_series(input_path): Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: inpu... | Implement the Python class `DICOM_2_NIFTI` described below.
Class description:
Implement the DICOM_2_NIFTI class.
Method signatures and docstrings:
- def convert_dicom_series(input_path): Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: inpu... | d665ca405bdf35fdb57f8149a10b90be82d8de22 | <|skeleton|>
class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DICOM_2_NIFTI:
def convert_dicom_series(input_path):
"""Converts a raw DICOM file series into a Nifti file. Saves a Nifti file to the file system based on path of DICOM file. Input: input_path: - a directory path to a valid series of DICOM images (more than 1) - sample directory layout /patient/date/d... | the_stack_v2_python_sparse | BSSCSFramework/CTConverter/DICOM_operations.py | wezleysherman/TBI-NN-421 | train | 3 | |
0964e5ba68df60f637198f8d671696605f4a2570 | [
"try:\n return User.objects.get(id=uid)\nexcept User.DoesNotExist:\n return None",
"try:\n return User.objects.get(username=username, password=pwd)\nexcept User.DoesNotExist as exp:\n logger.error(exp)\n return None",
"try:\n return User.objects.get(username=username)\nexcept User.DoesNotExist... | <|body_start_0|>
try:
return User.objects.get(id=uid)
except User.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
try:
return User.objects.get(username=username, password=pwd)
except User.DoesNotExist as exp:
logger.error(exp)
... | UserBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserBase:
def get_user(self, uid):
"""Find User by uid"""
<|body_0|>
def get_user_by_np(self, username, pwd):
"""Find User by username and password"""
<|body_1|>
def get_user_by_name(self, username):
"""Find User by username"""
<|body_2|>... | stack_v2_sparse_classes_36k_train_027561 | 3,847 | permissive | [
{
"docstring": "Find User by uid",
"name": "get_user",
"signature": "def get_user(self, uid)"
},
{
"docstring": "Find User by username and password",
"name": "get_user_by_np",
"signature": "def get_user_by_np(self, username, pwd)"
},
{
"docstring": "Find User by username",
"n... | 3 | stack_v2_sparse_classes_30k_train_001986 | Implement the Python class `UserBase` described below.
Class description:
Implement the UserBase class.
Method signatures and docstrings:
- def get_user(self, uid): Find User by uid
- def get_user_by_np(self, username, pwd): Find User by username and password
- def get_user_by_name(self, username): Find User by usern... | Implement the Python class `UserBase` described below.
Class description:
Implement the UserBase class.
Method signatures and docstrings:
- def get_user(self, uid): Find User by uid
- def get_user_by_np(self, username, pwd): Find User by username and password
- def get_user_by_name(self, username): Find User by usern... | 3c2454ebad7764906c5ff30cbdfe296cb7c64eb4 | <|skeleton|>
class UserBase:
def get_user(self, uid):
"""Find User by uid"""
<|body_0|>
def get_user_by_np(self, username, pwd):
"""Find User by username and password"""
<|body_1|>
def get_user_by_name(self, username):
"""Find User by username"""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserBase:
def get_user(self, uid):
"""Find User by uid"""
try:
return User.objects.get(id=uid)
except User.DoesNotExist:
return None
def get_user_by_np(self, username, pwd):
"""Find User by username and password"""
try:
return Us... | the_stack_v2_python_sparse | travel/views/userview.py | sausage-team/travel-notes | train | 0 | |
1bd1c02b237a89ac9c5c9cb3be0e2cf1d2602d2d | [
"self.data_dicts = data_dicts\nself.max_rep = max_rep\nself.csv_file_name = csv_fname\nself.dot_file_name = dot_fname\nself.png_file_name = png_fname\nlogger.info('Initialized the EmailRelations instance.')",
"data_dict_obj = DataDict(self.data_dicts, self.max_rep)\ndata_dict_obj.write_dup_data(self.csv_file_name... | <|body_start_0|>
self.data_dicts = data_dicts
self.max_rep = max_rep
self.csv_file_name = csv_fname
self.dot_file_name = dot_fname
self.png_file_name = png_fname
logger.info('Initialized the EmailRelations instance.')
<|end_body_0|>
<|body_start_1|>
data_dict_obj... | Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. of times an email is to duplicated. csv_fname : name of csv file where data is sto... | EmailRelations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailRelations:
"""Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. of times an email is to duplicated. csv_... | stack_v2_sparse_classes_36k_train_027562 | 1,902 | permissive | [
{
"docstring": "Initializes the list of emails, max. repition for each email, csv filename where the duplicated data is stored, the dot file where intermediate graph is stored and final png file.",
"name": "__init__",
"signature": "def __init__(self, data_dicts, max_rep, csv_fname, dot_fname, png_fname)... | 2 | stack_v2_sparse_classes_30k_train_008824 | Implement the Python class `EmailRelations` described below.
Class description:
Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. o... | Implement the Python class `EmailRelations` described below.
Class description:
Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. o... | 056e4c89e4f8d7fc4a4095ee0671d6944a86630e | <|skeleton|>
class EmailRelations:
"""Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. of times an email is to duplicated. csv_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailRelations:
"""Creates a png file describing relations based on emails list. Methods ------- create_relations_image : Creates a png file describing relations based on emails list. Parameters ---------- data_dicts : list of email dicts max_rep : max no. of times an email is to duplicated. csv_fname : name ... | the_stack_v2_python_sparse | Section_10/10_4 Logging your Project/my_package/get_relations.py | PacktPublishing/Software-Engineering-with-Python-3.x | train | 2 |
e87a8683d4300f34018575e8d42abaf0fb780b5c | [
"self.path = path\nself.external_data_dir = external_data_dir\nself.ignore_external_data = util.default(ignore_external_data, False)",
"G_LOGGER.info(f'Loading model: {self.path}')\nauto_load_ext_data = self.external_data_dir is None and (not self.ignore_external_data)\ntry:\n model = onnx.load(self.path, load... | <|body_start_0|>
self.path = path
self.external_data_dir = external_data_dir
self.ignore_external_data = util.default(ignore_external_data, False)
<|end_body_0|>
<|body_start_1|>
G_LOGGER.info(f'Loading model: {self.path}')
auto_load_ext_data = self.external_data_dir is None and... | Functor that loads an ONNX model from a file. | OnnxFromPath | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where ext... | stack_v2_sparse_classes_36k_train_027563 | 37,448 | permissive | [
{
"docstring": "Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where external data for the model is stored. ignore_external_data (bool): Whether to ignore any external data and just load the model structure without any weights. Th... | 2 | stack_v2_sparse_classes_30k_train_003770 | Implement the Python class `OnnxFromPath` described below.
Class description:
Functor that loads an ONNX model from a file.
Method signatures and docstrings:
- def __init__(self, path, external_data_dir=None, ignore_external_data=None): Loads an ONNX model from a file. Args: path (str): The path from which to load th... | Implement the Python class `OnnxFromPath` described below.
Class description:
Functor that loads an ONNX model from a file.
Method signatures and docstrings:
- def __init__(self, path, external_data_dir=None, ignore_external_data=None): Loads an ONNX model from a file. Args: path (str): The path from which to load th... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where ext... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnnxFromPath:
"""Functor that loads an ONNX model from a file."""
def __init__(self, path, external_data_dir=None, ignore_external_data=None):
"""Loads an ONNX model from a file. Args: path (str): The path from which to load the model. external_data_dir (str): The directory where external data fo... | the_stack_v2_python_sparse | tools/Polygraphy/polygraphy/backend/onnx/loader.py | NVIDIA/TensorRT | train | 8,026 |
fbf73fe4de2533d49992a3312390a173168fd486 | [
"self.disable_network = disable_network\nself.preserve_mac_address = preserve_mac_address\nself.source_network_id = source_network_id\nself.target_network_id = target_network_id",
"if dictionary is None:\n return None\ndisable_network = dictionary.get('disableNetwork')\npreserve_mac_address = dictionary.get('p... | <|body_start_0|>
self.disable_network = disable_network
self.preserve_mac_address = preserve_mac_address
self.source_network_id = source_network_id
self.target_network_id = target_network_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
d... | Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, if the network should be kept in disabled s... | NetworkMapping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, i... | stack_v2_sparse_classes_36k_train_027564 | 2,789 | permissive | [
{
"docstring": "Constructor for the NetworkMapping class",
"name": "__init__",
"signature": "def __init__(self, disable_network=None, preserve_mac_address=None, source_network_id=None, target_network_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | stack_v2_sparse_classes_30k_train_012617 | Implement the Python class `NetworkMapping` described below.
Class description:
Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be dis... | Implement the Python class `NetworkMapping` described below.
Class description:
Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be dis... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkMapping:
"""Implementation of the 'NetworkMapping' model. Specifies the information needed when mapping the source networks to target networks during restore and clone actions. Attributes: disable_network (bool): Specifies if the network should be disabled. On restore or clone of the VM, if the network... | the_stack_v2_python_sparse | cohesity_management_sdk/models/network_mapping.py | cohesity/management-sdk-python | train | 24 |
90482e06115bdef708c6f8059322cc3b17a63c66 | [
"try:\n metric = Metric.objects.get(name=name, project=project, sample=sample, rna=rna)\nexcept Metric.DoesNotExist:\n metric = self.create_and_symlink(name, project, sample, rna)\nreturn metric",
"res = []\nsample_names = [sample.name for sample in project.samples]\nmetric_info = dna_parse.get_metrics(proj... | <|body_start_0|>
try:
metric = Metric.objects.get(name=name, project=project, sample=sample, rna=rna)
except Metric.DoesNotExist:
metric = self.create_and_symlink(name, project, sample, rna)
return metric
<|end_body_0|>
<|body_start_1|>
res = []
sample_na... | Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it. | MetricManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricManager:
"""Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it."""
... | stack_v2_sparse_classes_36k_train_027565 | 27,913 | no_license | [
{
"docstring": "Overrides the standard get_or_create by calling create_or_symlink instead of vanilla create.",
"name": "get_or_create",
"signature": "def get_or_create(self, name, project, sample=None, rna=False)"
},
{
"docstring": "Uses the get_metrics function in the dna_parse toolkit script i... | 4 | stack_v2_sparse_classes_30k_train_016528 | Implement the Python class `MetricManager` described below.
Class description:
Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you h... | Implement the Python class `MetricManager` described below.
Class description:
Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you h... | c863c79c0cbc784834534a8ce894f9ff6b5ed4c1 | <|skeleton|>
class MetricManager:
"""Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricManager:
"""Metrics are trickier than BAMs or VCFs because Metrics have an associated symlink that lives in the static/metrics directory. Whenever a metric is created, you have to make sure to create the symlink, and whenever a metric is deleted, you have to make sure to delete it."""
def get_or_cr... | the_stack_v2_python_sparse | pbg/apps/analysis/models.py | mdschramm/dashboardngs | train | 0 |
55f19d3610a1f2d3da4f54aed0dd72169a6be3fa | [
"self.maxi = maxi\nself.p = self.__start_progress(maxi)()\nself.header_printed = False\nself.msg = msg\nself.size = size",
"if reset:\n self.__init__(self.maxi, self.size, self.msg)\nif not self.header_printed:\n self.__print_header()\nnext(self.p)",
"format_string = '\\n0%{: ^' + str(self.size - 6) + '}1... | <|body_start_0|>
self.maxi = maxi
self.p = self.__start_progress(maxi)()
self.header_printed = False
self.msg = msg
self.size = size
<|end_body_0|>
<|body_start_1|>
if reset:
self.__init__(self.maxi, self.size, self.msg)
if not self.header_printed:
... | Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart. | Progress | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Progress:
"""Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart."""
def __init__(self, maxi, size=100, msg=''):
"""Initialize class. Args: maxi: The number of steps required ... | stack_v2_sparse_classes_36k_train_027566 | 13,013 | permissive | [
{
"docstring": "Initialize class. Args: maxi: The number of steps required to reach 100%. size: The number of characters taken on the screen by the progress bar. msg: The message displayed in the header of the progress bar.",
"name": "__init__",
"signature": "def __init__(self, maxi, size=100, msg='')"
... | 4 | null | Implement the Python class `Progress` described below.
Class description:
Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart.
Method signatures and docstrings:
- def __init__(self, maxi, size=100, msg=''): In... | Implement the Python class `Progress` described below.
Class description:
Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart.
Method signatures and docstrings:
- def __init__(self, maxi, size=100, msg=''): In... | ba5086c9852a1ad2425126fa7a95c02213ddbab4 | <|skeleton|>
class Progress:
"""Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart."""
def __init__(self, maxi, size=100, msg=''):
"""Initialize class. Args: maxi: The number of steps required ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Progress:
"""Text mode progress bar. Usage: p = Progress(30) p.step() p.step() p.step(start=True) # to restart form 0% The progress bar displays a new header at each restart."""
def __init__(self, maxi, size=100, msg=''):
"""Initialize class. Args: maxi: The number of steps required to reach 100%... | the_stack_v2_python_sparse | src/python/bot/fuzzers/ml/rnn/utils.py | Google-Autofuzz/clusterfuzz | train | 4 |
69622fc7fdcfc0c3c24c456eeb4830606a242a19 | [
"assert spec_calc in ['scipy', 'librosa', 'padding'], \"Please use 'scipy' or 'librosa' to calculate spectrograms.\"\nself._spec_calc = spec_calc\nself.df = df\nself.batch_size = batch_size\nself.pad_value = pad_value\nself.targets = np.array(self.df['Target'].tolist()).astype(np.float32)\nself.path_list = self.df[... | <|body_start_0|>
assert spec_calc in ['scipy', 'librosa', 'padding'], "Please use 'scipy' or 'librosa' to calculate spectrograms."
self._spec_calc = spec_calc
self.df = df
self.batch_size = batch_size
self.pad_value = pad_value
self.targets = np.array(self.df['Target'].to... | Generates data for Keras | DataGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGenerator:
"""Generates data for Keras"""
def __init__(self, df, batch_size=32, pad_value=-9999, return_seq=True, spec_calc='scipy'):
"""df = manifest dataframe batch_size = desired batching size pad_value = desired value to pad data with, pads to max of each batch return_seq = d... | stack_v2_sparse_classes_36k_train_027567 | 35,860 | permissive | [
{
"docstring": "df = manifest dataframe batch_size = desired batching size pad_value = desired value to pad data with, pads to max of each batch return_seq = determines generated label structure, related to model architecture spec_calc = Pass 'scipy' or 'librosa' to calc specs from wav files. Pass 'padding' if ... | 4 | stack_v2_sparse_classes_30k_train_016666 | Implement the Python class `DataGenerator` described below.
Class description:
Generates data for Keras
Method signatures and docstrings:
- def __init__(self, df, batch_size=32, pad_value=-9999, return_seq=True, spec_calc='scipy'): df = manifest dataframe batch_size = desired batching size pad_value = desired value t... | Implement the Python class `DataGenerator` described below.
Class description:
Generates data for Keras
Method signatures and docstrings:
- def __init__(self, df, batch_size=32, pad_value=-9999, return_seq=True, spec_calc='scipy'): df = manifest dataframe batch_size = desired batching size pad_value = desired value t... | 43fcc570b78a80b245d745aebc19f341c7e283fc | <|skeleton|>
class DataGenerator:
"""Generates data for Keras"""
def __init__(self, df, batch_size=32, pad_value=-9999, return_seq=True, spec_calc='scipy'):
"""df = manifest dataframe batch_size = desired batching size pad_value = desired value to pad data with, pads to max of each batch return_seq = d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataGenerator:
"""Generates data for Keras"""
def __init__(self, df, batch_size=32, pad_value=-9999, return_seq=True, spec_calc='scipy'):
"""df = manifest dataframe batch_size = desired batching size pad_value = desired value to pad data with, pads to max of each batch return_seq = determines gen... | the_stack_v2_python_sparse | earshot/data.py | maglab-uconn/EARShot_TF2 | train | 2 |
8a8847b00bf0ad4a96fbb9c153776356939fcf58 | [
"length = len(nums)\nleft, right = (0, length - 1)\nwhile left <= right:\n if nums[left] == val:\n nums[left] = nums[right]\n right -= 1\n else:\n left += 1\nreturn left",
"slow = 0\nfor fast in range(len(nums)):\n if nums[fast] != val:\n nums[slow] = nums[fast]\n slow ... | <|body_start_0|>
length = len(nums)
left, right = (0, length - 1)
while left <= right:
if nums[left] == val:
nums[left] = nums[right]
right -= 1
else:
left += 1
return left
<|end_body_0|>
<|body_start_1|>
sl... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement1(self, nums: List[int], val: int) -> int:
"""First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we keeping doing the followings. If the left num equals the target $val, copy the right num to the l... | stack_v2_sparse_classes_36k_train_027568 | 2,401 | no_license | [
{
"docstring": "First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we keeping doing the followings. If the left num equals the target $val, copy the right num to the left num and decrease $right by one. Otherwise, increase $left by one. In the end,... | 2 | stack_v2_sparse_classes_30k_train_016153 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement1(self, nums: List[int], val: int) -> int: First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement1(self, nums: List[int], val: int) -> int: First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we ... | 9bdbe3232faedc5b23caeb0c47baeb0bda9d313d | <|skeleton|>
class Solution:
def removeElement1(self, nums: List[int], val: int) -> int:
"""First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we keeping doing the followings. If the left num equals the target $val, copy the right num to the l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement1(self, nums: List[int], val: int) -> int:
"""First of all, use two points $left, $right which points to the beginnning and the end. As long as $left <= $right, we keeping doing the followings. If the left num equals the target $val, copy the right num to the left num and de... | the_stack_v2_python_sparse | TwoPointers/27_RemoveElement.py | ideaqiwang/leetcode | train | 0 | |
b65fe7f50991dc67784a9bf98033a794ce36e605 | [
"if not email:\n raise ValueError('Users must have an email address')\nif not password:\n raise ValueError('Password is required')\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email=email, password=passw... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
if not password:
raise ValueError('Password is required')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
... | DiscoUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscoUserManager:
def create_user(self, email, password):
"""Creates and saves a User with the given email, username and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a User with the given email, username and password."""
... | stack_v2_sparse_classes_36k_train_027569 | 7,100 | no_license | [
{
"docstring": "Creates and saves a User with the given email, username and password.",
"name": "create_user",
"signature": "def create_user(self, email, password)"
},
{
"docstring": "Creates and saves a User with the given email, username and password.",
"name": "create_superuser",
"sig... | 2 | stack_v2_sparse_classes_30k_train_007749 | Implement the Python class `DiscoUserManager` described below.
Class description:
Implement the DiscoUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password): Creates and saves a User with the given email, username and password.
- def create_superuser(self, email, password): Creat... | Implement the Python class `DiscoUserManager` described below.
Class description:
Implement the DiscoUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password): Creates and saves a User with the given email, username and password.
- def create_superuser(self, email, password): Creat... | 8fcda9b412dae0b2c45d9418c9d97b8564c6f829 | <|skeleton|>
class DiscoUserManager:
def create_user(self, email, password):
"""Creates and saves a User with the given email, username and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a User with the given email, username and password."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscoUserManager:
def create_user(self, email, password):
"""Creates and saves a User with the given email, username and password."""
if not email:
raise ValueError('Users must have an email address')
if not password:
raise ValueError('Password is required')
... | the_stack_v2_python_sparse | discoauth/models.py | abhisolve/discog-portal_backend | train | 0 | |
61b8186209dbcb0c14734399d2c312c571c12a9e | [
"try:\n client.containers.get(name_or_id).remove(force=force)\nexcept docker.errors.NotFound as not_found:\n if not ignore_container_not_found:\n raise not_found",
"try:\n client.images.remove(name_or_id, force=force)\nexcept docker.errors.ImageNotFound as not_found:\n if not ignore_image_not_f... | <|body_start_0|>
try:
client.containers.get(name_or_id).remove(force=force)
except docker.errors.NotFound as not_found:
if not ignore_container_not_found:
raise not_found
<|end_body_0|>
<|body_start_1|>
try:
client.images.remove(name_or_id, fo... | docker extra tools that will be usefully also as stand alone commands | DockerTools | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerTools:
"""docker extra tools that will be usefully also as stand alone commands"""
def remove_container(name_or_id: str, ignore_container_not_found: bool=True, force: bool=False):
"""Examples docker rm MyTestContainer can be replaced with DockerTools.remove_container("MyTestCon... | stack_v2_sparse_classes_36k_train_027570 | 6,497 | permissive | [
{
"docstring": "Examples docker rm MyTestContainer can be replaced with DockerTools.remove_container(\"MyTestContainer\") in your code Args: name_or_id: the name or id of the container ignore_container_not_found: don't raise an exception in case the container already removed force: same as the -f option in the ... | 2 | stack_v2_sparse_classes_30k_train_019203 | Implement the Python class `DockerTools` described below.
Class description:
docker extra tools that will be usefully also as stand alone commands
Method signatures and docstrings:
- def remove_container(name_or_id: str, ignore_container_not_found: bool=True, force: bool=False): Examples docker rm MyTestContainer can... | Implement the Python class `DockerTools` described below.
Class description:
docker extra tools that will be usefully also as stand alone commands
Method signatures and docstrings:
- def remove_container(name_or_id: str, ignore_container_not_found: bool=True, force: bool=False): Examples docker rm MyTestContainer can... | 59d99cf4b5016be8a4a333c2541418e1612549e1 | <|skeleton|>
class DockerTools:
"""docker extra tools that will be usefully also as stand alone commands"""
def remove_container(name_or_id: str, ignore_container_not_found: bool=True, force: bool=False):
"""Examples docker rm MyTestContainer can be replaced with DockerTools.remove_container("MyTestCon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DockerTools:
"""docker extra tools that will be usefully also as stand alone commands"""
def remove_container(name_or_id: str, ignore_container_not_found: bool=True, force: bool=False):
"""Examples docker rm MyTestContainer can be replaced with DockerTools.remove_container("MyTestContainer") in y... | the_stack_v2_python_sparse | demisto_sdk/commands/common/docker_util.py | kfirstri/demisto-sdk | train | 1 |
96647a534284a3a0c57ba511cb75f8bb8cd45ddb | [
"session = db_apis.get_session()\nwith session.begin():\n db_amp = self.amphora_repo.get(session, id=amphora[constants.ID])\nfor port in ports:\n net = data_models.Network(**port.pop(constants.NETWORK))\n ips = port.pop(constants.FIXED_IPS)\n fixed_ips = []\n for ip in ips:\n subnet_arg = ip.p... | <|body_start_0|>
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=amphora[constants.ID])
for port in ports:
net = data_models.Network(**port.pop(constants.NETWORK))
ips = port.pop(constants.FIXED_IPS)
... | Task to notify the amphora post network plug. | AmphoraPostNetworkPlug | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmphoraPostNetworkPlug:
"""Task to notify the amphora post network plug."""
def execute(self, amphora, ports, amphora_network_config):
"""Execute post_network_plug routine."""
<|body_0|>
def revert(self, result, amphora, *args, **kwargs):
"""Handle a failed post ... | stack_v2_sparse_classes_36k_train_027571 | 28,773 | permissive | [
{
"docstring": "Execute post_network_plug routine.",
"name": "execute",
"signature": "def execute(self, amphora, ports, amphora_network_config)"
},
{
"docstring": "Handle a failed post network plug.",
"name": "revert",
"signature": "def revert(self, result, amphora, *args, **kwargs)"
}... | 2 | null | Implement the Python class `AmphoraPostNetworkPlug` described below.
Class description:
Task to notify the amphora post network plug.
Method signatures and docstrings:
- def execute(self, amphora, ports, amphora_network_config): Execute post_network_plug routine.
- def revert(self, result, amphora, *args, **kwargs): ... | Implement the Python class `AmphoraPostNetworkPlug` described below.
Class description:
Task to notify the amphora post network plug.
Method signatures and docstrings:
- def execute(self, amphora, ports, amphora_network_config): Execute post_network_plug routine.
- def revert(self, result, amphora, *args, **kwargs): ... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class AmphoraPostNetworkPlug:
"""Task to notify the amphora post network plug."""
def execute(self, amphora, ports, amphora_network_config):
"""Execute post_network_plug routine."""
<|body_0|>
def revert(self, result, amphora, *args, **kwargs):
"""Handle a failed post ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmphoraPostNetworkPlug:
"""Task to notify the amphora post network plug."""
def execute(self, amphora, ports, amphora_network_config):
"""Execute post_network_plug routine."""
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session,... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/amphora_driver_tasks.py | openstack/octavia | train | 147 |
13c909805eb299391b38016448c9726f2e684bd5 | [
"Algorithm.__init__(self)\nself.name = 'Threshold'\nself.parent = 'Segmentation'\nself.threshold = IntegerSlider('threshold value', 1, 50, 1, 1)\nself.maxvalue = IntegerSlider('maxvalue', 1, 255, 1, 1)\nself.integer_sliders.append(self.threshold)\nself.integer_sliders.append(self.maxvalue)",
"image = args[0]\nret... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Threshold'
self.parent = 'Segmentation'
self.threshold = IntegerSlider('threshold value', 1, 50, 1, 1)
self.maxvalue = IntegerSlider('maxvalue', 1, 255, 1, 1)
self.integer_sliders.append(self.threshold)
self.i... | Threshold algorithm implementation | AlgBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Threshold algorithm implementation"""
def __init__(self):
"""Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of threshold. Any value that is greater than the threshold value ... | stack_v2_sparse_classes_36k_train_027572 | 1,648 | no_license | [
{
"docstring": "Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of threshold. Any value that is greater than the threshold value is set to 255 and any value less than is set to 0 (by using cv2.TRESH_BINARY) | *maxv... | 2 | null | Implement the Python class `AlgBody` described below.
Class description:
Threshold algorithm implementation
Method signatures and docstrings:
- def __init__(self): Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of thres... | Implement the Python class `AlgBody` described below.
Class description:
Threshold algorithm implementation
Method signatures and docstrings:
- def __init__(self): Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of thres... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Threshold algorithm implementation"""
def __init__(self):
"""Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of threshold. Any value that is greater than the threshold value ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Threshold algorithm implementation"""
def __init__(self):
"""Threshold object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *threshold* : value of threshold. Any value that is greater than the threshold value is set to 255... | the_stack_v2_python_sparse | Andreas_Algorithms_Prototype/threshold.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
eac34677b256ce5527eb4b12698be65fa4ca9717 | [
"super(SparseGraphAttentionLayer, self).__init__()\nself.output_dim = output_dim\nself.W = nn.Parameter(torch.Tensor(input_dim, output_dim))\nself.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))\nif bias:\n self.bias = nn.Parameter(torch.FloatTensor(output_dim))\nelse:\n self.register_parameter('bias', None... | <|body_start_0|>
super(SparseGraphAttentionLayer, self).__init__()
self.output_dim = output_dim
self.W = nn.Parameter(torch.Tensor(input_dim, output_dim))
self.a = nn.Parameter(torch.Tensor(2 * output_dim, 1))
if bias:
self.bias = nn.Parameter(torch.FloatTensor(output... | Graph Attention层 (sparse input) | SparseGraphAttentionLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseGraphAttentionLayer:
"""Graph Attention层 (sparse input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 ... | stack_v2_sparse_classes_36k_train_027573 | 6,215 | permissive | [
{
"docstring": "Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean, 是否使用偏置",
"name": "__init__",
"signature": "def __init__(self, input_dim, output_dim, dropout, alpha, bias=True)"
},
{
"... | 5 | stack_v2_sparse_classes_30k_train_007851 | Implement the Python class `SparseGraphAttentionLayer` described below.
Class description:
Graph Attention层 (sparse input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度... | Implement the Python class `SparseGraphAttentionLayer` described below.
Class description:
Graph Attention层 (sparse input)
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, dropout, alpha, bias=True): Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class SparseGraphAttentionLayer:
"""Graph Attention层 (sparse input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseGraphAttentionLayer:
"""Graph Attention层 (sparse input)"""
def __init__(self, input_dim, output_dim, dropout, alpha, bias=True):
"""Graph Attention层 (sparse input) Inputs: ------- input_dim: int, 输入维度 outut_dim: int, 输出维度 dropout: float, dropout比例 alpha: float, LeakyReLU负数部分斜率 bias: boolean... | the_stack_v2_python_sparse | Node/GAT/script/layers.py | robbinc91/GNN-Pytorch | train | 0 |
e672577da09a1355cc0d899d4b1077a670613154 | [
"def is_exe(f):\n return os.path.isfile(f) and os.access(f, os.X_OK)\nfpath, fname = os.path.split(cmd)\nif fpath:\n if is_exe(cmd):\n self._gulp_cmd = cmd\n return\nelse:\n for path in os.environ['PATH'].split(os.pathsep):\n path = path.strip('\"')\n file = os.path.join(path, c... | <|body_start_0|>
def is_exe(f):
return os.path.isfile(f) and os.access(f, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
self._gulp_cmd = cmd
return
else:
for path in os.environ['PATH'].split(os.pat... | Class to run gulp from commandline | GulpCaller | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GulpCaller:
"""Class to run gulp from commandline"""
def __init__(self, cmd='gulp'):
"""Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp."""
<|body_0|>
def run(self, gin):
"""Run GULP using the gin as input Args: gin... | stack_v2_sparse_classes_36k_train_027574 | 26,921 | permissive | [
{
"docstring": "Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp.",
"name": "__init__",
"signature": "def __init__(self, cmd='gulp')"
},
{
"docstring": "Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string",... | 2 | stack_v2_sparse_classes_30k_train_006637 | Implement the Python class `GulpCaller` described below.
Class description:
Class to run gulp from commandline
Method signatures and docstrings:
- def __init__(self, cmd='gulp'): Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp.
- def run(self, gin): Run GULP using the g... | Implement the Python class `GulpCaller` described below.
Class description:
Class to run gulp from commandline
Method signatures and docstrings:
- def __init__(self, cmd='gulp'): Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp.
- def run(self, gin): Run GULP using the g... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class GulpCaller:
"""Class to run gulp from commandline"""
def __init__(self, cmd='gulp'):
"""Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp."""
<|body_0|>
def run(self, gin):
"""Run GULP using the gin as input Args: gin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GulpCaller:
"""Class to run gulp from commandline"""
def __init__(self, cmd='gulp'):
"""Initialize with the executable if not in the standard path Args: cmd: Command. Defaults to gulp."""
def is_exe(f):
return os.path.isfile(f) and os.access(f, os.X_OK)
fpath, fname = ... | the_stack_v2_python_sparse | pymatgen/command_line/gulp_caller.py | montoyjh/pymatgen | train | 2 |
bd5772588bb32e8fcc56d7a4c5e91d0960203e1c | [
"data = vertex_praser.parse_args()\npage = data.get('page')\npage_len = data.get('len')\nif None in [page, page_len]:\n return abort(400, 'Invalid parameters.')\nreturn vertex_dao.all(collection, page, page_len)",
"req_dict = api.payload\nname = req_dict.get('name')\nif not name:\n return abort(400, 'Invali... | <|body_start_0|>
data = vertex_praser.parse_args()
page = data.get('page')
page_len = data.get('len')
if None in [page, page_len]:
return abort(400, 'Invalid parameters.')
return vertex_dao.all(collection, page, page_len)
<|end_body_0|>
<|body_start_1|>
req_d... | VertexList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VertexList:
def get(self, graph_id, collection):
"""Fetch a given vetex collection"""
<|body_0|>
def post(self, graph_id, collection):
"""Create a new vertex"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = vertex_praser.parse_args()
p... | stack_v2_sparse_classes_36k_train_027575 | 2,797 | permissive | [
{
"docstring": "Fetch a given vetex collection",
"name": "get",
"signature": "def get(self, graph_id, collection)"
},
{
"docstring": "Create a new vertex",
"name": "post",
"signature": "def post(self, graph_id, collection)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001699 | Implement the Python class `VertexList` described below.
Class description:
Implement the VertexList class.
Method signatures and docstrings:
- def get(self, graph_id, collection): Fetch a given vetex collection
- def post(self, graph_id, collection): Create a new vertex | Implement the Python class `VertexList` described below.
Class description:
Implement the VertexList class.
Method signatures and docstrings:
- def get(self, graph_id, collection): Fetch a given vetex collection
- def post(self, graph_id, collection): Create a new vertex
<|skeleton|>
class VertexList:
def get(s... | 953c2916c38906b0941c015136f80b2e64dd94f3 | <|skeleton|>
class VertexList:
def get(self, graph_id, collection):
"""Fetch a given vetex collection"""
<|body_0|>
def post(self, graph_id, collection):
"""Create a new vertex"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VertexList:
def get(self, graph_id, collection):
"""Fetch a given vetex collection"""
data = vertex_praser.parse_args()
page = data.get('page')
page_len = data.get('len')
if None in [page, page_len]:
return abort(400, 'Invalid parameters.')
return ve... | the_stack_v2_python_sparse | kgeditor/api_1_0/graph_vertex.py | LaiXinyi823/KGEditor | train | 0 | |
3ecae1d38f71ea8151ab3d05b937391931f0081c | [
"self.fname = fname\nself.testing = testing\nself.fname_short = fname[fname.rfind('/') + 1:]\nwith open(fname, 'r') as f:\n data = f.readlines()\nself.knapsack_size = int(data[0].split()[0])\nself.num_items = int(data[0].split()[1])\nself.values = [0]\nself.weights = [0]\nself.max_weight = 0\nfor item in data[1:... | <|body_start_0|>
self.fname = fname
self.testing = testing
self.fname_short = fname[fname.rfind('/') + 1:]
with open(fname, 'r') as f:
data = f.readlines()
self.knapsack_size = int(data[0].split()[0])
self.num_items = int(data[0].split()[1])
self.value... | Class defining a knapsack | Knapsack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
<|body_0|>
def naive_solution(self):
"""Find and return the optimal total value of items that can fit in the knapsac... | stack_v2_sparse_classes_36k_train_027576 | 6,784 | no_license | [
{
"docstring": "Read in the input from fname and the solution if testing",
"name": "__init__",
"signature": "def __init__(self, fname, testing=False)"
},
{
"docstring": "Find and return the optimal total value of items that can fit in the knapsack. Use the naive method filling out the 2d array",... | 4 | stack_v2_sparse_classes_30k_train_003963 | Implement the Python class `Knapsack` described below.
Class description:
Class defining a knapsack
Method signatures and docstrings:
- def __init__(self, fname, testing=False): Read in the input from fname and the solution if testing
- def naive_solution(self): Find and return the optimal total value of items that c... | Implement the Python class `Knapsack` described below.
Class description:
Class defining a knapsack
Method signatures and docstrings:
- def __init__(self, fname, testing=False): Read in the input from fname and the solution if testing
- def naive_solution(self): Find and return the optimal total value of items that c... | 2a9b795d3bbcccd5b1fce83d3ed431ec54d084a7 | <|skeleton|>
class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
<|body_0|>
def naive_solution(self):
"""Find and return the optimal total value of items that can fit in the knapsac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
self.fname = fname
self.testing = testing
self.fname_short = fname[fname.rfind('/') + 1:]
with open(fname, 'r') as f:
... | the_stack_v2_python_sparse | course3/assignment4_q1.py | denck007/Algorithms_specialization | train | 1 |
0c1916949dbadfc08280503f30eb2fde711d562e | [
"passed = ['', None]\nfailed = ['', None]\noutput = sju.StdJson(passed=passed, failed=failed)\nself.assertFalse(output.tests)",
"tests = ['a']\noutput = sju.StdJson(passed=tests)\nself.assertEqual(output.tests['a']['actual'], 'PASS')\noutput = sju.StdJson(failed=tests)\nself.assertEqual(output.tests['a']['actual'... | <|body_start_0|>
passed = ['', None]
failed = ['', None]
output = sju.StdJson(passed=passed, failed=failed)
self.assertFalse(output.tests)
<|end_body_0|>
<|body_start_1|>
tests = ['a']
output = sju.StdJson(passed=tests)
self.assertEqual(output.tests['a']['actual'... | UnitTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitTest:
def test_base_cases(self):
"""Test invalid test names are skipped"""
<|body_0|>
def test_single_constructor(self):
"""Test one test passing, failing, flaking via constructor"""
<|body_1|>
def test_multi_run(self):
"""Test multiple execu... | stack_v2_sparse_classes_36k_train_027577 | 3,425 | permissive | [
{
"docstring": "Test invalid test names are skipped",
"name": "test_base_cases",
"signature": "def test_base_cases(self)"
},
{
"docstring": "Test one test passing, failing, flaking via constructor",
"name": "test_single_constructor",
"signature": "def test_single_constructor(self)"
},
... | 6 | null | Implement the Python class `UnitTest` described below.
Class description:
Implement the UnitTest class.
Method signatures and docstrings:
- def test_base_cases(self): Test invalid test names are skipped
- def test_single_constructor(self): Test one test passing, failing, flaking via constructor
- def test_multi_run(s... | Implement the Python class `UnitTest` described below.
Class description:
Implement the UnitTest class.
Method signatures and docstrings:
- def test_base_cases(self): Test invalid test names are skipped
- def test_single_constructor(self): Test one test passing, failing, flaking via constructor
- def test_multi_run(s... | 64bee65c921db7e78e25d08f1e98da2668b57be5 | <|skeleton|>
class UnitTest:
def test_base_cases(self):
"""Test invalid test names are skipped"""
<|body_0|>
def test_single_constructor(self):
"""Test one test passing, failing, flaking via constructor"""
<|body_1|>
def test_multi_run(self):
"""Test multiple execu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitTest:
def test_base_cases(self):
"""Test invalid test names are skipped"""
passed = ['', None]
failed = ['', None]
output = sju.StdJson(passed=passed, failed=failed)
self.assertFalse(output.tests)
def test_single_constructor(self):
"""Test one test pass... | the_stack_v2_python_sparse | ios/build/bots/scripts/standard_json_util_tests.py | otcshare/chromium-src | train | 18 | |
edca32cf06c8460b5918b66aa7495fc3562b2d1f | [
"result = []\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j]:\n result.extend([i, j])\n return result",
"r = []\nnum_copy = copy.deepcopy(nums)\nnums.sort()\nj = len(nums) - 1\ni = 0\nwhile i < j:\n if nums[i] + nums[j] > target:\n j... | <|body_start_0|>
result = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j]:
result.extend([i, j])
return result
<|end_body_0|>
<|body_start_1|>
r = []
num_copy = copy.deepcopy(nums)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSumTest(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_027578 | 1,651 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSumTest",
"signature": "def twoSumTest(self, nums, target... | 2 | stack_v2_sparse_classes_30k_train_012304 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSumTest(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSumTest(self, nums, target): :type nums: List[int] :type target: int :rtype: Li... | 90d07a53a537212f41740adb8e65c4e30c3c4f64 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSumTest(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
result = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j]:
result.extend([i, j])
... | the_stack_v2_python_sparse | 数组与字符串/sumTest.py | xianytt/LeetCode | train | 0 | |
5dbf7c5a54cb2b02ab8f6f28b54e8796046dde68 | [
"super().__init__(name='sequence_model')\nself.model_size = model_size\nself.action_space = action_space\nnum_gru_units = get_gru_units(self.model_size, override=num_gru_units)\nself.pre_gru_layer = MLP(num_dense_layers=1, model_size=self.model_size, output_layer_size=None)\nself.gru_unit = tf.keras.layers.GRU(num_... | <|body_start_0|>
super().__init__(name='sequence_model')
self.model_size = model_size
self.action_space = action_space
num_gru_units = get_gru_units(self.model_size, override=num_gru_units)
self.pre_gru_layer = MLP(num_dense_layers=1, model_size=self.model_size, output_layer_size... | The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic, discrete). There are two versions of z-states: "posterior" for world model tra... | SequenceModel | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceModel:
"""The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic, discrete). There are two versions of ... | stack_v2_sparse_classes_36k_train_027579 | 5,090 | permissive | [
{
"docstring": "Initializes a SequenceModel instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Use None for manually setting the number of GRU units used. action_space: The action space the our environment used. num_gru_units: Overrides the number of GRU units (dimension of the h-... | 2 | null | Implement the Python class `SequenceModel` described below.
Class description:
The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic... | Implement the Python class `SequenceModel` described below.
Class description:
The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class SequenceModel:
"""The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic, discrete). There are two versions of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceModel:
"""The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). Note: The "internal state" always consists of: The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, continuous), and `z`-states (stochastic, discrete). There are two versions of z-states: "po... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/sequence_model.py | ray-project/ray | train | 29,482 |
310dafe8ec0bf3ae520f4c09ae82e31acb7d8ac4 | [
"self.Whf = np.random.normal(size=(i + h, h))\nself.bhf = np.zeros((1, h))\nself.Whb = np.random.normal(size=(i + h, h))\nself.bhb = np.zeros((1, h))\nself.Wy = np.random.normal(size=(i + h + o, o))\nself.by = np.zeros((1, o))",
"X = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.matmul(X, self.Whf) +... | <|body_start_0|>
self.Whf = np.random.normal(size=(i + h, h))
self.bhf = np.zeros((1, h))
self.Whb = np.random.normal(size=(i + h, h))
self.bhb = np.zeros((1, h))
self.Wy = np.random.normal(size=(i + h + o, o))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
... | BidirectionalCell class. | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
"""BidirectionalCell class."""
def __init__(self, i, h, o):
"""Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs."""
<|body_0|>
def forward(self, h_prev, x_t):
... | stack_v2_sparse_classes_36k_train_027580 | 1,714 | no_license | [
{
"docstring": "Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs.",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "calculates the hidden state in the forward direction for one... | 3 | stack_v2_sparse_classes_30k_train_010623 | Implement the Python class `BidirectionalCell` described below.
Class description:
BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs.
- def for... | Implement the Python class `BidirectionalCell` described below.
Class description:
BidirectionalCell class.
Method signatures and docstrings:
- def __init__(self, i, h, o): Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs.
- def for... | 75274394adb52d740f6cd4000cc00bbde44b9b72 | <|skeleton|>
class BidirectionalCell:
"""BidirectionalCell class."""
def __init__(self, i, h, o):
"""Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs."""
<|body_0|>
def forward(self, h_prev, x_t):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalCell:
"""BidirectionalCell class."""
def __init__(self, i, h, o):
"""Initializer. Args: i: the dimensionality of the data. h: the dimensionality of the hidden states. o: the dimensionality of the outputs."""
self.Whf = np.random.normal(size=(i + h, h))
self.bhf = np.z... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/6-bi_backward.py | jdarangop/holbertonschool-machine_learning | train | 2 |
55d72c67ad38d7dae4f05c6d1cb7e56ae730e236 | [
"t0 = Triangle()\nself.assertIsNot(t0, None)\nself.assertIsInstance(t0, Triangle)",
"t1 = Triangle([1, 2, 3])\nself.assertIsNot(t1, None)\nself.assertIsInstance(t1, Triangle)\nt2 = Triangle('xyz')\nself.assertIsNot(t2, None)\nself.assertIsInstance(t2, Triangle)\nt3 = Triangle(['x', 'y', 'z'])\nself.assertIsNot(t3... | <|body_start_0|>
t0 = Triangle()
self.assertIsNot(t0, None)
self.assertIsInstance(t0, Triangle)
<|end_body_0|>
<|body_start_1|>
t1 = Triangle([1, 2, 3])
self.assertIsNot(t1, None)
self.assertIsInstance(t1, Triangle)
t2 = Triangle('xyz')
self.assertIsNot(t... | Test Triangle class call | TestConstructor_Triangle | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConstructor_Triangle:
"""Test Triangle class call"""
def test_none(self):
"""Calling Triangle class with no key (key = None)"""
<|body_0|>
def test_iterable(self):
"""Calling Vertex class with iterable key"""
<|body_1|>
def test_iterable_specific... | stack_v2_sparse_classes_36k_train_027581 | 6,423 | permissive | [
{
"docstring": "Calling Triangle class with no key (key = None)",
"name": "test_none",
"signature": "def test_none(self)"
},
{
"docstring": "Calling Vertex class with iterable key",
"name": "test_iterable",
"signature": "def test_iterable(self)"
},
{
"docstring": "Calling Vertex ... | 3 | stack_v2_sparse_classes_30k_train_013527 | Implement the Python class `TestConstructor_Triangle` described below.
Class description:
Test Triangle class call
Method signatures and docstrings:
- def test_none(self): Calling Triangle class with no key (key = None)
- def test_iterable(self): Calling Vertex class with iterable key
- def test_iterable_specific(sel... | Implement the Python class `TestConstructor_Triangle` described below.
Class description:
Test Triangle class call
Method signatures and docstrings:
- def test_none(self): Calling Triangle class with no key (key = None)
- def test_iterable(self): Calling Vertex class with iterable key
- def test_iterable_specific(sel... | f9b00a39bc16aea4abac60c0dd0aab2acac5adcf | <|skeleton|>
class TestConstructor_Triangle:
"""Test Triangle class call"""
def test_none(self):
"""Calling Triangle class with no key (key = None)"""
<|body_0|>
def test_iterable(self):
"""Calling Vertex class with iterable key"""
<|body_1|>
def test_iterable_specific... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestConstructor_Triangle:
"""Test Triangle class call"""
def test_none(self):
"""Calling Triangle class with no key (key = None)"""
t0 = Triangle()
self.assertIsNot(t0, None)
self.assertIsInstance(t0, Triangle)
def test_iterable(self):
"""Calling Vertex class ... | the_stack_v2_python_sparse | _BACKUPS_v3/v3_1/LightPicture_Test.py | nagame/LightPicture | train | 0 |
04068c2d9595b5d1c89d03ba9180d31767ccb468 | [
"if type(self) in (CQRSSerializer, CQRSPolymorphicSerializer):\n return {}\nfields = super(CQRSSerializer, self).get_default_fields()\nfor base in type(self).__bases__:\n base = CQRSSerializerMeta._register.instances[base.Meta.model]\n if type(base) in (CQRSSerializer, CQRSPolymorphicSerializer):\n ... | <|body_start_0|>
if type(self) in (CQRSSerializer, CQRSPolymorphicSerializer):
return {}
fields = super(CQRSSerializer, self).get_default_fields()
for base in type(self).__bases__:
base = CQRSSerializerMeta._register.instances[base.Meta.model]
if type(base) in... | CQRSSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CQRSSerializer:
def get_default_fields(self):
"""Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.get_default_fields` in that it only returns the *newly added fields*: that is, the fields from this cla... | stack_v2_sparse_classes_36k_train_027582 | 13,334 | no_license | [
{
"docstring": "Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.get_default_fields` in that it only returns the *newly added fields*: that is, the fields from this class but not from one of its CQRS bases (thus, fields from ... | 2 | stack_v2_sparse_classes_30k_train_004668 | Implement the Python class `CQRSSerializer` described below.
Class description:
Implement the CQRSSerializer class.
Method signatures and docstrings:
- def get_default_fields(self): Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.... | Implement the Python class `CQRSSerializer` described below.
Class description:
Implement the CQRSSerializer class.
Method signatures and docstrings:
- def get_default_fields(self): Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.... | 72dfb45220000bed3b506885c0196bc2e4540836 | <|skeleton|>
class CQRSSerializer:
def get_default_fields(self):
"""Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.get_default_fields` in that it only returns the *newly added fields*: that is, the fields from this cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CQRSSerializer:
def get_default_fields(self):
"""Return the PARTIAL set of default fields for the object, as a dict. This differs from :meth:`rest_framework.serializers.ModelSerializer.get_default_fields` in that it only returns the *newly added fields*: that is, the fields from this class but not fro... | the_stack_v2_python_sparse | cqrs/serializers.py | xyicheng/cqrs | train | 0 | |
b20e2f095ea4c83726ce383fef8d9c46a5455798 | [
"rc = []\nfor test in tests:\n try:\n testmethod = getattr(SCR_Test_Runtime, test)\n if callable(testmethod):\n rc.append(testmethod())\n else:\n print('SCR_Test_Runtime: ERROR: ' + test + ' is defined but is not a test method.')\n except AttributeError as e:\n ... | <|body_start_0|>
rc = []
for test in tests:
try:
testmethod = getattr(SCR_Test_Runtime, test)
if callable(testmethod):
rc.append(testmethod())
else:
print('SCR_Test_Runtime: ERROR: ' + test + ' is defined... | SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all methods are appropriate to test in every envi... | SCR_Test_Runtime | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCR_Test_Runtime:
"""SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all m... | stack_v2_sparse_classes_36k_train_027583 | 5,626 | permissive | [
{
"docstring": "This method collects the return codes of all static methods declared in SCR_Test_Runtime This method receives a list. Each element is a string and is the name of a method of the SCR_Test_Runtime class Returns ------- This method returns an integer. This method does not return an instance of a cl... | 3 | stack_v2_sparse_classes_30k_train_010487 | Implement the Python class `SCR_Test_Runtime` described below.
Class description:
SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately afte... | Implement the Python class `SCR_Test_Runtime` described below.
Class description:
SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately afte... | 1d78ff0bccd02a9443ad07844c4ca75129a537a1 | <|skeleton|>
class SCR_Test_Runtime:
"""SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SCR_Test_Runtime:
"""SCR_Test_Runtime class contains methods to determine whether we should launch with SCR This class contains methods to test the environment, to ensure SCR will be able to function. These tests are called in scr_prerun.py, immediately after checking if scr is enabled. Not all methods are ap... | the_stack_v2_python_sparse | scripts/python/scrjob/scr_test_runtime.py | LLNL/scr | train | 84 |
46a0c6c2f7401bff3b03f56e4376f577768a7e6e | [
"n = len(prices)\nif n < 2:\n return 0\nif k >= n / 2:\n return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))\nglobalMax = [[0] * n for _ in range(k + 1)]\nfor i in range(1, k + 1):\n localMax = [0] * n\n for j in range(1, n):\n profit = prices[j] - prices[j - 1]\n loc... | <|body_start_0|>
n = len(prices)
if n < 2:
return 0
if k >= n / 2:
return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))
globalMax = [[0] * n for _ in range(k + 1)]
for i in range(1, k + 1):
localMax = [0] * n
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len... | stack_v2_sparse_classes_36k_train_027584 | 3,578 | no_license | [
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, k, prices)"
},
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit_1",
"signature": "def maxProfit_1(self, k, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit_1(self, k, prices): :type k: int :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, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit_1(self, k, prices): :type k: int :type prices: List[int] :rtype: int
<|skeleton|... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_1(self, k, prices):
""":type k: int :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, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
n = len(prices)
if n < 2:
return 0
if k >= n / 2:
return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))
globalMax = [[0] * n for ... | the_stack_v2_python_sparse | Solutions/0188_maxProfit.py | YoupengLi/leetcode-sorting | train | 3 | |
f4eff9f11e62acb0ea476a495883534fb81a4bef | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = Information(userLogin).getPresentCar(send_data['parkName'], send_data['carNum'])\nresult = re\nAssertions().assert_in_text(result, expect... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = Information(userLogin).getPresentCar(send_data['parkName'], send_da... | pc端收费放行 | TestCheckOutNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCheckOutNormal:
"""pc端收费放行"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_36k_train_027585 | 2,342 | no_license | [
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, sentryLogin, send_data, expect)"
},
{
"docstring": "查看在场记录",
"name": "test_presentCar",
"signature": "def test_presentCar(self, userLogin, send_data, expect)"
},
{
"docstring": "模拟离场",
"na... | 5 | null | Implement the Python class `TestCheckOutNormal` described below.
Class description:
pc端收费放行
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | Implement the Python class `TestCheckOutNormal` described below.
Class description:
pc端收费放行
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCheckOutNormal:
"""pc端收费放行"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCheckOutNormal:
"""pc端收费放行"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_checkOutNormal.py | oyebino/pomp_api | train | 1 |
71194713f0215f1dec2ce3a5cbd65b629f9f5c3e | [
"super(AngularPenaltySMLoss, self).__init__()\nloss_type = loss_type.lower()\nassert loss_type in ['arcface', 'sphereface', 'cosface']\nif loss_type == 'arcface':\n self.s = 64.0 if not s else s\n self.m = 0.5 if not m else m\nif loss_type == 'sphereface':\n self.s = 64.0 if not s else s\n self.m = 1.35... | <|body_start_0|>
super(AngularPenaltySMLoss, self).__init__()
loss_type = loss_type.lower()
assert loss_type in ['arcface', 'sphereface', 'cosface']
if loss_type == 'arcface':
self.s = 64.0 if not s else s
self.m = 0.5 if not m else m
if loss_type == 'sphe... | AngularPenaltySMLoss | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AngularPenaltySMLoss:
def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-07, s=None, m=None):
"""Angular Penalty Softmax Loss Three 'loss_types' available: ['arcface', 'sphereface', 'cosface'] These losses are described in the following papers: ArcFace: https://arx... | stack_v2_sparse_classes_36k_train_027586 | 4,547 | permissive | [
{
"docstring": "Angular Penalty Softmax Loss Three 'loss_types' available: ['arcface', 'sphereface', 'cosface'] These losses are described in the following papers: ArcFace: https://arxiv.org/abs/1801.07698 SphereFace: https://arxiv.org/abs/1704.08063 CosFace/Ad Margin: https://arxiv.org/abs/1801.05599",
"na... | 2 | stack_v2_sparse_classes_30k_train_009765 | Implement the Python class `AngularPenaltySMLoss` described below.
Class description:
Implement the AngularPenaltySMLoss class.
Method signatures and docstrings:
- def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-07, s=None, m=None): Angular Penalty Softmax Loss Three 'loss_types' available: ... | Implement the Python class `AngularPenaltySMLoss` described below.
Class description:
Implement the AngularPenaltySMLoss class.
Method signatures and docstrings:
- def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-07, s=None, m=None): Angular Penalty Softmax Loss Three 'loss_types' available: ... | c6f1648a148335babc0a26d8a589120616327548 | <|skeleton|>
class AngularPenaltySMLoss:
def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-07, s=None, m=None):
"""Angular Penalty Softmax Loss Three 'loss_types' available: ['arcface', 'sphereface', 'cosface'] These losses are described in the following papers: ArcFace: https://arx... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AngularPenaltySMLoss:
def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-07, s=None, m=None):
"""Angular Penalty Softmax Loss Three 'loss_types' available: ['arcface', 'sphereface', 'cosface'] These losses are described in the following papers: ArcFace: https://arxiv.org/abs/180... | the_stack_v2_python_sparse | loss_functions.py | arianasatryan/physionet-challenge-2020 | train | 0 | |
23b05c29e736b822f673b1dd5246ae11126df428 | [
"context = {}\nclient = get_object_or_404(Client, id=kwargs['client_id'])\ncontext['form'] = ClientForm(instance=client)\nreturn render(self.request, self.template_name, context)",
"client = get_object_or_404(Client, id=kwargs['client_id'])\nform = ClientForm(self.request.POST, instance=client, company=self.reque... | <|body_start_0|>
context = {}
client = get_object_or_404(Client, id=kwargs['client_id'])
context['form'] = ClientForm(instance=client)
return render(self.request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
client = get_object_or_404(Client, id=kwargs['client_id... | View edit form client | ClientEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Getting the filled client form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cont... | stack_v2_sparse_classes_36k_train_027587 | 4,241 | no_license | [
{
"docstring": "Display the client form",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Getting the filled client form",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001916 | Implement the Python class `ClientEditView` described below.
Class description:
View edit form client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, request, *args, **kwargs): Getting the filled client form | Implement the Python class `ClientEditView` described below.
Class description:
View edit form client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, request, *args, **kwargs): Getting the filled client form
<|skeleton|>
class ClientEditView:
"""View e... | 17615ea9bfb1edebe41d60dbf2e977f0018d5339 | <|skeleton|>
class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Getting the filled client form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
context = {}
client = get_object_or_404(Client, id=kwargs['client_id'])
context['form'] = ClientForm(instance=client)
return render(self.request, self.template... | the_stack_v2_python_sparse | clients/views.py | Swiftkind/invoice | train | 0 |
0453af7a7ae77b73a5e1f4ea82d3b501b5f3dea0 | [
"self.show = show\nself.season = season\nself.episode = episode\nlog.info('Searching: %s' % self.show)\nself.show_id, self.show = self._get_show_id()\nlog.debug('Retrieved show id: %s' % self.show_id)\nlog.debug('Retrieved canonical show name: %s' % self.show)\nself.title = self._get_episode_name()\nlog.debug('Retr... | <|body_start_0|>
self.show = show
self.season = season
self.episode = episode
log.info('Searching: %s' % self.show)
self.show_id, self.show = self._get_show_id()
log.debug('Retrieved show id: %s' % self.show_id)
log.debug('Retrieved canonical show name: %s' % self... | TheTvDb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheTvDb:
def __init__(self, show, season, episode):
""":param show_name: The show name of the episode title to be retrieved."""
<|body_0|>
def _get_show_id(self):
"""Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Ra... | stack_v2_sparse_classes_36k_train_027588 | 4,345 | permissive | [
{
"docstring": ":param show_name: The show name of the episode title to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, show, season, episode)"
},
{
"docstring": "Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Raised when a... | 3 | stack_v2_sparse_classes_30k_test_000479 | Implement the Python class `TheTvDb` described below.
Class description:
Implement the TheTvDb class.
Method signatures and docstrings:
- def __init__(self, show, season, episode): :param show_name: The show name of the episode title to be retrieved.
- def _get_show_id(self): Retrieves the show ID of the show name pa... | Implement the Python class `TheTvDb` described below.
Class description:
Implement the TheTvDb class.
Method signatures and docstrings:
- def __init__(self, show, season, episode): :param show_name: The show name of the episode title to be retrieved.
- def _get_show_id(self): Retrieves the show ID of the show name pa... | aa44757ae4e61b32acfe7260e56868d1477dc96e | <|skeleton|>
class TheTvDb:
def __init__(self, show, season, episode):
""":param show_name: The show name of the episode title to be retrieved."""
<|body_0|>
def _get_show_id(self):
"""Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TheTvDb:
def __init__(self, show, season, episode):
""":param show_name: The show name of the episode title to be retrieved."""
self.show = show
self.season = season
self.episode = episode
log.info('Searching: %s' % self.show)
self.show_id, self.show = self._get... | the_stack_v2_python_sparse | tvrenamr/lib/thetvdb.py | msabramo/tvrenamr | train | 0 | |
f6ab7e37b99f5670cc87e257ff3e252a6c2f71b8 | [
"QWidget.__init__(self)\nself.title = 'Kill Switch'\nself.linking_layout = QGridLayout(self)\nself.linking_layout.setAlignment(Qt.AlignCenter)\nself.setLayout(self.linking_layout)\nself.setWindowTitle(self.title)\nself.KILL_STATUS = 'killed'\nself.pushButton = QPushButton('Kill Sub', self)\nself.pushButton.setStyle... | <|body_start_0|>
QWidget.__init__(self)
self.title = 'Kill Switch'
self.linking_layout = QGridLayout(self)
self.linking_layout.setAlignment(Qt.AlignCenter)
self.setLayout(self.linking_layout)
self.setWindowTitle(self.title)
self.KILL_STATUS = 'killed'
self... | This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A | Kill_Button | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kill_Button:
"""This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A"""
def __init__(self):
"""Initialize the layout for the widget by setting its color and instantiating its components. Parameter: N/A Returns: N/A"""
<|body_0|>
def _sub_k... | stack_v2_sparse_classes_36k_train_027589 | 4,397 | permissive | [
{
"docstring": "Initialize the layout for the widget by setting its color and instantiating its components. Parameter: N/A Returns: N/A",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "A callback function for the sub killed subscriber to listen if the sub has been kille... | 3 | stack_v2_sparse_classes_30k_train_000890 | Implement the Python class `Kill_Button` described below.
Class description:
This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A
Method signatures and docstrings:
- def __init__(self): Initialize the layout for the widget by setting its color and instantiating its components. Paramete... | Implement the Python class `Kill_Button` described below.
Class description:
This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A
Method signatures and docstrings:
- def __init__(self): Initialize the layout for the widget by setting its color and instantiating its components. Paramete... | 26b476e1c8743f422c5affea744234e6322d4f59 | <|skeleton|>
class Kill_Button:
"""This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A"""
def __init__(self):
"""Initialize the layout for the widget by setting its color and instantiating its components. Parameter: N/A Returns: N/A"""
<|body_0|>
def _sub_k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kill_Button:
"""This class is PyQt widget for toggeling sub kill status. Parameter: N/A Returns: N/A"""
def __init__(self):
"""Initialize the layout for the widget by setting its color and instantiating its components. Parameter: N/A Returns: N/A"""
QWidget.__init__(self)
self.tit... | the_stack_v2_python_sparse | GUI/Src/kill_sub_widget.py | senseishafi/mechatronics-2019 | train | 0 |
aa959fe90a3bc4b2a533c0a62fce8a4d3619db6b | [
"self.component = component\nself.description = description\nself.id = id\nself.ip = ip\nself.netmask_bits = netmask_bits\nself.netmask_ip_4 = netmask_ip_4\nself.nfs_access = nfs_access\nself.nfs_all_squash = nfs_all_squash\nself.nfs_root_squash = nfs_root_squash\nself.s3_access = s3_access\nself.smb_access = smb_a... | <|body_start_0|>
self.component = component
self.description = description
self.id = id
self.ip = ip
self.netmask_bits = netmask_bits
self.netmask_ip_4 = netmask_ip_4
self.nfs_access = nfs_access
self.nfs_all_squash = nfs_all_squash
self.nfs_root_s... | Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the subnet. description (string): Descrip... | Subnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the sub... | stack_v2_sparse_classes_36k_train_027590 | 5,189 | permissive | [
{
"docstring": "Constructor for the Subnet class",
"name": "__init__",
"signature": "def __init__(self, component=None, description=None, id=None, ip=None, netmask_bits=None, netmask_ip_4=None, nfs_access=None, nfs_all_squash=None, nfs_root_squash=None, s3_access=None, smb_access=None, tenant_id=None)"
... | 2 | stack_v2_sparse_classes_30k_train_005946 | Implement the Python class `Subnet` described below.
Class description:
Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (strin... | Implement the Python class `Subnet` described below.
Class description:
Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (strin... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the subnet. descript... | the_stack_v2_python_sparse | cohesity_management_sdk/models/subnet.py | cohesity/management-sdk-python | train | 24 |
2f07b1256353e490ab443ea4379b56c85e61307b | [
"dict_nums = {0: 0, 1: 0, 2: 0}\nfor num in nums:\n dict_nums[num] += 1\na, b, c = (dict_nums[0], dict_nums[1], dict_nums[2])\nnums[:a] = [0] * a\nnums[a:a + b] = [1] * b\nnums[a + b:a + b + c] = [2] * c",
"left, right, i = (0, len(nums) - 1, 0)\nwhile i <= right:\n if nums[i] == 0:\n nums[left], num... | <|body_start_0|>
dict_nums = {0: 0, 1: 0, 2: 0}
for num in nums:
dict_nums[num] += 1
a, b, c = (dict_nums[0], dict_nums[1], dict_nums[2])
nums[:a] = [0] * a
nums[a:a + b] = [1] * b
nums[a + b:a + b + c] = [2] * c
<|end_body_0|>
<|body_start_1|>
left, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_027591 | 1,035 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors1",
"signature": "def sortColors1(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors1(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors1(self, nums: List[int]) -> None: Do not return anything, mod... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
dict_nums = {0: 0, 1: 0, 2: 0}
for num in nums:
dict_nums[num] += 1
a, b, c = (dict_nums[0], dict_nums[1], dict_nums[2])
nums[:a] = [0] * a
... | the_stack_v2_python_sparse | leetcode/075颜色分类.py | ShawDa/Coding | train | 0 | |
00656689e19219415c1e39edc0b716d83de665db | [
"if not hasattr(self, '_D'):\n self.logger.warning('The differential operator G.D is not available, we need to compute it. Explicitly call G.compute_differential_operator() once beforehand to suppress the warning.')\n self.compute_differential_operator()\nreturn self._D",
"v_in, v_out, weights = self.get_ed... | <|body_start_0|>
if not hasattr(self, '_D'):
self.logger.warning('The differential operator G.D is not available, we need to compute it. Explicitly call G.compute_differential_operator() once beforehand to suppress the warning.')
self.compute_differential_operator()
return self._... | GraphDifference | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphDifference:
def D(self):
"""Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`."""
<|body_0|>
def compute_differential_operator(self):
"""Compute the graph differential operator (cached). The differential op... | stack_v2_sparse_classes_36k_train_027592 | 4,230 | permissive | [
{
"docstring": "Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`.",
"name": "D",
"signature": "def D(self)"
},
{
"docstring": "Compute the graph differential operator (cached). The differential operator is a matrix such that .. math:: L = ... | 4 | stack_v2_sparse_classes_30k_train_020135 | Implement the Python class `GraphDifference` described below.
Class description:
Implement the GraphDifference class.
Method signatures and docstrings:
- def D(self): Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`.
- def compute_differential_operator(self): C... | Implement the Python class `GraphDifference` described below.
Class description:
Implement the GraphDifference class.
Method signatures and docstrings:
- def D(self): Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`.
- def compute_differential_operator(self): C... | 361f0258a210193f482c6197ea879765a9041e91 | <|skeleton|>
class GraphDifference:
def D(self):
"""Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`."""
<|body_0|>
def compute_differential_operator(self):
"""Compute the graph differential operator (cached). The differential op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphDifference:
def D(self):
"""Differential operator (for gradient and divergence). Is computed by :func:`compute_differential_operator`."""
if not hasattr(self, '_D'):
self.logger.warning('The differential operator G.D is not available, we need to compute it. Explicitly call G.c... | the_stack_v2_python_sparse | pygsp/graphs/difference.py | naspert/pygsp | train | 0 | |
f8cd6b97371d5ba7ebdccb5698c56d55206117df | [
"self.db = db\nself.path = path\nself.parse_molecules = parse_molecules",
"directories = [e for e in self.path.iterdir() if e.is_dir()]\nvalid = list()\nfor directory in directories:\n file_names = [e.name for e in directory.iterdir() if e.is_file()]\n in_found = False\n out_found = False\n for file_n... | <|body_start_0|>
self.db = db
self.path = path
self.parse_molecules = parse_molecules
<|end_body_0|>
<|body_start_1|>
directories = [e for e in self.path.iterdir() if e.is_dir()]
valid = list()
for directory in directories:
file_names = [e.name for e in direc... | A drone to parse through a collection of many AutoTS calculations and enter them into a database. | AutoTSBuilderDrone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoTSBuilderDrone:
"""A drone to parse through a collection of many AutoTS calculations and enter them into a database."""
def __init__(self, db: CatDB, path: Path, parse_molecules: bool=True):
"""Args: db (CatDB): Database connection for storing calculations. path (Path): Path to t... | stack_v2_sparse_classes_36k_train_027593 | 29,493 | no_license | [
{
"docstring": "Args: db (CatDB): Database connection for storing calculations. path (Path): Path to the root directory where calculations are stored. parse_molecules (bool): Should all molecules (for instance, along all optimization trajectories) be stored?",
"name": "__init__",
"signature": "def __ini... | 6 | stack_v2_sparse_classes_30k_train_001930 | Implement the Python class `AutoTSBuilderDrone` described below.
Class description:
A drone to parse through a collection of many AutoTS calculations and enter them into a database.
Method signatures and docstrings:
- def __init__(self, db: CatDB, path: Path, parse_molecules: bool=True): Args: db (CatDB): Database co... | Implement the Python class `AutoTSBuilderDrone` described below.
Class description:
A drone to parse through a collection of many AutoTS calculations and enter them into a database.
Method signatures and docstrings:
- def __init__(self, db: CatDB, path: Path, parse_molecules: bool=True): Args: db (CatDB): Database co... | c21e4eb86d9118365e17166c852f3ba6d36dd674 | <|skeleton|>
class AutoTSBuilderDrone:
"""A drone to parse through a collection of many AutoTS calculations and enter them into a database."""
def __init__(self, db: CatDB, path: Path, parse_molecules: bool=True):
"""Args: db (CatDB): Database connection for storing calculations. path (Path): Path to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoTSBuilderDrone:
"""A drone to parse through a collection of many AutoTS calculations and enter them into a database."""
def __init__(self, db: CatDB, path: Path, parse_molecules: bool=True):
"""Args: db (CatDB): Database connection for storing calculations. path (Path): Path to the root direc... | the_stack_v2_python_sparse | mpcat/aggregate/drones.py | espottesmith/MPcat | train | 10 |
56067c6f0a794af1aed6cc0a3bef410bf64255fa | [
"path = urlJoin(urls.CLIENT_LOCATION['GET_CLIENT_LOC'], macaddr)\nparams = {'offset': offset, 'limit': limit, 'units': units}\nresp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)\nreturn resp",
"path = urlJoin(urls.CLIENT_LOCATION['GET_FLOOR_CLIENTS'], floor_id, 'client_location')\nparams = {'off... | <|body_start_0|>
path = urlJoin(urls.CLIENT_LOCATION['GET_CLIENT_LOC'], macaddr)
params = {'offset': offset, 'limit': limit, 'units': units}
resp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)
return resp
<|end_body_0|>
<|body_start_1|>
path = urlJoin(urls.CLIEN... | A python class to obtain client location based on visualRF floor map. | ClientLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Centr... | stack_v2_sparse_classes_36k_train_027594 | 13,713 | permissive | [
{
"docstring": "Get location of a client. This function provides output only when visualRF is configured in Aruba Central. :param conn: Instance of class:`pycentral.ArubaCentralBase` to make an API call. :type conn: class:`pycentral.ArubaCentralBase` :param macaddr: Provide a macaddr of a client. For example \"... | 2 | stack_v2_sparse_classes_30k_train_005544 | Implement the Python class `ClientLocation` described below.
Class description:
A python class to obtain client location based on visualRF floor map.
Method signatures and docstrings:
- def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of a client. This function provid... | Implement the Python class `ClientLocation` described below.
Class description:
A python class to obtain client location based on visualRF floor map.
Method signatures and docstrings:
- def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of a client. This function provid... | d938396a18193473afbe54e6cc6697d2bd4954a7 | <|skeleton|>
class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Centr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Central. :param co... | the_stack_v2_python_sparse | pycentral/visualrf.py | jayp193/pycentral | train | 0 |
16a14862e1d521fa8364da6a4f74af0b0c85851b | [
"mean = 0\nstd = 0.0001\nsize = (in_features, out_features)\nself.params = {}\nself.params['weight'] = np.random.normal(mean, std, size)\nself.params['bias'] = np.zeros(out_features)\nself.gradients = {}",
"self.x = x\nw = self.params['weight']\nb = self.params['bias']\nout = np.dot(x, w) + b\nself.out = out\nret... | <|body_start_0|>
mean = 0
std = 0.0001
size = (in_features, out_features)
self.params = {}
self.params['weight'] = np.random.normal(mean, std, size)
self.params['bias'] = np.zeros(out_features)
self.gradients = {}
<|end_body_0|>
<|body_start_1|>
self.x = ... | Linear | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
def __init__(self, in_features, out_features):
"""Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. 2) Initialize biases self.params[... | stack_v2_sparse_classes_36k_train_027595 | 4,281 | permissive | [
{
"docstring": "Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. 2) Initialize biases self.params['bias'] with 0. 3) Initialize gradients with zeros.",
"name": ... | 3 | null | Implement the Python class `Linear` described below.
Class description:
Implement the Linear class.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weigh... | Implement the Python class `Linear` described below.
Class description:
Implement the Linear class.
Method signatures and docstrings:
- def __init__(self, in_features, out_features): Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weigh... | 0420873110e91e8d13e6e85a974f1856e01d28d6 | <|skeleton|>
class Linear:
def __init__(self, in_features, out_features):
"""Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. 2) Initialize biases self.params[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linear:
def __init__(self, in_features, out_features):
"""Module initialisation. Args: in_features: input dimension out_features: output dimension TODO: 1) Initialize weights self.params['weight'] using normal distribution with mean = 0 and std = 0.0001. 2) Initialize biases self.params['bias'] with 0... | the_stack_v2_python_sparse | CS324_Deep-Learning/Assignmnet1/Part 2/modules.py | Eveneko/SUSTech-Courses | train | 5 | |
95d4d9c205ac971689cf6c9f8e41df5933851dc0 | [
"parser.add_argument('--source', metavar='SOURCE', required=True, default='.', help='The SBOM file for uploading.')\nparser.add_argument('--uri', metavar='ARTIFACT_URI', required=True, help=' The URI of the artifact the SBOM is generated from.\\n The URI can be a Docker image from any Docker r... | <|body_start_0|>
parser.add_argument('--source', metavar='SOURCE', required=True, default='.', help='The SBOM file for uploading.')
parser.add_argument('--uri', metavar='ARTIFACT_URI', required=True, help=' The URI of the artifact the SBOM is generated from.\n The URI can be a Dock... | Upload an SBOM file and create a reference occurrence. | Load | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Load:
"""Upload an SBOM file and create a reference occurrence."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run the load command."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_027596 | 6,697 | permissive | [
{
"docstring": "Set up arguments for this command. Args: parser: An argparse.ArgumentPaser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run the load command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `Load` described below.
Class description:
Upload an SBOM file and create a reference occurrence.
Method signatures and docstrings:
- def Args(parser): Set up arguments for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run the load command. | Implement the Python class `Load` described below.
Class description:
Upload an SBOM file and create a reference occurrence.
Method signatures and docstrings:
- def Args(parser): Set up arguments for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run the load command.
<|skeleton|>
clas... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Load:
"""Upload an SBOM file and create a reference occurrence."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run the load command."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Load:
"""Upload an SBOM file and create a reference occurrence."""
def Args(parser):
"""Set up arguments for this command. Args: parser: An argparse.ArgumentPaser."""
parser.add_argument('--source', metavar='SOURCE', required=True, default='.', help='The SBOM file for uploading.')
... | the_stack_v2_python_sparse | lib/surface/artifacts/sbom/load.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
f62f92dccf4c1fb9f42f49ec4ec1dba1dcbf9730 | [
"self.ssh_output = None\nself.ssh_error = None\nself.sshclient = None\nself.scpclient = None\nself.hostname = hostname\nself.username = username\nself.password = password",
"is_ssh_login = True\ntry:\n self.sshclient = paramiko.SSHClient()\n self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy(... | <|body_start_0|>
self.ssh_output = None
self.ssh_error = None
self.sshclient = None
self.scpclient = None
self.hostname = hostname
self.username = username
self.password = password
<|end_body_0|>
<|body_start_1|>
is_ssh_login = True
try:
... | Class to create ssh connection to remote host for remote host command execution and scp. | SSHRemoteclient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHRemoteclient:
"""Class to create ssh connection to remote host for remote host command execution and scp."""
def __init__(self, hostname, username, password):
"""Description of argument(s): hostname Name/IP of the remote (targeting) host username User on the remote host with acces... | stack_v2_sparse_classes_36k_train_027597 | 5,826 | permissive | [
{
"docstring": "Description of argument(s): hostname Name/IP of the remote (targeting) host username User on the remote host with access to FFCD files password Password for user on remote host",
"name": "__init__",
"signature": "def __init__(self, hostname, username, password)"
},
{
"docstring":... | 6 | stack_v2_sparse_classes_30k_train_010053 | Implement the Python class `SSHRemoteclient` described below.
Class description:
Class to create ssh connection to remote host for remote host command execution and scp.
Method signatures and docstrings:
- def __init__(self, hostname, username, password): Description of argument(s): hostname Name/IP of the remote (ta... | Implement the Python class `SSHRemoteclient` described below.
Class description:
Class to create ssh connection to remote host for remote host command execution and scp.
Method signatures and docstrings:
- def __init__(self, hostname, username, password): Description of argument(s): hostname Name/IP of the remote (ta... | 7eab8897f12fa56bed3625f95ebc5e148695febf | <|skeleton|>
class SSHRemoteclient:
"""Class to create ssh connection to remote host for remote host command execution and scp."""
def __init__(self, hostname, username, password):
"""Description of argument(s): hostname Name/IP of the remote (targeting) host username User on the remote host with acces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSHRemoteclient:
"""Class to create ssh connection to remote host for remote host command execution and scp."""
def __init__(self, hostname, username, password):
"""Description of argument(s): hostname Name/IP of the remote (targeting) host username User on the remote host with access to FFCD fil... | the_stack_v2_python_sparse | ffdc/lib/ssh_utility.py | Nuvoton-Israel/openbmc-test-automation | train | 0 |
ca40df9d33f45de846c703c23d38d9edd81d45a5 | [
"_input = [10, 7, 76, 415]\nexpected = 77641510\nactual = largest_int(_input)\nself.assertEqual(expected, actual)",
"_input = [20, 15, 23, 89, 23]\nexpected = 8923232015\nactual = largest_int(_input)\nself.assertEqual(expected, actual)",
"_input = [23, 234, 2367, 23897, 230987]\nexpected = 23897236723423230987\... | <|body_start_0|>
_input = [10, 7, 76, 415]
expected = 77641510
actual = largest_int(_input)
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
_input = [20, 15, 23, 89, 23]
expected = 8923232015
actual = largest_int(_input)
self.assertEqua... | LargestIntegerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LargestIntegerTest:
def test_example(self):
"""Tests the given example"""
<|body_0|>
def test_duplicate_number(self):
"""Tests the case where the list contains the same number multiple times"""
<|body_1|>
def test_identical_first_two_digits(self):
... | stack_v2_sparse_classes_36k_train_027598 | 912 | no_license | [
{
"docstring": "Tests the given example",
"name": "test_example",
"signature": "def test_example(self)"
},
{
"docstring": "Tests the case where the list contains the same number multiple times",
"name": "test_duplicate_number",
"signature": "def test_duplicate_number(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_005053 | Implement the Python class `LargestIntegerTest` described below.
Class description:
Implement the LargestIntegerTest class.
Method signatures and docstrings:
- def test_example(self): Tests the given example
- def test_duplicate_number(self): Tests the case where the list contains the same number multiple times
- def... | Implement the Python class `LargestIntegerTest` described below.
Class description:
Implement the LargestIntegerTest class.
Method signatures and docstrings:
- def test_example(self): Tests the given example
- def test_duplicate_number(self): Tests the case where the list contains the same number multiple times
- def... | 8fecf473a36be126311deeaa42f6f708165feb9a | <|skeleton|>
class LargestIntegerTest:
def test_example(self):
"""Tests the given example"""
<|body_0|>
def test_duplicate_number(self):
"""Tests the case where the list contains the same number multiple times"""
<|body_1|>
def test_identical_first_two_digits(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LargestIntegerTest:
def test_example(self):
"""Tests the given example"""
_input = [10, 7, 76, 415]
expected = 77641510
actual = largest_int(_input)
self.assertEqual(expected, actual)
def test_duplicate_number(self):
"""Tests the case where the list contain... | the_stack_v2_python_sparse | challenges/problem_228/unit_test.py | ashishkhiani/Daily-Coding-Problems | train | 0 | |
ce3b75f0fbb7f816dd9f1aacc0c1f4828be5bb7c | [
"a, b = (0, int(sqrt(c)) + 1)\nwhile a <= b:\n sum_ = a ** 2 + b ** 2\n if sum_ == c:\n return True\n elif sum_ < c:\n a += 1\n else:\n b -= 1\nreturn False",
"def isSquare(num):\n if num < 0:\n return False\n return int(sqrt(num)) ** 2 == num\nfor i in range(int(sqrt... | <|body_start_0|>
a, b = (0, int(sqrt(c)) + 1)
while a <= b:
sum_ = a ** 2 + b ** 2
if sum_ == c:
return True
elif sum_ < c:
a += 1
else:
b -= 1
return False
<|end_body_0|>
<|body_start_1|>
de... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def judgeSquareSum(self, c):
""":type c: int :rtype: bool"""
<|body_0|>
def judgeSquareSum2(self, c):
""":type c: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a, b = (0, int(sqrt(c)) + 1)
while a <= b:
... | stack_v2_sparse_classes_36k_train_027599 | 1,411 | no_license | [
{
"docstring": ":type c: int :rtype: bool",
"name": "judgeSquareSum",
"signature": "def judgeSquareSum(self, c)"
},
{
"docstring": ":type c: int :rtype: bool",
"name": "judgeSquareSum2",
"signature": "def judgeSquareSum2(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002936 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judgeSquareSum(self, c): :type c: int :rtype: bool
- def judgeSquareSum2(self, c): :type c: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judgeSquareSum(self, c): :type c: int :rtype: bool
- def judgeSquareSum2(self, c): :type c: int :rtype: bool
<|skeleton|>
class Solution:
def judgeSquareSum(self, c):
... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def judgeSquareSum(self, c):
""":type c: int :rtype: bool"""
<|body_0|>
def judgeSquareSum2(self, c):
""":type c: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def judgeSquareSum(self, c):
""":type c: int :rtype: bool"""
a, b = (0, int(sqrt(c)) + 1)
while a <= b:
sum_ = a ** 2 + b ** 2
if sum_ == c:
return True
elif sum_ < c:
a += 1
else:
... | the_stack_v2_python_sparse | code633SumOfSquareNumbers.py | cybelewang/leetcode-python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.