blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
509d526c6cdf1e42101f8e905a9fe55af1aa7705 | [
"super().__init__()\nif isinstance(graph, DirectedMultiGraph):\n mapping = dict()\n for node in graph.get_all_nodes():\n newnode = Node(node.name)\n super().add_node(newnode)\n mapping[node] = newnode\n for edge in graph.get_all_edges():\n node1 = mapping[edge.node1]\n no... | <|body_start_0|>
super().__init__()
if isinstance(graph, DirectedMultiGraph):
mapping = dict()
for node in graph.get_all_nodes():
newnode = Node(node.name)
super().add_node(newnode)
mapping[node] = newnode
for edge in gr... | DirectedMultiGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectedMultiGraph:
def __init__(self, graph=None):
"""Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigned annotations, if any, are not copied to the new graph. :param graph: directed multigraph to copy, when Non... | stack_v2_sparse_classes_75kplus_train_000700 | 28,184 | no_license | [
{
"docstring": "Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigned annotations, if any, are not copied to the new graph. :param graph: directed multigraph to copy, when None an empty directed multigraph will be created :type graph: Dir... | 2 | null | Implement the Python class `DirectedMultiGraph` described below.
Class description:
Implement the DirectedMultiGraph class.
Method signatures and docstrings:
- def __init__(self, graph=None): Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigne... | Implement the Python class `DirectedMultiGraph` described below.
Class description:
Implement the DirectedMultiGraph class.
Method signatures and docstrings:
- def __init__(self, graph=None): Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigne... | 4e58637cabc47123da16e97b5761bd19ddaa4454 | <|skeleton|>
class DirectedMultiGraph:
def __init__(self, graph=None):
"""Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigned annotations, if any, are not copied to the new graph. :param graph: directed multigraph to copy, when Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirectedMultiGraph:
def __init__(self, graph=None):
"""Copy constructor. Creates a copy of the given directed multigraph. All nodes and edges (including weights) are copied. Assigned annotations, if any, are not copied to the new graph. :param graph: directed multigraph to copy, when None an empty dir... | the_stack_v2_python_sparse | 1steBachelor/AlgoritmenEnDatastructuren/graph_library.py | JeeVeeVee/univ | train | 0 | |
3a7e23424e3b5808423657f247230eb6bc73b742 | [
"from sagas.ja.knp_helper import knp\nresult = knp.parse(sents)\nknp_deps(result)\nprint('bnst list', '-' * 15)\nfor bnst in result.bnst_list():\n print(f'{bnst.bnst_id}, {bnst.midasi}, {bnst.parent_id}, {bnst.repname}, {bnst.dpndtype}')\nprint('\\nbnst tree', '-' * 15)\nresult.draw_bnst_tree()\nprint('\\ntag tr... | <|body_start_0|>
from sagas.ja.knp_helper import knp
result = knp.parse(sents)
knp_deps(result)
print('bnst list', '-' * 15)
for bnst in result.bnst_list():
print(f'{bnst.bnst_id}, {bnst.midasi}, {bnst.parent_id}, {bnst.repname}, {bnst.dpndtype}')
print('\nbns... | KnpCli | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnpCli:
def deps(self, sents):
"""$ python -m sagas.ja.knp_cli deps "望遠鏡で泳いでいる少女を見た。" :param sents: :return:"""
<|body_0|>
def parse(self, sents, output='console'):
"""$ python -m sagas.ja.knp_cli parse "望遠鏡で泳いでいる少女を見た。" $ python -m sagas.ja.knp_cli parse "どのおかずを注文した... | stack_v2_sparse_classes_75kplus_train_000701 | 1,412 | permissive | [
{
"docstring": "$ python -m sagas.ja.knp_cli deps \"望遠鏡で泳いでいる少女を見た。\" :param sents: :return:",
"name": "deps",
"signature": "def deps(self, sents)"
},
{
"docstring": "$ python -m sagas.ja.knp_cli parse \"望遠鏡で泳いでいる少女を見た。\" $ python -m sagas.ja.knp_cli parse \"どのおかずを注文したの?\" :param sents: :param o... | 2 | stack_v2_sparse_classes_30k_train_037424 | Implement the Python class `KnpCli` described below.
Class description:
Implement the KnpCli class.
Method signatures and docstrings:
- def deps(self, sents): $ python -m sagas.ja.knp_cli deps "望遠鏡で泳いでいる少女を見た。" :param sents: :return:
- def parse(self, sents, output='console'): $ python -m sagas.ja.knp_cli parse "望遠鏡で... | Implement the Python class `KnpCli` described below.
Class description:
Implement the KnpCli class.
Method signatures and docstrings:
- def deps(self, sents): $ python -m sagas.ja.knp_cli deps "望遠鏡で泳いでいる少女を見た。" :param sents: :return:
- def parse(self, sents, output='console'): $ python -m sagas.ja.knp_cli parse "望遠鏡で... | 9958d18ee5e75cf9794f546c904097dc1ff4f3a0 | <|skeleton|>
class KnpCli:
def deps(self, sents):
"""$ python -m sagas.ja.knp_cli deps "望遠鏡で泳いでいる少女を見た。" :param sents: :return:"""
<|body_0|>
def parse(self, sents, output='console'):
"""$ python -m sagas.ja.knp_cli parse "望遠鏡で泳いでいる少女を見た。" $ python -m sagas.ja.knp_cli parse "どのおかずを注文した... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnpCli:
def deps(self, sents):
"""$ python -m sagas.ja.knp_cli deps "望遠鏡で泳いでいる少女を見た。" :param sents: :return:"""
from sagas.ja.knp_helper import knp
result = knp.parse(sents)
knp_deps(result)
print('bnst list', '-' * 15)
for bnst in result.bnst_list():
... | the_stack_v2_python_sparse | sagas/ja/knp_cli.py | samlet/stack | train | 3 | |
bcd0383301565e06aa7b8b40ba1362564f2951d3 | [
"v = TVector3(1.0, 2.0, 3.0)\nself.assertEqual(list(v), [1.0, 2.0, 3.0])\nw = 2 * v\nself.assertEqual(w.x(), 2 * v.x())\nself.assertEqual(w.y(), 2 * v.y())\nself.assertEqual(w.z(), 2 * v.z())",
"if not legacy_pyroot:\n v = TVector3(1.0, 2.0, 3.0)\n v * 2\n self.assertEqual(v * v, 14.0)"
] | <|body_start_0|>
v = TVector3(1.0, 2.0, 3.0)
self.assertEqual(list(v), [1.0, 2.0, 3.0])
w = 2 * v
self.assertEqual(w.x(), 2 * v.x())
self.assertEqual(w.y(), 2 * v.y())
self.assertEqual(w.z(), 2 * v.z())
<|end_body_0|>
<|body_start_1|>
if not legacy_pyroot:
... | Regression09TVector3Pythonize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regression09TVector3Pythonize:
def test1TVector3(self):
"""Verify TVector3 pythonization"""
<|body_0|>
def test2TVector3(self):
"""Verify that using one operator* overload does not mask the others"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
v = ... | stack_v2_sparse_classes_75kplus_train_000702 | 29,305 | no_license | [
{
"docstring": "Verify TVector3 pythonization",
"name": "test1TVector3",
"signature": "def test1TVector3(self)"
},
{
"docstring": "Verify that using one operator* overload does not mask the others",
"name": "test2TVector3",
"signature": "def test2TVector3(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053540 | Implement the Python class `Regression09TVector3Pythonize` described below.
Class description:
Implement the Regression09TVector3Pythonize class.
Method signatures and docstrings:
- def test1TVector3(self): Verify TVector3 pythonization
- def test2TVector3(self): Verify that using one operator* overload does not mask... | Implement the Python class `Regression09TVector3Pythonize` described below.
Class description:
Implement the Regression09TVector3Pythonize class.
Method signatures and docstrings:
- def test1TVector3(self): Verify TVector3 pythonization
- def test2TVector3(self): Verify that using one operator* overload does not mask... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class Regression09TVector3Pythonize:
def test1TVector3(self):
"""Verify TVector3 pythonization"""
<|body_0|>
def test2TVector3(self):
"""Verify that using one operator* overload does not mask the others"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Regression09TVector3Pythonize:
def test1TVector3(self):
"""Verify TVector3 pythonization"""
v = TVector3(1.0, 2.0, 3.0)
self.assertEqual(list(v), [1.0, 2.0, 3.0])
w = 2 * v
self.assertEqual(w.x(), 2 * v.x())
self.assertEqual(w.y(), 2 * v.y())
self.assert... | the_stack_v2_python_sparse | python/regression/PyROOT_regressiontests.py | root-project/roottest | train | 41 | |
a7f51d00a4767bea7719cfa72ce2fa42f441d3f1 | [
"if request.dbsession is None:\n raise DBAPIError\nreturn request.dbsession.query(cls).all()",
"if request.dbsession is None:\n raise DBAPIError\nreturn request.dbsession.query(cls).get(pk)",
"if request.dbsession is None:\n raise DBAPIError\nstock = cls(**kwargs)\nrequest.dbsession.add(stock)\nreturn ... | <|body_start_0|>
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).all()
<|end_body_0|>
<|body_start_1|>
if request.dbsession is None:
raise DBAPIError
return request.dbsession.query(cls).get(pk)
<|end_body_1|>
<|body_start_2|>
... | This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB | Stock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, requ... | stack_v2_sparse_classes_75kplus_train_000703 | 2,531 | permissive | [
{
"docstring": "GET all stocks we have in our DB",
"name": "all",
"signature": "def all(cls, request)"
},
{
"docstring": "Retrieve a single instance from the database by the primary key for that record. pk is used for the primary key",
"name": "one",
"signature": "def one(cls, request=No... | 4 | stack_v2_sparse_classes_30k_train_038993 | Implement the Python class `Stock` described below.
Class description:
This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last upda... | Implement the Python class `Stock` described below.
Class description:
This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last upda... | 1e5993f72d70d55ccab65034c0b2512e96ad57cc | <|skeleton|>
class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stock:
"""This creates instances of a company stock, using information from IEX API. We get company name, symbol, exchange, indusry, website, description, ceo, stock type, and sector. We also track when this info was put into our DB and when it was last updated in our DB"""
def all(cls, request):
... | the_stack_v2_python_sparse | stocks_api/models/stock.py | SeattleChris/stocks_api | train | 0 |
2cf202a505a4cf08901172b4253fdad983b401c1 | [
"try:\n skip, limit = self.get_paging_parser()\n count = self.mongo.operation.count()\n operations = list(self.mongo.operation.find().skip(skip).limit(limit))\n data = {'operations': marshal(operations, operation_field), 'total': count}\n return self.Response.return_true_data(data)\nexcept Exception ... | <|body_start_0|>
try:
skip, limit = self.get_paging_parser()
count = self.mongo.operation.count()
operations = list(self.mongo.operation.find().skip(skip).limit(limit))
data = {'operations': marshal(operations, operation_field), 'total': count}
return ... | OperationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperationManager:
def fetch_operaion_list(self):
"""获取运维数据列表"""
<|body_0|>
def fetch_operaion_detail(self, operation_id):
"""获取运维数据具体那周的详情"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
skip, limit = self.get_paging_parser()
... | stack_v2_sparse_classes_75kplus_train_000704 | 1,327 | no_license | [
{
"docstring": "获取运维数据列表",
"name": "fetch_operaion_list",
"signature": "def fetch_operaion_list(self)"
},
{
"docstring": "获取运维数据具体那周的详情",
"name": "fetch_operaion_detail",
"signature": "def fetch_operaion_detail(self, operation_id)"
}
] | 2 | null | Implement the Python class `OperationManager` described below.
Class description:
Implement the OperationManager class.
Method signatures and docstrings:
- def fetch_operaion_list(self): 获取运维数据列表
- def fetch_operaion_detail(self, operation_id): 获取运维数据具体那周的详情 | Implement the Python class `OperationManager` described below.
Class description:
Implement the OperationManager class.
Method signatures and docstrings:
- def fetch_operaion_list(self): 获取运维数据列表
- def fetch_operaion_detail(self, operation_id): 获取运维数据具体那周的详情
<|skeleton|>
class OperationManager:
def fetch_operai... | 64be1148f38274c12fcaa8b2062bfe221d5eb524 | <|skeleton|>
class OperationManager:
def fetch_operaion_list(self):
"""获取运维数据列表"""
<|body_0|>
def fetch_operaion_detail(self, operation_id):
"""获取运维数据具体那周的详情"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OperationManager:
def fetch_operaion_list(self):
"""获取运维数据列表"""
try:
skip, limit = self.get_paging_parser()
count = self.mongo.operation.count()
operations = list(self.mongo.operation.find().skip(skip).limit(limit))
data = {'operations': marshal(... | the_stack_v2_python_sparse | app/controllers/operation_c.py | leeexing/opera-api | train | 1 | |
4598b59d5742015b1bb1cbe9beef3c256677f14a | [
"self.logger = logger\ntry:\n self.db = Database(db_connection)\n self.ingester = UpsertIngester(db_connection)\n self.oh = OHWrapper(logger=logger, files_directory=BULK_FILES_DIRECTORY, master_token=master_token)\n self.current_source = current_source\nexcept Psycopg2Error:\n logger.error(f'Error oc... | <|body_start_0|>
self.logger = logger
try:
self.db = Database(db_connection)
self.ingester = UpsertIngester(db_connection)
self.oh = OHWrapper(logger=logger, files_directory=BULK_FILES_DIRECTORY, master_token=master_token)
self.current_source = current_sou... | OpenHumansETL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenHumansETL:
def __init__(self, logger, db_connection, master_token, current_source):
"""Class to initialise downloading of files from OH, convert files into lists of dictionaries, and upload to db :param logger: logging object passed from parent script :param db_connection: database c... | stack_v2_sparse_classes_75kplus_train_000705 | 7,383 | no_license | [
{
"docstring": "Class to initialise downloading of files from OH, convert files into lists of dictionaries, and upload to db :param logger: logging object passed from parent script :param db_connection: database connection in the form of psycopg2.connect(...)",
"name": "__init__",
"signature": "def __in... | 4 | stack_v2_sparse_classes_30k_train_010881 | Implement the Python class `OpenHumansETL` described below.
Class description:
Implement the OpenHumansETL class.
Method signatures and docstrings:
- def __init__(self, logger, db_connection, master_token, current_source): Class to initialise downloading of files from OH, convert files into lists of dictionaries, and... | Implement the Python class `OpenHumansETL` described below.
Class description:
Implement the OpenHumansETL class.
Method signatures and docstrings:
- def __init__(self, logger, db_connection, master_token, current_source): Class to initialise downloading of files from OH, convert files into lists of dictionaries, and... | 5f3b2cabc1205f5285a9f59727e636e9701e1dc6 | <|skeleton|>
class OpenHumansETL:
def __init__(self, logger, db_connection, master_token, current_source):
"""Class to initialise downloading of files from OH, convert files into lists of dictionaries, and upload to db :param logger: logging object passed from parent script :param db_connection: database c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenHumansETL:
def __init__(self, logger, db_connection, master_token, current_source):
"""Class to initialise downloading of files from OH, convert files into lists of dictionaries, and upload to db :param logger: logging object passed from parent script :param db_connection: database connection in t... | the_stack_v2_python_sparse | open-humans-etl/full_ingest.py | latainethomas/open-aps-streaming | train | 1 | |
ef570b7fd344a4be8df24e21f2e3eb89546362ee | [
"processingToolPaths = self.getProcessingToolPaths(processor_directory)\nfor processingToolPath in processingToolPaths:\n processingToolName = splitext(basename(processingToolPath))[0]\n processingToolModule = imp.load_source(processingToolName, processingToolPath)\n ProcessingTool = getattr(processingTool... | <|body_start_0|>
processingToolPaths = self.getProcessingToolPaths(processor_directory)
for processingToolPath in processingToolPaths:
processingToolName = splitext(basename(processingToolPath))[0]
processingToolModule = imp.load_source(processingToolName, processingToolPath)
... | Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...): Return the appropriate processing tool for a eopy.product.productIO.Product.Product ob... | ProductProcessingTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductProcessingTool:
"""Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...): Return the appropriate processing too... | stack_v2_sparse_classes_75kplus_train_000706 | 4,338 | no_license | [
{
"docstring": "Return the appropriate processing tool for a *eopy.product.productIO.Product.Product* object with a specified product_string entry in it's attributes dictionary for a given *eopy.product.productProcessing* processor :type processor_directory: str :param processor_directory: Directory of *eopy.da... | 2 | stack_v2_sparse_classes_30k_test_000854 | Implement the Python class `ProductProcessingTool` described below.
Class description:
Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...)... | Implement the Python class `ProductProcessingTool` described below.
Class description:
Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...)... | bea8becf9e71d0acd59121781ae4b029873a3141 | <|skeleton|>
class ProductProcessingTool:
"""Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...): Return the appropriate processing too... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductProcessingTool:
"""Provides functionality to return appropriate product Processing Tool for a *eopy.dataIO.Product.Product* instance with a specified *product_string* entry in it's attributes dictionary. :Methods: .. py:method:: setProcessingTool(...): Return the appropriate processing tool for a eopy.... | the_stack_v2_python_sparse | product/productProcessing/ProductProcessingTool.py | shunt16/eopy | train | 0 |
be9a7462be4842eb8df4a3e1d834e74c8e159e3a | [
"self.crypto = crypto\nself.liveness = liveness\nself.game_instance = game_instance\nself.mailbox = mailbox\nself.agent_name = agent_name\nself.dialogues = game_instance.dialogues\nself.negotiation_behaviour = FIPABehaviour(crypto, game_instance, agent_name)",
"assert message.get('performative') == FIPAMessage.Pe... | <|body_start_0|>
self.crypto = crypto
self.liveness = liveness
self.game_instance = game_instance
self.mailbox = mailbox
self.agent_name = agent_name
self.dialogues = game_instance.dialogues
self.negotiation_behaviour = FIPABehaviour(crypto, game_instance, agent_n... | The DialogueReactions class defines the reactions of an agent in the context of a Dialogue. | DialogueReactions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogueReactions:
"""The DialogueReactions class defines the reactions of an agent in the context of a Dialogue."""
def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None:
"""Instantiate the DialogueReactions. :... | stack_v2_sparse_classes_75kplus_train_000707 | 22,792 | permissive | [
{
"docstring": "Instantiate the DialogueReactions. :param crypto: the crypto module :param liveness: the liveness module :param game_instance: the game instance :param mailbox: the mailbox of the agent :param agent_name: the agent name :return: None",
"name": "__init__",
"signature": "def __init__(self,... | 5 | stack_v2_sparse_classes_30k_train_004335 | Implement the Python class `DialogueReactions` described below.
Class description:
The DialogueReactions class defines the reactions of an agent in the context of a Dialogue.
Method signatures and docstrings:
- def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent... | Implement the Python class `DialogueReactions` described below.
Class description:
The DialogueReactions class defines the reactions of an agent in the context of a Dialogue.
Method signatures and docstrings:
- def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent... | 33c4aa24ca8daf26f2c8f2d2fa38d7f4bf750cfa | <|skeleton|>
class DialogueReactions:
"""The DialogueReactions class defines the reactions of an agent in the context of a Dialogue."""
def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None:
"""Instantiate the DialogueReactions. :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DialogueReactions:
"""The DialogueReactions class defines the reactions of an agent in the context of a Dialogue."""
def __init__(self, crypto: Crypto, liveness: Liveness, game_instance: GameInstance, mailbox: MailBox, agent_name: str) -> None:
"""Instantiate the DialogueReactions. :param crypto:... | the_stack_v2_python_sparse | tac/agents/participant/v1/base/reactions.py | fetchai/agents-tac | train | 30 |
175d1eaf35b396011e9481660300561d4dc466e5 | [
"import collections as co\nself.um, self.s, self.r = (co.defaultdict(list), '', set())\nfor s, t in zip(sentences, times):\n self.r |= {s}\n for i in range(len(s)):\n self.um[s[:i + 1]].append([-t, s])",
"if c == '#':\n if self.s in self.r:\n for i in range(len(self.s)):\n for j ... | <|body_start_0|>
import collections as co
self.um, self.s, self.r = (co.defaultdict(list), '', set())
for s, t in zip(sentences, times):
self.r |= {s}
for i in range(len(s)):
self.um[s[:i + 1]].append([-t, s])
<|end_body_0|>
<|body_start_1|>
if c ... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections as ... | stack_v2_sparse_classes_75kplus_train_000708 | 1,337 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046270 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | db64a67869aae4f0e55e78b65a7e04f5bc2e671c | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
import collections as co
self.um, self.s, self.r = (co.defaultdict(list), '', set())
for s, t in zip(sentences, times):
self.r |= {s}
for i ... | the_stack_v2_python_sparse | Questiondir/642.design-search-autocomplete-system/642.design-search-autocomplete-system_109800207.py | cczhong11/Leetcode-contest-code-downloader | train | 0 | |
fcd28400a292e2ebc9466e17a30d1df5ba5bc547 | [
"uom = self._node.uom\nif isinstance(uom, list):\n return UOM_FRIENDLY_NAME.get(uom[0], uom[0])\nisy_states = UOM_TO_STATES.get(uom)\nif isy_states:\n return isy_states\nif uom in [UOM_ON_OFF, UOM_INDEX]:\n return uom\nreturn UOM_FRIENDLY_NAME.get(uom)",
"value = self._node.status\nif value == ISY_VALUE_... | <|body_start_0|>
uom = self._node.uom
if isinstance(uom, list):
return UOM_FRIENDLY_NAME.get(uom[0], uom[0])
isy_states = UOM_TO_STATES.get(uom)
if isy_states:
return isy_states
if uom in [UOM_ON_OFF, UOM_INDEX]:
return uom
return UOM_F... | Representation of an ISY994 sensor device. | ISYSensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYSensorEntity:
"""Representation of an ISY994 sensor device."""
def raw_unit_of_measurement(self) -> dict | str:
"""Get the raw unit of measurement for the ISY994 sensor device."""
<|body_0|>
def state(self) -> str:
"""Get the state of the ISY994 sensor device.... | stack_v2_sparse_classes_75kplus_train_000709 | 4,390 | permissive | [
{
"docstring": "Get the raw unit of measurement for the ISY994 sensor device.",
"name": "raw_unit_of_measurement",
"signature": "def raw_unit_of_measurement(self) -> dict | str"
},
{
"docstring": "Get the state of the ISY994 sensor device.",
"name": "state",
"signature": "def state(self)... | 3 | stack_v2_sparse_classes_30k_train_020834 | Implement the Python class `ISYSensorEntity` described below.
Class description:
Representation of an ISY994 sensor device.
Method signatures and docstrings:
- def raw_unit_of_measurement(self) -> dict | str: Get the raw unit of measurement for the ISY994 sensor device.
- def state(self) -> str: Get the state of the ... | Implement the Python class `ISYSensorEntity` described below.
Class description:
Representation of an ISY994 sensor device.
Method signatures and docstrings:
- def raw_unit_of_measurement(self) -> dict | str: Get the raw unit of measurement for the ISY994 sensor device.
- def state(self) -> str: Get the state of the ... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ISYSensorEntity:
"""Representation of an ISY994 sensor device."""
def raw_unit_of_measurement(self) -> dict | str:
"""Get the raw unit of measurement for the ISY994 sensor device."""
<|body_0|>
def state(self) -> str:
"""Get the state of the ISY994 sensor device.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ISYSensorEntity:
"""Representation of an ISY994 sensor device."""
def raw_unit_of_measurement(self) -> dict | str:
"""Get the raw unit of measurement for the ISY994 sensor device."""
uom = self._node.uom
if isinstance(uom, list):
return UOM_FRIENDLY_NAME.get(uom[0], uo... | the_stack_v2_python_sparse | homeassistant/components/isy994/sensor.py | BenWoodford/home-assistant | train | 11 |
dc8b33504b04a6e63b8567d7fee920896e9c3994 | [
"if root == None:\n return\nroot.left, root.right = (root.right, root.left)\nself.invertTree(root.left)\nself.invertTree(root.right)\nreturn root",
"if not root:\n return None\nqueue = deque()\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n node.left, node.right = (node.right, node.left)\... | <|body_start_0|>
if root == None:
return
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return None
queue = deque()
qu... | Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree."""
def invertTree(self, root):
""":type root: TreeNo... | stack_v2_sparse_classes_75kplus_train_000710 | 1,802 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042589 | Implement the Python class `Solution` described below.
Class description:
Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree.
Method signatures and doc... | Implement the Python class `Solution` described below.
Class description:
Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree.
Method signatures and doc... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree."""
def invertTree(self, root):
""":type root: TreeNo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Recursive Stats: O(n) time, O(1) space Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree."""
def invertTree(self, root):
""":type root: TreeNode :rtype: Tr... | the_stack_v2_python_sparse | 226-invert_binary_tree.py | stevestar888/leetcode-problems | train | 2 |
a6f3666caa66d1c8d3ceb7267e6613f9b4f96bd3 | [
"try:\n return 'IPv6' if type(ip_address(IP)) is IPv6Address else 'IPv4'\nexcept ValueError:\n return 'Neither'",
"chunk_IPv4 = '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\npatten_IPv4 = re.compile('^(' + chunk_IPv4 + '\\\\.){3}' + chunk_IPv4 + '$')\nchunk_IPv6 = '([0-9a-fA-F]{1,4})'\npatten_IPv6 =... | <|body_start_0|>
try:
return 'IPv6' if type(ip_address(IP)) is IPv6Address else 'IPv4'
except ValueError:
return 'Neither'
<|end_body_0|>
<|body_start_1|>
chunk_IPv4 = '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
patten_IPv4 = re.compile('^(' + chunk_IPv4... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def valid_IP_address(self, IP: str) -> str:
"""内置函数。"""
<|body_0|>
def valid_IP_address_2(self, IP: str) -> str:
"""正则表达式。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return 'IPv6' if type(ip_address(IP)) is IP... | stack_v2_sparse_classes_75kplus_train_000711 | 4,067 | no_license | [
{
"docstring": "内置函数。",
"name": "valid_IP_address",
"signature": "def valid_IP_address(self, IP: str) -> str"
},
{
"docstring": "正则表达式。",
"name": "valid_IP_address_2",
"signature": "def valid_IP_address_2(self, IP: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_044594 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def valid_IP_address(self, IP: str) -> str: 内置函数。
- def valid_IP_address_2(self, IP: str) -> str: 正则表达式。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def valid_IP_address(self, IP: str) -> str: 内置函数。
- def valid_IP_address_2(self, IP: str) -> str: 正则表达式。
<|skeleton|>
class OfficialSolution:
def valid_IP_a... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def valid_IP_address(self, IP: str) -> str:
"""内置函数。"""
<|body_0|>
def valid_IP_address_2(self, IP: str) -> str:
"""正则表达式。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficialSolution:
def valid_IP_address(self, IP: str) -> str:
"""内置函数。"""
try:
return 'IPv6' if type(ip_address(IP)) is IPv6Address else 'IPv4'
except ValueError:
return 'Neither'
def valid_IP_address_2(self, IP: str) -> str:
"""正则表达式。"""
ch... | the_stack_v2_python_sparse | 0468_validate-ip-address.py | Nigirimeshi/leetcode | train | 0 | |
0d63ce587e4463078e380c1a4be36de6870278b3 | [
"try:\n cls._run(part, opts or popts.PowerOnOpts(), timeout, synchronous=synchronous)\nexcept pexc.JobRequestTimedOut as error:\n LOG.exception(error)\n raise pexc.VMPowerOnTimeout(lpar_nm=part.name, timeout=timeout)\nexcept pexc.JobRequestFailed as error:\n emsg = six.text_type(error)\n if any((err_... | <|body_start_0|>
try:
cls._run(part, opts or popts.PowerOnOpts(), timeout, synchronous=synchronous)
except pexc.JobRequestTimedOut as error:
LOG.exception(error)
raise pexc.VMPowerOnTimeout(lpar_nm=part.name, timeout=timeout)
except pexc.JobRequestFailed as er... | Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details. | PowerOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
... | stack_v2_sparse_classes_75kplus_train_000712 | 23,048 | permissive | [
{
"docstring": "Power on a partition. :param part: Partition (LPAR or VIOS) wrapper indicating the partition to power on. :param opts: An instance of power_opts.PowerOnOpts indicating additional options to specify to the PowerOn operation. By default, no additional options are used. :param timeout: value in sec... | 3 | stack_v2_sparse_classes_30k_train_050148 | Implement the Python class `PowerOp` described below.
Class description:
Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the... | Implement the Python class `PowerOp` described below.
Class description:
Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the... | 68f2b586b4f17489f379534ab52fc56a524b6da5 | <|skeleton|>
class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PowerOp:
"""Provides granular control over a partition PowerOn/Off Job. Use the start or stop @classmethod to invoke the appropriate Job. Jobs invoked through these methods are never retried. If they fail or time out, they raise relevant exceptions - see the methods' docstrings for details."""
def start(... | the_stack_v2_python_sparse | pypowervm/tasks/power.py | powervm/pypowervm | train | 25 |
f378a17a35dfb59cf36fd54569ea56ffcbfe78c2 | [
"text = self._clean_text(sentence)\ntext = self._tokenize_chinese_chars(text)\norig_tokens = whitespace_tokenize(text)\nsplit_tokens = []\nfor token in orig_tokens:\n if self.do_lower_case:\n token = token.lower()\n token = self._run_strip_accents(token)\n split_tokens.extend(self._run_split_on_... | <|body_start_0|>
text = self._clean_text(sentence)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token = self._... | BertBasicSplitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertBasicSplitter:
def split_words(self, sentence: str) -> List[Token]:
"""Tokenizes a piece of text."""
<|body_0|>
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
<|body_1|>
def _run_split_on_punc(self, text):
"""S... | stack_v2_sparse_classes_75kplus_train_000713 | 9,323 | no_license | [
{
"docstring": "Tokenizes a piece of text.",
"name": "split_words",
"signature": "def split_words(self, sentence: str) -> List[Token]"
},
{
"docstring": "Strips accents from a piece of text.",
"name": "_run_strip_accents",
"signature": "def _run_strip_accents(self, text)"
},
{
"d... | 6 | stack_v2_sparse_classes_30k_train_023619 | Implement the Python class `BertBasicSplitter` described below.
Class description:
Implement the BertBasicSplitter class.
Method signatures and docstrings:
- def split_words(self, sentence: str) -> List[Token]: Tokenizes a piece of text.
- def _run_strip_accents(self, text): Strips accents from a piece of text.
- def... | Implement the Python class `BertBasicSplitter` described below.
Class description:
Implement the BertBasicSplitter class.
Method signatures and docstrings:
- def split_words(self, sentence: str) -> List[Token]: Tokenizes a piece of text.
- def _run_strip_accents(self, text): Strips accents from a piece of text.
- def... | 2e7e82e9ae9fa6fc93d0f498ac67acc5b84fe7f3 | <|skeleton|>
class BertBasicSplitter:
def split_words(self, sentence: str) -> List[Token]:
"""Tokenizes a piece of text."""
<|body_0|>
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
<|body_1|>
def _run_split_on_punc(self, text):
"""S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BertBasicSplitter:
def split_words(self, sentence: str) -> List[Token]:
"""Tokenizes a piece of text."""
text = self._clean_text(sentence)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_token... | the_stack_v2_python_sparse | semmatch/data/tokenizers/word_spliter.py | MRuAyAN/SemMatch | train | 0 | |
250be7c797d2c6e674b4e81044cf164e552d964f | [
"par = [[p] if p != -1 else [] for p in parent]\nq = [par[i] for i, p in enumerate(parent) if p != -1]\ni = 0\nwhile q:\n new_q = []\n for p in q:\n if not i < len(par[p[i]]):\n continue\n p.append(par[p[i]][i])\n new_q.append(p)\n q = new_q\n i += 1\nself.__parent = par"... | <|body_start_0|>
par = [[p] if p != -1 else [] for p in parent]
q = [par[i] for i, p in enumerate(parent) if p != -1]
i = 0
while q:
new_q = []
for p in q:
if not i < len(par[p[i]]):
continue
p.append(par[p[i]][i... | TreeAncestor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeAncestor:
def __init__(self, n, parent):
""":type n: int :type parent: List[int]"""
<|body_0|>
def getKthAncestor(self, node, k):
""":type node: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
par = [[p] if p != -1 e... | stack_v2_sparse_classes_75kplus_train_000714 | 1,225 | permissive | [
{
"docstring": ":type n: int :type parent: List[int]",
"name": "__init__",
"signature": "def __init__(self, n, parent)"
},
{
"docstring": ":type node: int :type k: int :rtype: int",
"name": "getKthAncestor",
"signature": "def getKthAncestor(self, node, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053030 | Implement the Python class `TreeAncestor` described below.
Class description:
Implement the TreeAncestor class.
Method signatures and docstrings:
- def __init__(self, n, parent): :type n: int :type parent: List[int]
- def getKthAncestor(self, node, k): :type node: int :type k: int :rtype: int | Implement the Python class `TreeAncestor` described below.
Class description:
Implement the TreeAncestor class.
Method signatures and docstrings:
- def __init__(self, n, parent): :type n: int :type parent: List[int]
- def getKthAncestor(self, node, k): :type node: int :type k: int :rtype: int
<|skeleton|>
class Tree... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class TreeAncestor:
def __init__(self, n, parent):
""":type n: int :type parent: List[int]"""
<|body_0|>
def getKthAncestor(self, node, k):
""":type node: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeAncestor:
def __init__(self, n, parent):
""":type n: int :type parent: List[int]"""
par = [[p] if p != -1 else [] for p in parent]
q = [par[i] for i, p in enumerate(parent) if p != -1]
i = 0
while q:
new_q = []
for p in q:
if ... | the_stack_v2_python_sparse | Python/kth-ancestor-of-a-tree-node.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
cd4b67090e3409f8da2ac6a07ff6a899510a1805 | [
"points_with_distance = [(point, point[0] ** 2 + point[1] ** 2) for point in points]\npoints_with_distance = sorted(points_with_distance, key=lambda a: a[1])\nreturn [point[0] for point in points_with_distance][:K]",
"import heapq\nh = []\nfor point in points:\n heapq.heappush(h, (-point[0] ** 2 - point[1] ** ... | <|body_start_0|>
points_with_distance = [(point, point[0] ** 2 + point[1] ** 2) for point in points]
points_with_distance = sorted(points_with_distance, key=lambda a: a[1])
return [point[0] for point in points_with_distance][:K]
<|end_body_0|>
<|body_start_1|>
import heapq
h = [... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)"""
<|body_0|>
def kClosest_1(self, points, K):
"""1308 ms 17.7 MB O(nlgk) :param points: :param K: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_000715 | 4,947 | no_license | [
{
"docstring": ":type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)",
"name": "kClosest",
"signature": "def kClosest(self, points, K)"
},
{
"docstring": "1308 ms 17.7 MB O(nlgk) :param points: :param K: :return:",
"name": "kClosest_1",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_046748 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)
- def kClosest_1(self, points, K): 1308 ms 17.7 MB O(nlgk)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points, K): :type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)
- def kClosest_1(self, points, K): 1308 ms 17.7 MB O(nlgk)... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)"""
<|body_0|>
def kClosest_1(self, points, K):
"""1308 ms 17.7 MB O(nlgk) :param points: :param K: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kClosest(self, points, K):
""":type points: List[List[int]] :type K: int :rtype: List[List[int]] 1304 ms 18 MB O(nlgn)"""
points_with_distance = [(point, point[0] ** 2 + point[1] ** 2) for point in points]
points_with_distance = sorted(points_with_distance, key=lambda a: ... | the_stack_v2_python_sparse | KClosestPointsToOrigin_MID_973.py | 953250587/leetcode-python | train | 2 | |
9f93c780de2c717e71480575681c32389e263806 | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_neighbor_v4_by_search(self.search)\n objects = obj_model['query_set']\n only_main_property = False\nelse:\n ids = kwargs.get('obj_ids').split(';')\n objects = facade.get_neighbor_v4_by_ids(ids)\n only_main_property = True\n obj_model = Non... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_neighbor_v4_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
else:
ids = kwargs.get('obj_ids').split(';')
objects = facade.get_neighbor_v4_b... | NeighborDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighborDBView:
def get(self, request, **kwargs):
"""Returns a list of Neighbors by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new Neighbor."""
<|body_1|>
def put(self, request):
"""Update Neighbors."""
... | stack_v2_sparse_classes_75kplus_train_000716 | 12,495 | permissive | [
{
"docstring": "Returns a list of Neighbors by ids ou dict.",
"name": "get",
"signature": "def get(self, request, **kwargs)"
},
{
"docstring": "Create new Neighbor.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update Neighbors.",
... | 4 | stack_v2_sparse_classes_30k_train_044680 | Implement the Python class `NeighborDBView` described below.
Class description:
Implement the NeighborDBView class.
Method signatures and docstrings:
- def get(self, request, **kwargs): Returns a list of Neighbors by ids ou dict.
- def post(self, request, *args, **kwargs): Create new Neighbor.
- def put(self, request... | Implement the Python class `NeighborDBView` described below.
Class description:
Implement the NeighborDBView class.
Method signatures and docstrings:
- def get(self, request, **kwargs): Returns a list of Neighbors by ids ou dict.
- def post(self, request, *args, **kwargs): Create new Neighbor.
- def put(self, request... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class NeighborDBView:
def get(self, request, **kwargs):
"""Returns a list of Neighbors by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new Neighbor."""
<|body_1|>
def put(self, request):
"""Update Neighbors."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeighborDBView:
def get(self, request, **kwargs):
"""Returns a list of Neighbors by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_neighbor_v4_by_search(self.search)
objects = obj_model['query_set']
only_main_property = False
el... | the_stack_v2_python_sparse | networkapi/api_neighbor/v4/views.py | globocom/GloboNetworkAPI | train | 86 | |
68d0c9bf025cc3834ab5d71b253f2f213ae64bb7 | [
"dummy = ListNode(0)\ndummy.next = head\np = dummy\nwhile p.next and p.next.val < x:\n p = p.next\nif not p.next:\n return dummy.next\nq = p.next\nm = q.next\nwhile m:\n if m.val >= x:\n m = m.next\n q = q.next\n else:\n q.next = m.next\n temp = p.next\n p.next = m\n ... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
p = dummy
while p.next and p.next.val < x:
p = p.next
if not p.next:
return dummy.next
q = p.next
m = q.next
while m:
if m.val >= x:
m = m.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partition_one_dummy(self, head, x):
""":type head: ListNode :type x: int :rtype: ListNode"""
<|body_0|>
def partition_two_dummy(self, head, x):
""":type head: ListNode :type x: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_000717 | 1,659 | no_license | [
{
"docstring": ":type head: ListNode :type x: int :rtype: ListNode",
"name": "partition_one_dummy",
"signature": "def partition_one_dummy(self, head, x)"
},
{
"docstring": ":type head: ListNode :type x: int :rtype: ListNode",
"name": "partition_two_dummy",
"signature": "def partition_two... | 2 | stack_v2_sparse_classes_30k_val_000290 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition_one_dummy(self, head, x): :type head: ListNode :type x: int :rtype: ListNode
- def partition_two_dummy(self, head, x): :type head: ListNode :type x: int :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition_one_dummy(self, head, x): :type head: ListNode :type x: int :rtype: ListNode
- def partition_two_dummy(self, head, x): :type head: ListNode :type x: int :rtype: Lis... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def partition_one_dummy(self, head, x):
""":type head: ListNode :type x: int :rtype: ListNode"""
<|body_0|>
def partition_two_dummy(self, head, x):
""":type head: ListNode :type x: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def partition_one_dummy(self, head, x):
""":type head: ListNode :type x: int :rtype: ListNode"""
dummy = ListNode(0)
dummy.next = head
p = dummy
while p.next and p.next.val < x:
p = p.next
if not p.next:
return dummy.next
... | the_stack_v2_python_sparse | medium/linklist/test_86_Partition_List.py | wuxu1019/leetcode_sophia | train | 1 | |
a6fbe29ea097848f408e6f547887fc4976c88a84 | [
"self.driver.get(url)\nself.driver.max_window()\nself.driver.find_element(locator.HeaderLocator.Isellcar).click()\nsell_is_dispayed = self.driver.is_display(locator.HeaderLocator.sell_img)\ntt_check.assertTrue(sell_is_dispayed, '我要卖车页是否显示:%s' % sell_is_dispayed)",
"self.driver.get(url)\nself.driver.max_window()\n... | <|body_start_0|>
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.Isellcar).click()
sell_is_dispayed = self.driver.is_display(locator.HeaderLocator.sell_img)
tt_check.assertTrue(sell_is_dispayed, '我要卖车页是否显示:%s' % sell_is_dispayed)
<|end... | sellcar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sellcar:
def test_Isellcar1(self):
"""测试首页我要卖车跳转,@author:xulanzhong"""
<|body_0|>
def test_Isellcar2(self):
"""测试首页我要卖车按钮跳转,@author:xulanzhong"""
<|body_1|>
def test_Isellcar3(self):
"""测试首页免费估价按钮跳转,@author:xulanzhong"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus_train_000718 | 1,785 | no_license | [
{
"docstring": "测试首页我要卖车跳转,@author:xulanzhong",
"name": "test_Isellcar1",
"signature": "def test_Isellcar1(self)"
},
{
"docstring": "测试首页我要卖车按钮跳转,@author:xulanzhong",
"name": "test_Isellcar2",
"signature": "def test_Isellcar2(self)"
},
{
"docstring": "测试首页免费估价按钮跳转,@author:xulanzh... | 3 | stack_v2_sparse_classes_30k_train_033242 | Implement the Python class `sellcar` described below.
Class description:
Implement the sellcar class.
Method signatures and docstrings:
- def test_Isellcar1(self): 测试首页我要卖车跳转,@author:xulanzhong
- def test_Isellcar2(self): 测试首页我要卖车按钮跳转,@author:xulanzhong
- def test_Isellcar3(self): 测试首页免费估价按钮跳转,@author:xulanzhong | Implement the Python class `sellcar` described below.
Class description:
Implement the sellcar class.
Method signatures and docstrings:
- def test_Isellcar1(self): 测试首页我要卖车跳转,@author:xulanzhong
- def test_Isellcar2(self): 测试首页我要卖车按钮跳转,@author:xulanzhong
- def test_Isellcar3(self): 测试首页免费估价按钮跳转,@author:xulanzhong
<|s... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class sellcar:
def test_Isellcar1(self):
"""测试首页我要卖车跳转,@author:xulanzhong"""
<|body_0|>
def test_Isellcar2(self):
"""测试首页我要卖车按钮跳转,@author:xulanzhong"""
<|body_1|>
def test_Isellcar3(self):
"""测试首页免费估价按钮跳转,@author:xulanzhong"""
<|body_2|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sellcar:
def test_Isellcar1(self):
"""测试首页我要卖车跳转,@author:xulanzhong"""
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.Isellcar).click()
sell_is_dispayed = self.driver.is_display(locator.HeaderLocator.sell_img)
tt_che... | the_stack_v2_python_sparse | mc/taochePC/test_crawler/test_homepage/test_sellcarlink.py | boeai/mc | train | 0 | |
e574d67b7d7093e24f662d892af3b9d85b5273e3 | [
"self.asg = AwsClient().connect('autoscaling', region_name)\ntry:\n self.asg.describe_auto_scaling_groups()\nexcept EndpointConnectionError:\n print('Autoscaling resource is not available in this aws region')\n return",
"for scaling in self.list_asg(older_than_seconds):\n try:\n self.asg.delete... | <|body_start_0|>
self.asg = AwsClient().connect('autoscaling', region_name)
try:
self.asg.describe_auto_scaling_groups()
except EndpointConnectionError:
print('Autoscaling resource is not available in this aws region')
return
<|end_body_0|>
<|body_start_1|>
... | Abstract autoscaling nuke in a class. | NukeAutoscaling | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NukeAutoscaling:
"""Abstract autoscaling nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize autoscaling nuke."""
<|body_0|>
def nuke(self, older_than_seconds: float) -> None:
"""Autoscaling deleting function. Deleting all Autoscaling ... | stack_v2_sparse_classes_75kplus_train_000719 | 3,293 | permissive | [
{
"docstring": "Initialize autoscaling nuke.",
"name": "__init__",
"signature": "def __init__(self, region_name=None) -> None"
},
{
"docstring": "Autoscaling deleting function. Deleting all Autoscaling Groups and Launch Configurations resources with a timestamp greater than older_than_seconds. :... | 4 | stack_v2_sparse_classes_30k_test_002218 | Implement the Python class `NukeAutoscaling` described below.
Class description:
Abstract autoscaling nuke in a class.
Method signatures and docstrings:
- def __init__(self, region_name=None) -> None: Initialize autoscaling nuke.
- def nuke(self, older_than_seconds: float) -> None: Autoscaling deleting function. Dele... | Implement the Python class `NukeAutoscaling` described below.
Class description:
Abstract autoscaling nuke in a class.
Method signatures and docstrings:
- def __init__(self, region_name=None) -> None: Initialize autoscaling nuke.
- def nuke(self, older_than_seconds: float) -> None: Autoscaling deleting function. Dele... | 25c4159e71935a9903a41540c168992586c5ba0c | <|skeleton|>
class NukeAutoscaling:
"""Abstract autoscaling nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize autoscaling nuke."""
<|body_0|>
def nuke(self, older_than_seconds: float) -> None:
"""Autoscaling deleting function. Deleting all Autoscaling ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NukeAutoscaling:
"""Abstract autoscaling nuke in a class."""
def __init__(self, region_name=None) -> None:
"""Initialize autoscaling nuke."""
self.asg = AwsClient().connect('autoscaling', region_name)
try:
self.asg.describe_auto_scaling_groups()
except Endpoint... | the_stack_v2_python_sparse | package/nuke/compute/autoscaling.py | diodonfrost/terraform-aws-lambda-nuke | train | 20 |
3a7660e003988568899bd07222e53a87855df3d4 | [
"super().__init__()\nself.input_conv = nn.Conv1D(in_channels, hidden_channels, 1)\nself.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_channels=hidden_channels * 2, skip_c... | <|body_start_0|>
super().__init__()
self.input_conv = nn.Conv1D(in_channels, hidden_channels, 1)
self.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_ch... | Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://arxiv.org/abs/2006.04558 | PosteriorEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_75kplus_train_000720 | 4,766 | permissive | [
{
"docstring": "Initilialize PosteriorEncoder module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. hidden_channels (int): Number of hidden channels. kernel_size (int): Kernel size in WaveNet. layers (int): Number of layers of WaveNet. stacks (int): Number of ... | 2 | stack_v2_sparse_classes_30k_train_012173 | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://a... | the_stack_v2_python_sparse | paddlespeech/t2s/models/vits/posterior_encoder.py | anniyanvr/DeepSpeech-1 | train | 0 |
b38616a7947205da2eba9d5bba426e6c593c99b5 | [
"self.pool_size = pool_size\nif self.pool_size > 0:\n self.num_imgs = 0\n self.images = []",
"if self.pool_size == 0:\n return images\nreturn_images = []\nfor image in images:\n image = torch.unsqueeze(image.data, 0)\n if self.num_imgs < self.pool_size:\n self.num_imgs = self.num_imgs + 1\n ... | <|body_start_0|>
self.pool_size = pool_size
if self.pool_size > 0:
self.num_imgs = 0
self.images = []
<|end_body_0|>
<|body_start_1|>
if self.pool_size == 0:
return images
return_images = []
for image in images:
image = torch.unsqu... | This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. | ImagePool | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators."""
def __init__(self, pool_size):
"""Initialize the... | stack_v2_sparse_classes_75kplus_train_000721 | 2,226 | permissive | [
{
"docstring": "Initialize the ImagePool class Parameters: pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created",
"name": "__init__",
"signature": "def __init__(self, pool_size)"
},
{
"docstring": "Return an image from the pool. Parameters: images: the latest ge... | 2 | stack_v2_sparse_classes_30k_train_002002 | Implement the Python class `ImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.
Method signatures and do... | Implement the Python class `ImagePool` described below.
Class description:
This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.
Method signatures and do... | df4da9bdff11a2f948d5bd4ac83da7922e6f44f4 | <|skeleton|>
class ImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators."""
def __init__(self, pool_size):
"""Initialize the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagePool:
"""This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators."""
def __init__(self, pool_size):
"""Initialize the ImagePool cl... | the_stack_v2_python_sparse | torchbenchmark/models/pytorch_CycleGAN_and_pix2pix/util/image_pool.py | pytorch/benchmark | train | 685 |
1256d96f7e526597a2fa769a7cc25f395cc16cb0 | [
"self.vbname = vbname\nself.pyname = pyname\nself.vbargs = vbargs or []\nself.pyargs = pyargs or []",
"method.identifier = self.pyname % name\nmethod.parameters = [vb2py.vbparser.VBRenderDirect('*args')]\nmethod.scope = 'Public'\nif self.vbargs:\n mapping = '%s = vbGetEventArgs([%s], args)' % (', '.join(self.v... | <|body_start_0|>
self.vbname = vbname
self.pyname = pyname
self.vbargs = vbargs or []
self.pyargs = pyargs or []
<|end_body_0|>
<|body_start_1|>
method.identifier = self.pyname % name
method.parameters = [vb2py.vbparser.VBRenderDirect('*args')]
method.scope = 'Pu... | Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up in an event object. This class helps in the mapping of one to the other. | ControlEvent | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlEvent:
"""Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up in an event object. This class helps in... | stack_v2_sparse_classes_75kplus_train_000722 | 21,850 | permissive | [
{
"docstring": "Initialize the control event",
"name": "__init__",
"signature": "def __init__(self, vbname, pyname, vbargs=None, pyargs=None)"
},
{
"docstring": "Update the definition of a method based on this translation",
"name": "updateMethodDefinition",
"signature": "def updateMethod... | 2 | stack_v2_sparse_classes_30k_train_010653 | Implement the Python class `ControlEvent` described below.
Class description:
Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up ... | Implement the Python class `ControlEvent` described below.
Class description:
Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up ... | 847ce71e85093ea5ee668ec61dbfba760ffa6bbd | <|skeleton|>
class ControlEvent:
"""Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up in an event object. This class helps in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControlEvent:
"""Represents a control event mapping from VB to PythonCard A control event (eg MouseClick) is defined in VB with a certain name and list of parameters. PythonCard has an analogus event with a different name and all the parameters are bound up in an event object. This class helps in the mapping ... | the_stack_v2_python_sparse | vb2py/targets/pythoncard/controls.py | rayzamgh/sumurProjection | train | 1 |
83ebe8a9f22560f6b7fe79e0caff35ac781a445f | [
"dct = dict(dictionary)\nfor key in dictionary:\n if isinstance(dct[key], str):\n if dct[key].lower() == 'false':\n dct[key] = False\n elif dct[key].lower() == 'true':\n dct[key] = True\nreturn dct",
"dct = dict(dictionary)\nfor key in dictionary:\n if dct[key] == value:\... | <|body_start_0|>
dct = dict(dictionary)
for key in dictionary:
if isinstance(dct[key], str):
if dct[key].lower() == 'false':
dct[key] = False
elif dct[key].lower() == 'true':
dct[key] = True
return dct
<|end_body... | Contains methods for pruning keys and changing values of a boolean based dictionary | Params | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Params:
"""Contains methods for pruning keys and changing values of a boolean based dictionary"""
def _values_to_bools(dictionary):
"""Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g., "False" -> False or "false" -> False Args: dictionary (d... | stack_v2_sparse_classes_75kplus_train_000723 | 9,465 | permissive | [
{
"docstring": "Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g., \"False\" -> False or \"false\" -> False Args: dictionary (dict): Dictionary with values of string booleans. Returns: Altered copy of the dictionary with boolean values instead of string boolean values."... | 3 | stack_v2_sparse_classes_30k_train_026341 | Implement the Python class `Params` described below.
Class description:
Contains methods for pruning keys and changing values of a boolean based dictionary
Method signatures and docstrings:
- def _values_to_bools(dictionary): Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g.,... | Implement the Python class `Params` described below.
Class description:
Contains methods for pruning keys and changing values of a boolean based dictionary
Method signatures and docstrings:
- def _values_to_bools(dictionary): Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g.,... | 8581055553ba1f8094f64d96222f4e87c6c981b1 | <|skeleton|>
class Params:
"""Contains methods for pruning keys and changing values of a boolean based dictionary"""
def _values_to_bools(dictionary):
"""Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g., "False" -> False or "false" -> False Args: dictionary (d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Params:
"""Contains methods for pruning keys and changing values of a boolean based dictionary"""
def _values_to_bools(dictionary):
"""Converts values, one level deep in a dictionary, that are string booleans to booleans, e.g., "False" -> False or "false" -> False Args: dictionary (dict): Diction... | the_stack_v2_python_sparse | blade_runner/jamf_pro/params.py | univ-of-utah-marriott-library-apple/blade_runner | train | 27 |
97a5b26cca65adfb68b490538ea07b4e39e1cbd2 | [
"middle = len(nums) // 2\nif middle == 0:\n return nums[0]\nreturn min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))",
"if len(nums) == 2:\n return min(nums)\nmiddle = len(nums) // 2\nif middle == 0:\n return nums[0]\nif nums[middle] < nums[-1]:\n print('a', middle)\n return self.findMi... | <|body_start_0|>
middle = len(nums) // 2
if middle == 0:
return nums[0]
return min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))
<|end_body_0|>
<|body_start_1|>
if len(nums) == 2:
return min(nums)
middle = len(nums) // 2
if middle == 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_000724 | 1,068 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin3",
"signature": "def findMin3(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_018666 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin3(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype:... | 2711bc08f15266bec4ca135e8e3e629df46713eb | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin3(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
middle = len(nums) // 2
if middle == 0:
return nums[0]
return min(self.findMin(nums[:middle]), self.findMin(nums[middle:]))
def findMin3(self, nums):
""":type nums: List[int] :rt... | the_stack_v2_python_sparse | 0.算法/153_FindMinRotatedSortedArr.py | unlimitediw/CheckCode | train | 0 | |
7d284d419762d29019091319b619bc68450fe829 | [
"data = self.get_json()\ngroup_ids = data.get('groupIds')\nif group_ids is None:\n return self.error('Missing required parameter: `groupIds`')\ntry:\n group_ids = [int(gid) for gid in data['groupIds']]\nexcept ValueError:\n return self.error('Invalid value provided for `groupIDs`; unable to parse all list ... | <|body_start_0|>
data = self.get_json()
group_ids = data.get('groupIds')
if group_ids is None:
return self.error('Missing required parameter: `groupIds`')
try:
group_ids = [int(gid) for gid in data['groupIds']]
except ValueError:
return self.er... | SourceLabelsHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content:... | stack_v2_sparse_classes_75kplus_train_000725 | 4,944 | permissive | [
{
"docstring": "--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content: application/json: schema: type: object properties: grou... | 2 | stack_v2_sparse_classes_30k_train_001811 | Implement the Python class `SourceLabelsHandler` described below.
Class description:
Implement the SourceLabelsHandler class.
Method signatures and docstrings:
- def post(self, obj_id): --- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: ... | Implement the Python class `SourceLabelsHandler` described below.
Class description:
Implement the SourceLabelsHandler class.
Method signatures and docstrings:
- def post(self, obj_id): --- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SourceLabelsHandler:
def post(self, obj_id):
"""--- description: Note that a source has been labelled. tags: - sources - source_scans parameters: - in: path name: obj_id required: true schema: type: string description: | ID of object to indicate source labelling for requestBody: content: application/j... | the_stack_v2_python_sparse | skyportal/handlers/api/source_labels.py | skyportal/skyportal | train | 80 | |
c758f6b2e4694afbb60c747d8d832ae1fe9f8851 | [
"container = ExcelLayoutSheetParsingContainer._init_tag_definition_container(self, predicate)\nresult = container\nif not container is None:\n conv_predicate = self._convert_keyword(predicate)\n for alias in self._parser.molecule_design_id_predicates:\n md_alias = self._convert_keyword(alias)\n ... | <|body_start_0|>
container = ExcelLayoutSheetParsingContainer._init_tag_definition_container(self, predicate)
result = container
if not container is None:
conv_predicate = self._convert_keyword(predicate)
for alias in self._parser.molecule_design_id_predicates:
... | Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position). | ExcelMoleculeDesignPoolLayoutParsingContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelMoleculeDesignPoolLayoutParsingContainer:
"""Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position)."""
def _init_tag_definition_container(self, predicate):
"""We ... | stack_v2_sparse_classes_75kplus_train_000726 | 49,405 | permissive | [
{
"docstring": "We also need to check whether the predicate is a molecule design pool alias.",
"name": "_init_tag_definition_container",
"signature": "def _init_tag_definition_container(self, predicate)"
},
{
"docstring": "In case of floating molecule design pools we might have to replace the ta... | 3 | stack_v2_sparse_classes_30k_train_028267 | Implement the Python class `ExcelMoleculeDesignPoolLayoutParsingContainer` described below.
Class description:
Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position).
Method signatures and docstrings:
-... | Implement the Python class `ExcelMoleculeDesignPoolLayoutParsingContainer` described below.
Class description:
Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position).
Method signatures and docstrings:
-... | d2dc7a478ee5d24ccf3cc680888e712d482321d0 | <|skeleton|>
class ExcelMoleculeDesignPoolLayoutParsingContainer:
"""Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position)."""
def _init_tag_definition_container(self, predicate):
"""We ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExcelMoleculeDesignPoolLayoutParsingContainer:
"""Excel layout sheet parsing container for sheets that might contain molecule design pool layouts (floating positions must be replaced by markers depending on the position)."""
def _init_tag_definition_container(self, predicate):
"""We also need to ... | the_stack_v2_python_sparse | thelma/tools/parsers/base.py | papagr/TheLMA | train | 1 |
5244047ecb4e94bbf9e247bbc26a2a9858b1ff56 | [
"lock_key = STAB_LOCK_KEY.format(ctx.author, target)\nwith await self.redis as conn:\n if await conn.exists(lock_key):\n return await ctx.send(f'too soon, try stabbing {target.name} later!')\n await conn.set(lock_key, 'haha yes', expire=STAB_DURATION)\n await conn.incr(STAB_KEY.format(target))\n ... | <|body_start_0|>
lock_key = STAB_LOCK_KEY.format(ctx.author, target)
with await self.redis as conn:
if await conn.exists(lock_key):
return await ctx.send(f'too soon, try stabbing {target.name} later!')
await conn.set(lock_key, 'haha yes', expire=STAB_DURATION)
... | Fun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fun:
async def stab(self, ctx: Context, *, target: User):
"""stab someone"""
<|body_0|>
async def stab_stats(self, ctx: Context, *, target: User):
"""show how many times someone got stabbed"""
<|body_1|>
async def pick(self, ctx: Context, *things: clean_... | stack_v2_sparse_classes_75kplus_train_000727 | 4,233 | no_license | [
{
"docstring": "stab someone",
"name": "stab",
"signature": "async def stab(self, ctx: Context, *, target: User)"
},
{
"docstring": "show how many times someone got stabbed",
"name": "stab_stats",
"signature": "async def stab_stats(self, ctx: Context, *, target: User)"
},
{
"docs... | 6 | stack_v2_sparse_classes_30k_train_015272 | Implement the Python class `Fun` described below.
Class description:
Implement the Fun class.
Method signatures and docstrings:
- async def stab(self, ctx: Context, *, target: User): stab someone
- async def stab_stats(self, ctx: Context, *, target: User): show how many times someone got stabbed
- async def pick(self... | Implement the Python class `Fun` described below.
Class description:
Implement the Fun class.
Method signatures and docstrings:
- async def stab(self, ctx: Context, *, target: User): stab someone
- async def stab_stats(self, ctx: Context, *, target: User): show how many times someone got stabbed
- async def pick(self... | 8d4ba0ca1d39248fa2c555e16ee0cb3f42cf0117 | <|skeleton|>
class Fun:
async def stab(self, ctx: Context, *, target: User):
"""stab someone"""
<|body_0|>
async def stab_stats(self, ctx: Context, *, target: User):
"""show how many times someone got stabbed"""
<|body_1|>
async def pick(self, ctx: Context, *things: clean_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fun:
async def stab(self, ctx: Context, *, target: User):
"""stab someone"""
lock_key = STAB_LOCK_KEY.format(ctx.author, target)
with await self.redis as conn:
if await conn.exists(lock_key):
return await ctx.send(f'too soon, try stabbing {target.name} later... | the_stack_v2_python_sparse | kmn/cogs/fun.py | slice/kmn | train | 1 | |
3019803152bc7807f566570960c2ce0e37966fce | [
"if sens_type not in self._sens_types:\n raise ValueError('illegal sensitivity type: \"{}\"'.format(sens_type))\nif isinstance(sig, HDLModulePort):\n sig = sig.signal\nelif sig is None and sens_type != 'any':\n raise ValueError('signal cannot be None')\nif not isinstance(sig, (HDLSignal, HDLSignalSlice, ty... | <|body_start_0|>
if sens_type not in self._sens_types:
raise ValueError('illegal sensitivity type: "{}"'.format(sens_type))
if isinstance(sig, HDLModulePort):
sig = sig.signal
elif sig is None and sens_type != 'any':
raise ValueError('signal cannot be None')
... | Signal sensitivity descriptor. | HDLSensitivityDescriptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDLSensitivityDescriptor:
"""Signal sensitivity descriptor."""
def __init__(self, sens_type, sig=None):
"""Initialize."""
<|body_0|>
def dumps(self):
"""Get representation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if sens_type not in self... | stack_v2_sparse_classes_75kplus_train_000728 | 2,166 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, sens_type, sig=None)"
},
{
"docstring": "Get representation.",
"name": "dumps",
"signature": "def dumps(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041773 | Implement the Python class `HDLSensitivityDescriptor` described below.
Class description:
Signal sensitivity descriptor.
Method signatures and docstrings:
- def __init__(self, sens_type, sig=None): Initialize.
- def dumps(self): Get representation. | Implement the Python class `HDLSensitivityDescriptor` described below.
Class description:
Signal sensitivity descriptor.
Method signatures and docstrings:
- def __init__(self, sens_type, sig=None): Initialize.
- def dumps(self): Get representation.
<|skeleton|>
class HDLSensitivityDescriptor:
"""Signal sensitivi... | 463412cf6a72456acc8cb99569e7dc9c9d472f6d | <|skeleton|>
class HDLSensitivityDescriptor:
"""Signal sensitivity descriptor."""
def __init__(self, sens_type, sig=None):
"""Initialize."""
<|body_0|>
def dumps(self):
"""Get representation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HDLSensitivityDescriptor:
"""Signal sensitivity descriptor."""
def __init__(self, sens_type, sig=None):
"""Initialize."""
if sens_type not in self._sens_types:
raise ValueError('illegal sensitivity type: "{}"'.format(sens_type))
if isinstance(sig, HDLModulePort):
... | the_stack_v2_python_sparse | hdltools/abshdl/sens.py | brunosmmm/hdltools | train | 2 |
707d820f37aff3f092868c741833758b5b273441 | [
"self.fc1 = nn.Linear(self.observation_space.shape[0], 256)\nself.fc2 = nn.Linear(256, 256)\nself.fc3 = nn.Linear(256, 256)\nself.vf = nn.Linear(256, 1)",
"x = x.float()\nx = F.relu(self.fc1(x))\nx = F.relu(self.fc2(x))\nx = F.relu(self.fc3(x))\nreturn self.vf(x)"
] | <|body_start_0|>
self.fc1 = nn.Linear(self.observation_space.shape[0], 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 256)
self.vf = nn.Linear(256, 1)
<|end_body_0|>
<|body_start_1|>
x = x.float()
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
... | Value Function. | VFNet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VFNet:
"""Value Function."""
def build(self):
"""Build."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.fc1 = nn.Linear(self.observation_space.shape[0], 256)
self.fc2 = nn.Linear(256, ... | stack_v2_sparse_classes_75kplus_train_000729 | 18,517 | permissive | [
{
"docstring": "Build.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014712 | Implement the Python class `VFNet` described below.
Class description:
Value Function.
Method signatures and docstrings:
- def build(self): Build.
- def forward(self, x): Forward. | Implement the Python class `VFNet` described below.
Class description:
Value Function.
Method signatures and docstrings:
- def build(self): Build.
- def forward(self, x): Forward.
<|skeleton|>
class VFNet:
"""Value Function."""
def build(self):
"""Build."""
<|body_0|>
def forward(self, ... | f53cf3191f4c38f4d1f394ccd55b1d935a6a70ba | <|skeleton|>
class VFNet:
"""Value Function."""
def build(self):
"""Build."""
<|body_0|>
def forward(self, x):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VFNet:
"""Value Function."""
def build(self):
"""Build."""
self.fc1 = nn.Linear(self.observation_space.shape[0], 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 256)
self.vf = nn.Linear(256, 1)
def forward(self, x):
"""Forward."""
... | the_stack_v2_python_sparse | python/rrc_example_package/code/residual_ppo.py | takuma-yoneda/rrc_example_package | train | 0 |
eeb04f19d397c7cebd869c09d40e1bd0b0abf144 | [
"self.stream = stream\nself.encoding = encoding or 'UTF-8'\nself._logger = logger",
"try:\n self.stream.close()\nexcept Exception as e:\n if self._logger is not None:\n self._logger.exception(f'Exception raised when writer stream closed: {e}')",
"json_content = json.dumps(message.dictionary, sort_k... | <|body_start_0|>
self.stream = stream
self.encoding = encoding or 'UTF-8'
self._logger = logger
<|end_body_0|>
<|body_start_1|>
try:
self.stream.close()
except Exception as e:
if self._logger is not None:
self._logger.exception(f'Exception... | Write JSON RPC messages to a stream | JSONRPCWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONRPCWriter:
"""Write JSON RPC messages to a stream"""
def __init__(self, stream, encoding=None, logger=None):
"""Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional encoding choice for messages. Defaults to UTF-8 :param log... | stack_v2_sparse_classes_75kplus_train_000730 | 2,136 | permissive | [
{
"docstring": "Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional encoding choice for messages. Defaults to UTF-8 :param logger: Optional destination for logging",
"name": "__init__",
"signature": "def __init__(self, stream, encoding=None, logg... | 3 | stack_v2_sparse_classes_30k_train_021452 | Implement the Python class `JSONRPCWriter` described below.
Class description:
Write JSON RPC messages to a stream
Method signatures and docstrings:
- def __init__(self, stream, encoding=None, logger=None): Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional e... | Implement the Python class `JSONRPCWriter` described below.
Class description:
Write JSON RPC messages to a stream
Method signatures and docstrings:
- def __init__(self, stream, encoding=None, logger=None): Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional e... | 24a048226f7f30c775bbcbab462d499a465be5da | <|skeleton|>
class JSONRPCWriter:
"""Write JSON RPC messages to a stream"""
def __init__(self, stream, encoding=None, logger=None):
"""Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional encoding choice for messages. Defaults to UTF-8 :param log... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONRPCWriter:
"""Write JSON RPC messages to a stream"""
def __init__(self, stream, encoding=None, logger=None):
"""Initializes the JSON RPC writer :param stream: Stream that messages will be sent on :param encoding: Optional encoding choice for messages. Defaults to UTF-8 :param logger: Optional... | the_stack_v2_python_sparse | ossdbtoolsservice/hosting/json_writer.py | microsoft/pgtoolsservice | train | 68 |
e92bb6fc75bbe45792922b629872827ad1d4881a | [
"self.length = length\nself.diameter = diameter\nself.mass = mass\nself.deck_space = deck_space",
"key = 'mono_fasten_time'\ntime = kwargs.get(key, pt[key])\nreturn ('Fasten Monopile', time)",
"key = 'mono_release_time'\ntime = kwargs.get(key, pt[key])\nreturn ('Release Monopile', time)"
] | <|body_start_0|>
self.length = length
self.diameter = diameter
self.mass = mass
self.deck_space = deck_space
<|end_body_0|>
<|body_start_1|>
key = 'mono_fasten_time'
time = kwargs.get(key, pt[key])
return ('Fasten Monopile', time)
<|end_body_1|>
<|body_start_2|>... | Monopile Cargo | Monopile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monopile:
"""Monopile Cargo"""
def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `Monopile`."""
<|body_0|>
def fasten(**kwargs):
"""Returns time required to fasten a monopile at port."""
<|body... | stack_v2_sparse_classes_75kplus_train_000731 | 8,555 | permissive | [
{
"docstring": "Creates an instance of `Monopile`.",
"name": "__init__",
"signature": "def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs)"
},
{
"docstring": "Returns time required to fasten a monopile at port.",
"name": "fasten",
"signature": "def fasten... | 3 | null | Implement the Python class `Monopile` described below.
Class description:
Monopile Cargo
Method signatures and docstrings:
- def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs): Creates an instance of `Monopile`.
- def fasten(**kwargs): Returns time required to fasten a monopile at po... | Implement the Python class `Monopile` described below.
Class description:
Monopile Cargo
Method signatures and docstrings:
- def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs): Creates an instance of `Monopile`.
- def fasten(**kwargs): Returns time required to fasten a monopile at po... | d7270ebe1c554293a9d36730d67ab555c071cb17 | <|skeleton|>
class Monopile:
"""Monopile Cargo"""
def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `Monopile`."""
<|body_0|>
def fasten(**kwargs):
"""Returns time required to fasten a monopile at port."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Monopile:
"""Monopile Cargo"""
def __init__(self, length=None, diameter=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `Monopile`."""
self.length = length
self.diameter = diameter
self.mass = mass
self.deck_space = deck_space
def fasten... | the_stack_v2_python_sparse | wisdem/orbit/phases/install/monopile_install/common.py | WISDEM/WISDEM | train | 120 |
909d6e7e9ad569c8f9d1a7d6c07fe07d0836695d | [
"super().__init__()\nself.root = root\nfiles = glob.glob(os.path.join(root, '**.csv'))\nif not files:\n raise FileNotFoundError(f'Dataset not found in `root={self.root}`')\ntry:\n import pandas as pd\nexcept ImportError:\n raise ImportError('pandas is not installed and is required to use this dataset')\nda... | <|body_start_0|>
super().__init__()
self.root = root
files = glob.glob(os.path.join(root, '**.csv'))
if not files:
raise FileNotFoundError(f'Dataset not found in `root={self.root}`')
try:
import pandas as pd
except ImportError:
raise Im... | Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can be downloaded by scientists and researchers. If you use an iNaturalist datase... | INaturalist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INaturalist:
"""Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can be downloaded by scientists and resear... | stack_v2_sparse_classes_75kplus_train_000732 | 3,857 | permissive | [
{
"docstring": "Initialize a new Dataset instance. Args: root: root directory where dataset can be found Raises: FileNotFoundError: if no files are found in ``root`` ImportError: if pandas is not installed",
"name": "__init__",
"signature": "def __init__(self, root: str='data') -> None"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_042948 | Implement the Python class `INaturalist` described below.
Class description:
Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can... | Implement the Python class `INaturalist` described below.
Class description:
Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class INaturalist:
"""Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can be downloaded by scientists and resear... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INaturalist:
"""Dataset for iNaturalist. `iNaturalist <https://www.inaturalist.org/>`__ is a joint initiative of the California Academy of Sciences and the National Geographic Society. It allows citizen scientists to upload observations of organisms that can be downloaded by scientists and researchers. If you... | the_stack_v2_python_sparse | torchgeo/datasets/inaturalist.py | microsoft/torchgeo | train | 1,724 |
976aa770ac9f0c536f90d9c75624ed001447dfc8 | [
"super(AttributeProperty, self).__init__()\nself.instance = instance\nself.attribute = attribute",
"if not hasattr(self.instance, self.attribute):\n raise Exception('Attribute or instance has not been set')\nreturn getattr(self.instance, self.attribute)",
"if not hasattr(self.instance, self.attribute):\n ... | <|body_start_0|>
super(AttributeProperty, self).__init__()
self.instance = instance
self.attribute = attribute
<|end_body_0|>
<|body_start_1|>
if not hasattr(self.instance, self.attribute):
raise Exception('Attribute or instance has not been set')
return getattr(self... | Provides a property that sets and gets attributes from a python object. | AttributeProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
<|body_0|>
def get(self):
"""Returns the value of the attribute specified by self.attribute onto ... | stack_v2_sparse_classes_75kplus_train_000733 | 1,578 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, instance=None, attribute=None)"
},
{
"docstring": "Returns the value of the attribute specified by self.attribute onto self.instance. For example, if self.attribute is \"test\" and self.instance is myobj, this wil... | 3 | stack_v2_sparse_classes_30k_train_033975 | Implement the Python class `AttributeProperty` described below.
Class description:
Provides a property that sets and gets attributes from a python object.
Method signatures and docstrings:
- def __init__(self, instance=None, attribute=None): Constructor
- def get(self): Returns the value of the attribute specified by... | Implement the Python class `AttributeProperty` described below.
Class description:
Provides a property that sets and gets attributes from a python object.
Method signatures and docstrings:
- def __init__(self, instance=None, attribute=None): Constructor
- def get(self): Returns the value of the attribute specified by... | 31773128238830d3d335c1915877dc0db56836cd | <|skeleton|>
class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
<|body_0|>
def get(self):
"""Returns the value of the attribute specified by self.attribute onto ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
super(AttributeProperty, self).__init__()
self.instance = instance
self.attribute = attribute
def get(... | the_stack_v2_python_sparse | fp_py/src/main/fruitpunch/attribute_property.py | leolimasa/fruitpunch | train | 0 |
a7a0e54a1bf8a0e5b3f369ffedbbd455d4f42209 | [
"if fmt is None:\n fmt = self.DEFAULT_FORMAT\nif datefmt is None:\n datefmt = self.DEFAULT_DATE_FORMAT\nif colors is None:\n colors = self.DEFAULT_COLORS\nlogging.Formatter.__init__(self, datefmt=datefmt)\nself._fmt = fmt\nself._colors = {}\nself._normal = ''\nif color and check_color_support():\n self.... | <|body_start_0|>
if fmt is None:
fmt = self.DEFAULT_FORMAT
if datefmt is None:
datefmt = self.DEFAULT_DATE_FORMAT
if colors is None:
colors = self.DEFAULT_COLORS
logging.Formatter.__init__(self, datefmt=datefmt)
self._fmt = fmt
self._co... | Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems. | BaseFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_75kplus_train_000734 | 5,254 | permissive | [
{
"docstring": "Parameters ---------- color: Enable color support. bool, default: True fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. str, default: None datefmt... | 2 | stack_v2_sparse_classes_30k_train_023259 | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=None, colors=... | the_stack_v2_python_sparse | mridc/utils/formaters/base.py | wdika/mridc | train | 40 |
03f6d379ddad6def7ccbcff54613265eb831c5df | [
"try:\n cur.execute('SELECT * FROM tbl_parties where id = %s' % party)\n row = cur.fetchall()\n size = len(row)\n if not size > 0:\n return make_response(jsonify({'status': 404, 'message': 'invalid party'}), 404)\n cur.execute('SELECT * FROM tbl_offices where id = %s' % office)\n row = cu... | <|body_start_0|>
try:
cur.execute('SELECT * FROM tbl_parties where id = %s' % party)
row = cur.fetchall()
size = len(row)
if not size > 0:
return make_response(jsonify({'status': 404, 'message': 'invalid party'}), 404)
cur.execute('SEL... | Candidate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Candidate:
def add_candidate(self, party, office, candidate):
"""This method saves candidates data"""
<|body_0|>
def getall_candidates(self):
"""querying the database to get all candidates"""
<|body_1|>
def get_specific_candidate(self, candidate_id):
... | stack_v2_sparse_classes_75kplus_train_000735 | 4,159 | permissive | [
{
"docstring": "This method saves candidates data",
"name": "add_candidate",
"signature": "def add_candidate(self, party, office, candidate)"
},
{
"docstring": "querying the database to get all candidates",
"name": "getall_candidates",
"signature": "def getall_candidates(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_011264 | Implement the Python class `Candidate` described below.
Class description:
Implement the Candidate class.
Method signatures and docstrings:
- def add_candidate(self, party, office, candidate): This method saves candidates data
- def getall_candidates(self): querying the database to get all candidates
- def get_specif... | Implement the Python class `Candidate` described below.
Class description:
Implement the Candidate class.
Method signatures and docstrings:
- def add_candidate(self, party, office, candidate): This method saves candidates data
- def getall_candidates(self): querying the database to get all candidates
- def get_specif... | e2b8f4c3f027520ae6294bc1df24599ebe23f86d | <|skeleton|>
class Candidate:
def add_candidate(self, party, office, candidate):
"""This method saves candidates data"""
<|body_0|>
def getall_candidates(self):
"""querying the database to get all candidates"""
<|body_1|>
def get_specific_candidate(self, candidate_id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Candidate:
def add_candidate(self, party, office, candidate):
"""This method saves candidates data"""
try:
cur.execute('SELECT * FROM tbl_parties where id = %s' % party)
row = cur.fetchall()
size = len(row)
if not size > 0:
retur... | the_stack_v2_python_sparse | app/api/v2/candidates/C_Model.py | kiariepeter/politicov1 | train | 1 | |
b6aa73e7a5fd0259e5719a364a4a913122f6d1ac | [
"if 'surname' in request.params:\n redirect(url('now_name', surname=request.params['surname']))\nelse:\n return render('now/index.xml')",
"schedule = [time(7, 55), time(8, 55), time(10, 0), time(10, 55), time(12, 0), time(12, 55), time(13, 50), time(14, 45)]\nnow = datetime.now().time()\nif now < schedule[0... | <|body_start_0|>
if 'surname' in request.params:
redirect(url('now_name', surname=request.params['surname']))
else:
return render('now/index.xml')
<|end_body_0|>
<|body_start_1|>
schedule = [time(7, 55), time(8, 55), time(10, 0), time(10, 55), time(12, 0), time(12, 55), ... | NowController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
<|body_0|>
def current_order(self):
"""Return the current lesson order."""
<|body_1|>
def now(self, surname):
... | stack_v2_sparse_classes_75kplus_train_000736 | 2,786 | no_license | [
{
"docstring": "Render index page or redirect to now or now_id actions if surname is available in the request's params.",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Return the current lesson order.",
"name": "current_order",
"signature": "def current_order(self)"
... | 4 | stack_v2_sparse_classes_30k_train_022916 | Implement the Python class `NowController` described below.
Class description:
Implement the NowController class.
Method signatures and docstrings:
- def index(self): Render index page or redirect to now or now_id actions if surname is available in the request's params.
- def current_order(self): Return the current l... | Implement the Python class `NowController` described below.
Class description:
Implement the NowController class.
Method signatures and docstrings:
- def index(self): Render index page or redirect to now or now_id actions if surname is available in the request's params.
- def current_order(self): Return the current l... | 327ef2fd4f65db471c408a26095439630c53139e | <|skeleton|>
class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
<|body_0|>
def current_order(self):
"""Return the current lesson order."""
<|body_1|>
def now(self, surname):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
if 'surname' in request.params:
redirect(url('now_name', surname=request.params['surname']))
else:
return render('now/in... | the_stack_v2_python_sparse | sis/controllers/now.py | kuba/SIS | train | 0 | |
c74f6c401a6da9db0cd466ef12560afa0f1631a5 | [
"if self.model.cfg.get('demo_pipeline', None):\n test_pipeline = self.model.cfg.demo_pipeline\nelif self.model.cfg.get('test_pipeline', None):\n test_pipeline = self.model.cfg.test_pipeline\nelse:\n test_pipeline = self.model.cfg.val_pipeline\nfile_extension = osp.splitext(video)[1]\nif file_extension in V... | <|body_start_0|>
if self.model.cfg.get('demo_pipeline', None):
test_pipeline = self.model.cfg.demo_pipeline
elif self.model.cfg.get('test_pipeline', None):
test_pipeline = self.model.cfg.test_pipeline
else:
test_pipeline = self.model.cfg.val_pipeline
f... | inferencer that predicts with video restoration models. | VideoRestorationInferencer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoRestorationInferencer:
"""inferencer that predicts with video restoration models."""
def preprocess(self, video: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: video(InputsType): Video to be restored by models. Returns: results(InputsType): Result... | stack_v2_sparse_classes_75kplus_train_000737 | 7,539 | permissive | [
{
"docstring": "Process the inputs into a model-feedable format. Args: video(InputsType): Video to be restored by models. Returns: results(InputsType): Results of preprocess.",
"name": "preprocess",
"signature": "def preprocess(self, video: InputsType) -> Dict"
},
{
"docstring": "Forward the inp... | 4 | null | Implement the Python class `VideoRestorationInferencer` described below.
Class description:
inferencer that predicts with video restoration models.
Method signatures and docstrings:
- def preprocess(self, video: InputsType) -> Dict: Process the inputs into a model-feedable format. Args: video(InputsType): Video to be... | Implement the Python class `VideoRestorationInferencer` described below.
Class description:
inferencer that predicts with video restoration models.
Method signatures and docstrings:
- def preprocess(self, video: InputsType) -> Dict: Process the inputs into a model-feedable format. Args: video(InputsType): Video to be... | a382f143c0fd20d227e1e5524831ba26a568190d | <|skeleton|>
class VideoRestorationInferencer:
"""inferencer that predicts with video restoration models."""
def preprocess(self, video: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: video(InputsType): Video to be restored by models. Returns: results(InputsType): Result... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoRestorationInferencer:
"""inferencer that predicts with video restoration models."""
def preprocess(self, video: InputsType) -> Dict:
"""Process the inputs into a model-feedable format. Args: video(InputsType): Video to be restored by models. Returns: results(InputsType): Results of preproce... | the_stack_v2_python_sparse | mmagic/apis/inferencers/video_restoration_inferencer.py | open-mmlab/mmagic | train | 1,370 |
56ef9c3dc71951a7aacce7117f10b88c0eb5c452 | [
"query_params = defaultdict(dict)\nquery_params['path_type'] = path_type.value\nif band_gap:\n query_params.update({'band_gap_min': band_gap[0], 'band_gap_max': band_gap[1]})\nif efermi:\n query_params.update({'efermi_min': efermi[0], 'efermi_max': efermi[1]})\nif magnetic_ordering:\n query_params.update({... | <|body_start_0|>
query_params = defaultdict(dict)
query_params['path_type'] = path_type.value
if band_gap:
query_params.update({'band_gap_min': band_gap[0], 'band_gap_max': band_gap[1]})
if efermi:
query_params.update({'efermi_min': efermi[0], 'efermi_max': efermi... | BandStructureRester | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-hdf5",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BandStructureRester:
def search_bandstructure_summary(self, path_type: BSPathType=BSPathType.setyawan_curtarolo, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_ordering: Optional[Ordering]=None, is_gap_direct: bool=None, is_metal: bool=None, so... | stack_v2_sparse_classes_75kplus_train_000738 | 14,062 | permissive | [
{
"docstring": "Query band structure summary data in electronic structure docs using a variety of search criteria. Arguments: path_type (BSPathType): k-path selection convention for the band structure. band_gap (Tuple[float,float]): Minimum and maximum band gap in eV to consider. efermi (Tuple[float,float]): Mi... | 3 | stack_v2_sparse_classes_30k_train_004676 | Implement the Python class `BandStructureRester` described below.
Class description:
Implement the BandStructureRester class.
Method signatures and docstrings:
- def search_bandstructure_summary(self, path_type: BSPathType=BSPathType.setyawan_curtarolo, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[T... | Implement the Python class `BandStructureRester` described below.
Class description:
Implement the BandStructureRester class.
Method signatures and docstrings:
- def search_bandstructure_summary(self, path_type: BSPathType=BSPathType.setyawan_curtarolo, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[T... | e2dc71934baecd1a85621f7f7f6ff85f96cbd684 | <|skeleton|>
class BandStructureRester:
def search_bandstructure_summary(self, path_type: BSPathType=BSPathType.setyawan_curtarolo, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_ordering: Optional[Ordering]=None, is_gap_direct: bool=None, is_metal: bool=None, so... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BandStructureRester:
def search_bandstructure_summary(self, path_type: BSPathType=BSPathType.setyawan_curtarolo, band_gap: Optional[Tuple[float, float]]=None, efermi: Optional[Tuple[float, float]]=None, magnetic_ordering: Optional[Ordering]=None, is_gap_direct: bool=None, is_metal: bool=None, sort_field: Opti... | the_stack_v2_python_sparse | src/mp_api/routes/electronic_structure/client.py | hhaoyan/api | train | 0 | |
0ace549fed70054fb9e78cb643cfd600e3a13237 | [
"handlers = [('/plot', PlotHandler, {'appRef': self})]\nsettings = {'xsrf_cookies': False, 'debug': True}\nself.plotters = []\nsuper(WebDisplayServer, self).__init__(handlers, **settings)",
"wsport = getFreePort()\nplotter = WebPlotter(dataReader, wsport, initParams)\nplotter.start()\nself.plotters.append((plotte... | <|body_start_0|>
handlers = [('/plot', PlotHandler, {'appRef': self})]
settings = {'xsrf_cookies': False, 'debug': True}
self.plotters = []
super(WebDisplayServer, self).__init__(handlers, **settings)
<|end_body_0|>
<|body_start_1|>
wsport = getFreePort()
plotter = WebPl... | WebDisplayServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebDisplayServer:
def __init__(self):
"""Initialize a web display server"""
<|body_0|>
def addPlotter(self, dataReader, initParams: dict):
"""Add another plotter to the server The web display server will create a free port used for interaction between the front end c... | stack_v2_sparse_classes_75kplus_train_000739 | 5,833 | no_license | [
{
"docstring": "Initialize a web display server",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add another plotter to the server The web display server will create a free port used for interaction between the front end client and the web plotter. The web plotter will ... | 2 | stack_v2_sparse_classes_30k_train_005274 | Implement the Python class `WebDisplayServer` described below.
Class description:
Implement the WebDisplayServer class.
Method signatures and docstrings:
- def __init__(self): Initialize a web display server
- def addPlotter(self, dataReader, initParams: dict): Add another plotter to the server The web display server... | Implement the Python class `WebDisplayServer` described below.
Class description:
Implement the WebDisplayServer class.
Method signatures and docstrings:
- def __init__(self): Initialize a web display server
- def addPlotter(self, dataReader, initParams: dict): Add another plotter to the server The web display server... | 52d1f867e72c0ac37a309b087824a8d878168374 | <|skeleton|>
class WebDisplayServer:
def __init__(self):
"""Initialize a web display server"""
<|body_0|>
def addPlotter(self, dataReader, initParams: dict):
"""Add another plotter to the server The web display server will create a free port used for interaction between the front end c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebDisplayServer:
def __init__(self):
"""Initialize a web display server"""
handlers = [('/plot', PlotHandler, {'appRef': self})]
settings = {'xsrf_cookies': False, 'debug': True}
self.plotters = []
super(WebDisplayServer, self).__init__(handlers, **settings)
def a... | the_stack_v2_python_sparse | displayserver.py | xttjsn/tradingshell | train | 1 | |
9f2e7ca86aa7d2d9b27d9909e3c33eb5bcacffa9 | [
"self.launcher = ROSLaunch()\nself.launcher.start()\nself.namespace = namespace\nself.pedestrian_id = int(pedestrian_id)\nself.crosswalk_id = int(crosswalk_id)\nself.class_name = self.__class__.__name__\nself.simulation_rate = simulation_rate\nself.simulate = False\nself.x = x\nself.y = y\nself.yaw = yaw\nself.np_t... | <|body_start_0|>
self.launcher = ROSLaunch()
self.launcher.start()
self.namespace = namespace
self.pedestrian_id = int(pedestrian_id)
self.crosswalk_id = int(crosswalk_id)
self.class_name = self.__class__.__name__
self.simulation_rate = simulation_rate
sel... | Base class for pedestrians. | Pedestrian | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pedestrian:
"""Base class for pedestrians."""
def __init__(self, namespace, pedestrian_id, simulation_rate, crosswalk_id, x=0.0, y=0.0, yaw=0.0):
"""Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which the pedestrian node is started. @param pedestrian_id: I{(... | stack_v2_sparse_classes_75kplus_train_000740 | 6,610 | no_license | [
{
"docstring": "Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which the pedestrian node is started. @param pedestrian_id: I{(int)} ID of the pedestrian that is created. @param simulation_rate: I{(int)} Rate at which the pedestrian is simulated (hz). @param crosswalk_id: I{(int)} ID of ... | 5 | stack_v2_sparse_classes_30k_train_039547 | Implement the Python class `Pedestrian` described below.
Class description:
Base class for pedestrians.
Method signatures and docstrings:
- def __init__(self, namespace, pedestrian_id, simulation_rate, crosswalk_id, x=0.0, y=0.0, yaw=0.0): Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which ... | Implement the Python class `Pedestrian` described below.
Class description:
Base class for pedestrians.
Method signatures and docstrings:
- def __init__(self, namespace, pedestrian_id, simulation_rate, crosswalk_id, x=0.0, y=0.0, yaw=0.0): Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which ... | d34f47d55df7b728c78d870e2f6f2b2d842bdee9 | <|skeleton|>
class Pedestrian:
"""Base class for pedestrians."""
def __init__(self, namespace, pedestrian_id, simulation_rate, crosswalk_id, x=0.0, y=0.0, yaw=0.0):
"""Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which the pedestrian node is started. @param pedestrian_id: I{(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pedestrian:
"""Base class for pedestrians."""
def __init__(self, namespace, pedestrian_id, simulation_rate, crosswalk_id, x=0.0, y=0.0, yaw=0.0):
"""Initialize class Pedestrian. @param namespace: I{(string)} Namespace in which the pedestrian node is started. @param pedestrian_id: I{(int)} ID of t... | the_stack_v2_python_sparse | sml_world/scripts/sml_modules/pedestrian_model.py | xiao3913/UGV_demo_new | train | 0 |
76f68093fbb8927100b7ad2af0d984fc4c166a9e | [
"if self.codeable_concept:\n return 'Performer {0.reference_txt} {0.codeable_concept}'.format(self)\nreturn 'Performer {0.reference_txt}'.format(self)",
"if self.codeable_concept:\n return {'actor': self.reference_txt, 'role': self.codeable_concept.as_fhir()}\nreturn self.reference_txt",
"instance = cls()... | <|body_start_0|>
if self.codeable_concept:
return 'Performer {0.reference_txt} {0.codeable_concept}'.format(self)
return 'Performer {0.reference_txt}'.format(self)
<|end_body_0|>
<|body_start_1|>
if self.codeable_concept:
return {'actor': self.reference_txt, 'role': self... | ORM for FHIR Performer - performers table | Performer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Performer:
"""ORM for FHIR Performer - performers table"""
def __str__(self):
"""Print friendly format for logging, etc."""
<|body_0|>
def as_fhir(self):
"""Return self in JSON FHIR formatted string FHIR is not currently consistant in performer inclusion. For exa... | stack_v2_sparse_classes_75kplus_train_000741 | 4,146 | permissive | [
{
"docstring": "Print friendly format for logging, etc.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Return self in JSON FHIR formatted string FHIR is not currently consistant in performer inclusion. For example, Observation.performer is simply a list of Reference res... | 4 | stack_v2_sparse_classes_30k_train_021831 | Implement the Python class `Performer` described below.
Class description:
ORM for FHIR Performer - performers table
Method signatures and docstrings:
- def __str__(self): Print friendly format for logging, etc.
- def as_fhir(self): Return self in JSON FHIR formatted string FHIR is not currently consistant in perform... | Implement the Python class `Performer` described below.
Class description:
ORM for FHIR Performer - performers table
Method signatures and docstrings:
- def __str__(self): Print friendly format for logging, etc.
- def as_fhir(self): Return self in JSON FHIR formatted string FHIR is not currently consistant in perform... | 622e90f54692c6fc9c84468f489ab6f297af0feb | <|skeleton|>
class Performer:
"""ORM for FHIR Performer - performers table"""
def __str__(self):
"""Print friendly format for logging, etc."""
<|body_0|>
def as_fhir(self):
"""Return self in JSON FHIR formatted string FHIR is not currently consistant in performer inclusion. For exa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Performer:
"""ORM for FHIR Performer - performers table"""
def __str__(self):
"""Print friendly format for logging, etc."""
if self.codeable_concept:
return 'Performer {0.reference_txt} {0.codeable_concept}'.format(self)
return 'Performer {0.reference_txt}'.format(self... | the_stack_v2_python_sparse | portal/models/performer.py | pep8speaks/true_nth_usa_portal | train | 1 |
340c76534c47e16cd71a32098d38074817be8fa7 | [
"if user_id is None or type(user_id) != str:\n return None\nelse:\n session_id = str(uuid.uuid4())\n self.user_id_by_session_id[session_id] = user_id\n return session_id",
"if session_id is None or type(session_id) != str:\n return None\nelse:\n x = self.user_id_by_session_id.get(session_id)\n ... | <|body_start_0|>
if user_id is None or type(user_id) != str:
return None
else:
session_id = str(uuid.uuid4())
self.user_id_by_session_id[session_id] = user_id
return session_id
<|end_body_0|>
<|body_start_1|>
if session_id is None or type(session_... | authentication mechanism | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""authentication mechanism"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""returns a User ID based on a Session ID"""
... | stack_v2_sparse_classes_75kplus_train_000742 | 1,182 | no_license | [
{
"docstring": "Creates a Session ID for a user_id",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "returns a User ID based on a Session ID",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, s... | 3 | stack_v2_sparse_classes_30k_train_004964 | Implement the Python class `SessionAuth` described below.
Class description:
authentication mechanism
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Creates a Session ID for a user_id
- def user_id_for_session_id(self, session_id: str=None) -> str: returns a User ID based on a... | Implement the Python class `SessionAuth` described below.
Class description:
authentication mechanism
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Creates a Session ID for a user_id
- def user_id_for_session_id(self, session_id: str=None) -> str: returns a User ID based on a... | 8a96ae4ccb489d4b7b194871d34abbca711e490a | <|skeleton|>
class SessionAuth:
"""authentication mechanism"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""returns a User ID based on a Session ID"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionAuth:
"""authentication mechanism"""
def create_session(self, user_id: str=None) -> str:
"""Creates a Session ID for a user_id"""
if user_id is None or type(user_id) != str:
return None
else:
session_id = str(uuid.uuid4())
self.user_id_by... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | LiliTa1762/holbertonschool-web_back_end | train | 0 |
eeb2bda7acf47639501ff8dc8029fabac384f08c | [
"super().__init__()\nif nn_embedding is not None:\n self.embedding = nn.Embedding.from_pretrained(nn_embedding)\nelif field_size is not None and embed_size is not None:\n self.embedding = nn.Embedding(field_size, embed_size, padding_idx=padding_idx)\nelse:\n raise ValueError('missing required arguments')\n... | <|body_start_0|>
super().__init__()
if nn_embedding is not None:
self.embedding = nn.Embedding.from_pretrained(nn_embedding)
elif field_size is not None and embed_size is not None:
self.embedding = nn.Embedding(field_size, embed_size, padding_idx=padding_idx)
else... | Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return | ListIndicesEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListIndicesEmbedding:
"""Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return"""
def __init__(self, embed_size: Optional[int]=None, field_size: Optional[int]=None, padding_idx: Optional[int]=0, nn_embedding:... | stack_v2_sparse_classes_75kplus_train_000743 | 9,540 | permissive | [
{
"docstring": "Initialize ListIndicesEmbedding. Args: embed_size (int, optional): size of embedding tensor. Defaults to None field_size (int, optional): size of inputs field. Defaults to None padding_idx (int, optional): padding index. Defaults to 0 nn_embedding (nn.Parameter, optional): pretrained embedding v... | 3 | stack_v2_sparse_classes_30k_train_020408 | Implement the Python class `ListIndicesEmbedding` described below.
Class description:
Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, field_s... | Implement the Python class `ListIndicesEmbedding` described below.
Class description:
Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, field_s... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class ListIndicesEmbedding:
"""Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return"""
def __init__(self, embed_size: Optional[int]=None, field_size: Optional[int]=None, padding_idx: Optional[int]=0, nn_embedding:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListIndicesEmbedding:
"""Base Input class for embedding of list of indices without order, which embed the list by multi head attention and aggregate before return"""
def __init__(self, embed_size: Optional[int]=None, field_size: Optional[int]=None, padding_idx: Optional[int]=0, nn_embedding: Optional[nn.... | the_stack_v2_python_sparse | torecsys/inputs/base/list_indices_emb.py | p768lwy3/torecsys | train | 98 |
4717b02c5afae899d00cb79205e12c7716ad16d9 | [
"children = self.pop()\nparts_prefix = self.peek_last()[1].label\nchildren = [prepend_parts(parts_prefix, c[1]) for c in children]\nself.peek_last()[1].children = children",
"while self.size() > 1:\n self.unwind()\nreturn self.peek_last()[1]"
] | <|body_start_0|>
children = self.pop()
parts_prefix = self.peek_last()[1].label
children = [prepend_parts(parts_prefix, c[1]) for c in children]
self.peek_last()[1].children = children
<|end_body_0|>
<|body_start_1|>
while self.size() > 1:
self.unwind()
retur... | The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary | NodeStack | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeStack:
"""The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary"""
def unwind(self):
"""Unwind the stack, co... | stack_v2_sparse_classes_75kplus_train_000744 | 5,071 | permissive | [
{
"docstring": "Unwind the stack, collapsing sub-paragraphs that are on the stack into the children of the previous level.",
"name": "unwind",
"signature": "def unwind(self)"
},
{
"docstring": "After all of the nodes have been inserted at their proper levels, collapse them into a single root nod... | 2 | stack_v2_sparse_classes_30k_train_052929 | Implement the Python class `NodeStack` described below.
Class description:
The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary
Method signatures... | Implement the Python class `NodeStack` described below.
Class description:
The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary
Method signatures... | ea608ac109a918fdda60491fffa3fbd646928cf4 | <|skeleton|>
class NodeStack:
"""The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary"""
def unwind(self):
"""Unwind the stack, co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeStack:
"""The NodeStack aids our construction of a struct.Node tree. We process xml one paragraph at a time; using a priority stack allows us to insert items at their proper depth and unwind the stack (collecting children) as necessary"""
def unwind(self):
"""Unwind the stack, collapsing sub-... | the_stack_v2_python_sparse | regparser/tree/xml_parser/tree_utils.py | fecgov/regulations-parser | train | 1 |
e9f4b101c0c60b4422a7603c2d0b056e06849d3d | [
"Process.__init__(self)\nself.logger = logging.getLogger('WeightsToEMA')\nself.conf = conf\nself.out_path = out_path\nself.queue = queue",
"while True:\n base = self.queue.get()\n if base is None:\n break\n for cur_stream in self.conf.STREAMS:\n if cur_stream['kind'] == 'weight':\n ... | <|body_start_0|>
Process.__init__(self)
self.logger = logging.getLogger('WeightsToEMA')
self.conf = conf
self.out_path = out_path
self.queue = queue
<|end_body_0|>
<|body_start_1|>
while True:
base = self.queue.get()
if base is None:
... | Helper to convert the weights to the EMA JSON formatted file | WeightsToEMA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightsToEMA:
"""Helper to convert the weights to the EMA JSON formatted file"""
def __init__(self, conf, out_path, queue):
"""Constructor :param conf: the configuration object :param out_path: the output directory :param logger: the logger :param queue: the queue of utterance to dea... | stack_v2_sparse_classes_75kplus_train_000745 | 5,839 | no_license | [
{
"docstring": "Constructor :param conf: the configuration object :param out_path: the output directory :param logger: the logger :param queue: the queue of utterance to deal with :returns: None :rtype:",
"name": "__init__",
"signature": "def __init__(self, conf, out_path, queue)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_012390 | Implement the Python class `WeightsToEMA` described below.
Class description:
Helper to convert the weights to the EMA JSON formatted file
Method signatures and docstrings:
- def __init__(self, conf, out_path, queue): Constructor :param conf: the configuration object :param out_path: the output directory :param logge... | Implement the Python class `WeightsToEMA` described below.
Class description:
Helper to convert the weights to the EMA JSON formatted file
Method signatures and docstrings:
- def __init__(self, conf, out_path, queue): Constructor :param conf: the configuration object :param out_path: the output directory :param logge... | c537a391f4547fcc48aa34ca7ddd949c3ebdc441 | <|skeleton|>
class WeightsToEMA:
"""Helper to convert the weights to the EMA JSON formatted file"""
def __init__(self, conf, out_path, queue):
"""Constructor :param conf: the configuration object :param out_path: the output directory :param logger: the logger :param queue: the queue of utterance to dea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeightsToEMA:
"""Helper to convert the weights to the EMA JSON formatted file"""
def __init__(self, conf, out_path, queue):
"""Constructor :param conf: the configuration object :param out_path: the output directory :param logger: the logger :param queue: the queue of utterance to deal with :retur... | the_stack_v2_python_sparse | rendering/utils/weights.py | seblemaguer/pyhts | train | 1 |
168079bd42d72499a3172b43ae429a1f2d2dd9d9 | [
"vals = []\n\ndef dfs(node):\n if node:\n vals.append(node.val)\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ' '.join(map(str, vals))",
"vals = collections.deque((int(val) for val in data.split()))\n\ndef dfs(min_val, max_val):\n if vals and min_val < vals[0] < max_val:\n ... | <|body_start_0|>
vals = []
def dfs(node):
if node:
vals.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return ' '.join(map(str, vals))
<|end_body_0|>
<|body_start_1|>
vals = collections.deque((int(val) for v... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vals = []
... | stack_v2_sparse_classes_75kplus_train_000746 | 1,905 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 8b08c72b7d448e8842ae4034e454f25281fce8c8 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
vals = []
def dfs(node):
if node:
vals.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return ' '.join(map(... | the_stack_v2_python_sparse | LeetCode/0449. Serialize and Deserialize BST.py | iverson52000/DataStructure_Algorithm | train | 0 | |
506cb6ea1613c2294980fcfd0fdf046fcf6b7766 | [
"self.MusicList = []\nself.MusicList.append('Music/9h00')\nself.MusicList.append('Music/Distress_Signa')\nself.MusicList.append('Music/Exchange')\nself.MusicList.append('Music/MN84_Theme')\nself.MusicList.append('Music/Shoulder_of_Orion')\nself.MusicList.append('Music/Sung-Thunder_Love')\nself.MusicList.append('Mus... | <|body_start_0|>
self.MusicList = []
self.MusicList.append('Music/9h00')
self.MusicList.append('Music/Distress_Signa')
self.MusicList.append('Music/Exchange')
self.MusicList.append('Music/MN84_Theme')
self.MusicList.append('Music/Shoulder_of_Orion')
self.MusicList... | 关于音乐播放 | Music | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Music:
"""关于音乐播放"""
def __init__(self):
"""加载音乐"""
<|body_0|>
def PlayMusic(self, MusicNumber):
"""播放音乐"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.MusicList = []
self.MusicList.append('Music/9h00')
self.MusicList.append... | stack_v2_sparse_classes_75kplus_train_000747 | 814 | no_license | [
{
"docstring": "加载音乐",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "播放音乐",
"name": "PlayMusic",
"signature": "def PlayMusic(self, MusicNumber)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013217 | Implement the Python class `Music` described below.
Class description:
关于音乐播放
Method signatures and docstrings:
- def __init__(self): 加载音乐
- def PlayMusic(self, MusicNumber): 播放音乐 | Implement the Python class `Music` described below.
Class description:
关于音乐播放
Method signatures and docstrings:
- def __init__(self): 加载音乐
- def PlayMusic(self, MusicNumber): 播放音乐
<|skeleton|>
class Music:
"""关于音乐播放"""
def __init__(self):
"""加载音乐"""
<|body_0|>
def PlayMusic(self, MusicN... | 0e268529e58a414a93390bd72d01cd242a365395 | <|skeleton|>
class Music:
"""关于音乐播放"""
def __init__(self):
"""加载音乐"""
<|body_0|>
def PlayMusic(self, MusicNumber):
"""播放音乐"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Music:
"""关于音乐播放"""
def __init__(self):
"""加载音乐"""
self.MusicList = []
self.MusicList.append('Music/9h00')
self.MusicList.append('Music/Distress_Signa')
self.MusicList.append('Music/Exchange')
self.MusicList.append('Music/MN84_Theme')
self.MusicList... | the_stack_v2_python_sparse | Music/Music.py | jubgjf/Rocket2 | train | 0 |
f88335f1626945df598ec5e619c88df3c14f83ef | [
"app = self.request.app\napp.logger.debug(f'Chat command {cmd}')\nif cmd == '/clear':\n await app.objects.execute(Message.delete().where(Message.room == self.room))\n app.logger.debug(f'Removed {count} messages')\n for peer in app.wslist[self.room.id].values():\n peer.send_json({'cmd': 'empty'})\nel... | <|body_start_0|>
app = self.request.app
app.logger.debug(f'Chat command {cmd}')
if cmd == '/clear':
await app.objects.execute(Message.delete().where(Message.room == self.room))
app.logger.debug(f'Removed {count} messages')
for peer in app.wslist[self.room.id].... | Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер | WebSocketMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
<|body_0|>
async def broadcast(self, message: Message) ... | stack_v2_sparse_classes_75kplus_train_000748 | 4,826 | no_license | [
{
"docstring": "Некоторые управляющие команды",
"name": "command_line",
"signature": "async def command_line(self, cmd: str) -> Dict[str, str]"
},
{
"docstring": "Рассылка сообщениий по всей комнате",
"name": "broadcast",
"signature": "async def broadcast(self, message: Message) -> None"... | 2 | stack_v2_sparse_classes_30k_train_045100 | Implement the Python class `WebSocketMixin` described below.
Class description:
Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер
Method signatures and docstrings:
- async def command_line(self, cmd: str) -> Dict[str, str]: Некоторые управляющие команды
- async def br... | Implement the Python class `WebSocketMixin` described below.
Class description:
Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер
Method signatures and docstrings:
- async def command_line(self, cmd: str) -> Dict[str, str]: Некоторые управляющие команды
- async def br... | b7760f05e1d00f28a06b07bcd120c4af0237ce94 | <|skeleton|>
class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
<|body_0|>
async def broadcast(self, message: Message) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
app = self.request.app
app.logger.debug(f'Chat command {cmd}')
... | the_stack_v2_python_sparse | src/chat_take_aiohttp/web/chat_handlers.py | Tsvetov/chat_take_aiohttp | train | 0 |
ba2ddacee0876c20dc77bbad2f57de2650a0ff89 | [
"form = ProductForm({'name': '', 'description': 'test', 'price': 'test', 'image': 'test'})\nself.assertFalse(form.is_valid())\nself.assertIn('name', form.errors.keys())\nself.assertEqual(form.errors['name'][0], 'This field is required.')",
"form = ProductForm({'name': 'test', 'description': '', 'price': 'test', '... | <|body_start_0|>
form = ProductForm({'name': '', 'description': 'test', 'price': 'test', 'image': 'test'})
self.assertFalse(form.is_valid())
self.assertIn('name', form.errors.keys())
self.assertEqual(form.errors['name'][0], 'This field is required.')
<|end_body_0|>
<|body_start_1|>
... | Test that the product form works | TestProductForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProductForm:
"""Test that the product form works"""
def test_name_is_required(self):
"""Test if form submits without name field"""
<|body_0|>
def test_description_is_required(self):
"""Test if form submits without description field"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_000749 | 2,400 | no_license | [
{
"docstring": "Test if form submits without name field",
"name": "test_name_is_required",
"signature": "def test_name_is_required(self)"
},
{
"docstring": "Test if form submits without description field",
"name": "test_description_is_required",
"signature": "def test_description_is_requ... | 4 | stack_v2_sparse_classes_30k_val_002601 | Implement the Python class `TestProductForm` described below.
Class description:
Test that the product form works
Method signatures and docstrings:
- def test_name_is_required(self): Test if form submits without name field
- def test_description_is_required(self): Test if form submits without description field
- def ... | Implement the Python class `TestProductForm` described below.
Class description:
Test that the product form works
Method signatures and docstrings:
- def test_name_is_required(self): Test if form submits without name field
- def test_description_is_required(self): Test if form submits without description field
- def ... | b4ef7a46708711bda460667b1f602d0bd67c0bae | <|skeleton|>
class TestProductForm:
"""Test that the product form works"""
def test_name_is_required(self):
"""Test if form submits without name field"""
<|body_0|>
def test_description_is_required(self):
"""Test if form submits without description field"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProductForm:
"""Test that the product form works"""
def test_name_is_required(self):
"""Test if form submits without name field"""
form = ProductForm({'name': '', 'description': 'test', 'price': 'test', 'image': 'test'})
self.assertFalse(form.is_valid())
self.assertIn(... | the_stack_v2_python_sparse | products/test_forms.py | AmyOShea/MS4-ARTstop | train | 1 |
e753452d7460b808bf887b7d8cf0a4474f68da9b | [
"super(PowerOn, self).__init__()\nself.switches = switches\nreturn",
"self.turn_all_off()\nparams = parameters.id_switch.parameters\nself.logger.info(\"Turning on {0} (switch '{1}')\".format(params.identifier, params.switch))\nself.switches[params.identifier](params.switch)\nreturn '{0}'.format(params.identifier)... | <|body_start_0|>
super(PowerOn, self).__init__()
self.switches = switches
return
<|end_body_0|>
<|body_start_1|>
self.turn_all_off()
params = parameters.id_switch.parameters
self.logger.info("Turning on {0} (switch '{1}')".format(params.identifier, params.switch))
... | A class to power-on a networked-switch | PowerOn | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowerOn:
"""A class to power-on a networked-switch"""
def __init__(self, switches):
""":param: - `switches`: A dictionary of identifiers:switches"""
<|body_0|>
def __call__(self, parameters):
""":param: - `parameters`: namedtuple with parameters.id_switch.paramet... | stack_v2_sparse_classes_75kplus_train_000750 | 1,138 | permissive | [
{
"docstring": ":param: - `switches`: A dictionary of identifiers:switches",
"name": "__init__",
"signature": "def __init__(self, switches)"
},
{
"docstring": ":param: - `parameters`: namedtuple with parameters.id_switch.parameters",
"name": "__call__",
"signature": "def __call__(self, p... | 3 | stack_v2_sparse_classes_30k_test_000998 | Implement the Python class `PowerOn` described below.
Class description:
A class to power-on a networked-switch
Method signatures and docstrings:
- def __init__(self, switches): :param: - `switches`: A dictionary of identifiers:switches
- def __call__(self, parameters): :param: - `parameters`: namedtuple with paramet... | Implement the Python class `PowerOn` described below.
Class description:
A class to power-on a networked-switch
Method signatures and docstrings:
- def __init__(self, switches): :param: - `switches`: A dictionary of identifiers:switches
- def __call__(self, parameters): :param: - `parameters`: namedtuple with paramet... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class PowerOn:
"""A class to power-on a networked-switch"""
def __init__(self, switches):
""":param: - `switches`: A dictionary of identifiers:switches"""
<|body_0|>
def __call__(self, parameters):
""":param: - `parameters`: namedtuple with parameters.id_switch.paramet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PowerOn:
"""A class to power-on a networked-switch"""
def __init__(self, switches):
""":param: - `switches`: A dictionary of identifiers:switches"""
super(PowerOn, self).__init__()
self.switches = switches
return
def __call__(self, parameters):
""":param: - `p... | the_stack_v2_python_sparse | apetools/commands/poweron.py | russell-n/oldape | train | 0 |
e14770f6fb324f8a37e997f57eb98353c5081c99 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | the Transformer decoder block class | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""the Transformer decoder block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate"""
<|body_0|>
def c... | stack_v2_sparse_classes_75kplus_train_000751 | 2,383 | no_license | [
{
"docstring": "Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "the call method for the transfor... | 2 | stack_v2_sparse_classes_30k_train_004954 | Implement the Python class `DecoderBlock` described below.
Class description:
the Transformer decoder block class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer... | Implement the Python class `DecoderBlock` described below.
Class description:
the Transformer decoder block class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class DecoderBlock:
"""the Transformer decoder block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate"""
<|body_0|>
def c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderBlock:
"""the Transformer decoder block class"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate"""
super(DecoderBlock, self).__init__... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/8-transformer_decoder_block.py | mag389/holbertonschool-machine_learning | train | 2 |
318b2e93ae4383e9492397a8596f33a0287dfee9 | [
"sum = 0\nif not root:\n return 0\nif root.left and (not root.left.left) and (not root.left.right):\n sum += root.left.val\nsum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)\nreturn sum",
"res = 0\nif not root:\n return res\nstack = [root]\nwhile stack:\n node = stack.pop(0)\n ... | <|body_start_0|>
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
return sum
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sum = 0
if not root:
... | stack_v2_sparse_classes_75kplus_train_000752 | 1,046 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves2",
"signature": "def sumOfLeftLeaves2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032023 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumO... | 88a822c48ef50187507d0f75ce65ecc39e849839 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.su... | the_stack_v2_python_sparse | bwu/binary_tree/404-sum-of-left-leaves.py | captainhcg/leetcode-in-py-and-go | train | 1 | |
30cbd1ada28240f02246a68d9885ded1c51c3ecd | [
"max_profit = 0\nlength = len(prices)\nfor i in range(length):\n pre = 0\n for j in range(i, length):\n pre = max(prices[j] - prices[i], pre)\n if max_profit < pre:\n max_profit = pre\nreturn max_profit",
"min_price = float('inf')\nmax_profit = 0\nlength = len(prices)\nfor i in rang... | <|body_start_0|>
max_profit = 0
length = len(prices)
for i in range(length):
pre = 0
for j in range(i, length):
pre = max(prices[j] - prices[i], pre)
if max_profit < pre:
max_profit = pre
return max_profit
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_profit = 0
length = len(pric... | stack_v2_sparse_classes_75kplus_train_000753 | 1,044 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043291 | 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 maxProfit1(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit1(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | d4a33dc28a6d3f99d5179fdb6a83b2ab8c5a0beb | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
max_profit = 0
length = len(prices)
for i in range(length):
pre = 0
for j in range(i, length):
pre = max(prices[j] - prices[i], pre)
if max_p... | the_stack_v2_python_sparse | leetcode/121_buy_stocks.py | 294150302hxq/python_learn | train | 0 | |
d42ed03251948c456c11cb1c31527be41a30e1ca | [
"if not root:\n return []\nres = []\nres += self.inorderTravel(root.left)\nres.append(root.val)\nres += self.inorderTravel(root.right)\nreturn res",
"res, stack = ([], [])\nwhile root is not None or stack:\n while root:\n stack.append(root)\n root = root.left\n node = stack.pop()\n res.a... | <|body_start_0|>
if not root:
return []
res = []
res += self.inorderTravel(root.left)
res.append(root.val)
res += self.inorderTravel(root.right)
return res
<|end_body_0|>
<|body_start_1|>
res, stack = ([], [])
while root is not None or stack:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTravel(self, root: TreeNode) -> list[int]:
"""递归解法"""
<|body_0|>
def inorderTravel2(self, root: TreeNode) -> list[int]:
"""迭代解法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
res = []
... | stack_v2_sparse_classes_75kplus_train_000754 | 725 | no_license | [
{
"docstring": "递归解法",
"name": "inorderTravel",
"signature": "def inorderTravel(self, root: TreeNode) -> list[int]"
},
{
"docstring": "迭代解法",
"name": "inorderTravel2",
"signature": "def inorderTravel2(self, root: TreeNode) -> list[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_030639 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTravel(self, root: TreeNode) -> list[int]: 递归解法
- def inorderTravel2(self, root: TreeNode) -> list[int]: 迭代解法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTravel(self, root: TreeNode) -> list[int]: 递归解法
- def inorderTravel2(self, root: TreeNode) -> list[int]: 迭代解法
<|skeleton|>
class Solution:
def inorderTravel(self... | bb02714b312d5a8368d7e4f4c35bb66eaaff36b9 | <|skeleton|>
class Solution:
def inorderTravel(self, root: TreeNode) -> list[int]:
"""递归解法"""
<|body_0|>
def inorderTravel2(self, root: TreeNode) -> list[int]:
"""迭代解法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def inorderTravel(self, root: TreeNode) -> list[int]:
"""递归解法"""
if not root:
return []
res = []
res += self.inorderTravel(root.left)
res.append(root.val)
res += self.inorderTravel(root.right)
return res
def inorderTravel2(self... | the_stack_v2_python_sparse | 数据结构/树/0010inorderTravel.py | AndongWen/leetcode | train | 0 | |
e22b7ee057ff4af98c2e036037015de5babe6ee1 | [
"self._model = model\nself._regress = regress\nself._planner = planner\nself._solver_names = sorted(suite.solvers)\nself._runs_limit = 256",
"with borg.accounting() as accountant:\n if self._regress is None:\n initial_model = self._model\n else:\n feature_names, feature_values = suite.domain.c... | <|body_start_0|>
self._model = model
self._regress = regress
self._planner = planner
self._solver_names = sorted(suite.solvers)
self._runs_limit = 256
<|end_body_0|>
<|body_start_1|>
with borg.accounting() as accountant:
if self._regress is None:
... | Hybrid mixture-model portfolio. | PureModelPortfolio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PureModelPortfolio:
"""Hybrid mixture-model portfolio."""
def __init__(self, suite, model, regress=None, planner=borg.planners.default):
"""Initialize."""
<|body_0|>
def __call__(self, task, suite, budget):
"""Run the portfolio."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_000755 | 7,542 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, suite, model, regress=None, planner=borg.planners.default)"
},
{
"docstring": "Run the portfolio.",
"name": "__call__",
"signature": "def __call__(self, task, suite, budget)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038849 | Implement the Python class `PureModelPortfolio` described below.
Class description:
Hybrid mixture-model portfolio.
Method signatures and docstrings:
- def __init__(self, suite, model, regress=None, planner=borg.planners.default): Initialize.
- def __call__(self, task, suite, budget): Run the portfolio. | Implement the Python class `PureModelPortfolio` described below.
Class description:
Hybrid mixture-model portfolio.
Method signatures and docstrings:
- def __init__(self, suite, model, regress=None, planner=borg.planners.default): Initialize.
- def __call__(self, task, suite, budget): Run the portfolio.
<|skeleton|>... | e4f0f0f400fdbfe969c8514f03b1fac3451fea60 | <|skeleton|>
class PureModelPortfolio:
"""Hybrid mixture-model portfolio."""
def __init__(self, suite, model, regress=None, planner=borg.planners.default):
"""Initialize."""
<|body_0|>
def __call__(self, task, suite, budget):
"""Run the portfolio."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PureModelPortfolio:
"""Hybrid mixture-model portfolio."""
def __init__(self, suite, model, regress=None, planner=borg.planners.default):
"""Initialize."""
self._model = model
self._regress = regress
self._planner = planner
self._solver_names = sorted(suite.solvers)... | the_stack_v2_python_sparse | optimization_code/venv/lib/python3.6/site-packages/borg/portfolios.py | iditbela2/Borg_python | train | 0 |
06a72380412a61e31b47c4be5bda90006cbcfe97 | [
"form_valid = isinstance(response, HttpResponseRedirect)\nif request.POST.get('_save') and form_valid:\n return redirect('admin:index')\nreturn response",
"try:\n singleton = self.model.objects.get()\nexcept (self.model.DoesNotExist, self.model.MultipleObjectsReturned):\n kwargs.setdefault('extra_context... | <|body_start_0|>
form_valid = isinstance(response, HttpResponseRedirect)
if request.POST.get('_save') and form_valid:
return redirect('admin:index')
return response
<|end_body_0|>
<|body_start_1|>
try:
singleton = self.model.objects.get()
except (self.mod... | Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton attribute to the div contain... | SingletonAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_75kplus_train_000756 | 3,870 | permissive | [
{
"docstring": "Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid.",
"name": "handle_save",
"signature": "def handle_save(self, request, response)"
},
{
"docstring": "Redirec... | 4 | stack_v2_sparse_classes_30k_test_002732 | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | c4fad2fe2cacaa21dd252a7407a84229dd20a46c | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton... | the_stack_v2_python_sparse | backend/apps/utils/admin.py | MadeInHaus/django-template | train | 1 |
7888c2b1eb20ff56234bb05f494a8abc41294b8a | [
"search = ['أ', 'إ', 'آ', 'ة', '_', '-', '/', '.', '،', ' و ', ' يا ', '\"', 'ـ', \"'\", 'ى', '\\\\', '\\n', '\\t', '"', '?', '؟', '!', ':', '(', ')', '\\x02']\nreplace = ['ا', 'ا', 'ا', 'ه', ' ', ' ', '', '', '', ' و', ' يا', '', '', '', 'ي', '', ' ', ' ', ' ', ' ? ', ' ؟ ', ' ! ', '', '', '', '']\np_tashkeel... | <|body_start_0|>
search = ['أ', 'إ', 'آ', 'ة', '_', '-', '/', '.', '،', ' و ', ' يا ', '"', 'ـ', "'", 'ى', '\\', '\n', '\t', '"', '?', '؟', '!', ':', '(', ')', '\x02']
replace = ['ا', 'ا', 'ا', 'ه', ' ', ' ', '', '', '', ' و', ' يا', '', '', '', 'ي', '', ' ', ' ', ' ', ' ? ', ' ؟ ', ' ! ', '', '', ... | Procces the data and embed them using AraVec OR ELMo | Embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
"""Procces the data and embed them using AraVec OR ELMo"""
def clean_str(text: str) -> str:
"""Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns str as a preprocessed book"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_000757 | 5,959 | no_license | [
{
"docstring": "Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns str as a preprocessed book",
"name": "clean_str",
"signature": "def clean_str(text: str) -> str"
},
{
"docstring": "Embed each word in the book into a Vector in... | 3 | stack_v2_sparse_classes_30k_train_026449 | Implement the Python class `Embedding` described below.
Class description:
Procces the data and embed them using AraVec OR ELMo
Method signatures and docstrings:
- def clean_str(text: str) -> str: Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns s... | Implement the Python class `Embedding` described below.
Class description:
Procces the data and embed them using AraVec OR ELMo
Method signatures and docstrings:
- def clean_str(text: str) -> str: Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns s... | c7349dd0501e9a0d47a8f1024762ee15b225c6e0 | <|skeleton|>
class Embedding:
"""Procces the data and embed them using AraVec OR ELMo"""
def clean_str(text: str) -> str:
"""Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns str as a preprocessed book"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedding:
"""Procces the data and embed them using AraVec OR ELMo"""
def clean_str(text: str) -> str:
"""Removing any additional characters found in the TEXT, Based on AraVec. :parameter text in str format as a book :returns str as a preprocessed book"""
search = ['أ', 'إ', 'آ', 'ة', '_'... | the_stack_v2_python_sparse | Algs/Embedding.py | saleems11/Final_Project_B | train | 0 |
edd85c517a28e0d07098960a989d08a439a70eaf | [
"def preorder(node: TreeNode) -> str:\n if not node:\n return ''\n return ','.join([str(node.val), preorder(node.left), preorder(node.right)])\nreturn preorder(root)",
"arr = data.split(',')\narr.reverse()\n\ndef build(arr) -> TreeNode:\n val = arr.pop()\n if val == '':\n return None\n ... | <|body_start_0|>
def preorder(node: TreeNode) -> str:
if not node:
return ''
return ','.join([str(node.val), preorder(node.left), preorder(node.right)])
return preorder(root)
<|end_body_0|>
<|body_start_1|>
arr = data.split(',')
arr.reverse()
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def preorder(n... | stack_v2_sparse_classes_75kplus_train_000758 | 1,297 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_046865 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 64fd7baf3543a7a32ebcbaadb39c11fcc152bf4c | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(node: TreeNode) -> str:
if not node:
return ''
return ','.join([str(node.val), preorder(node.left), preorder(node.right)])
return preorder(ro... | the_stack_v2_python_sparse | daily/20201009-serialize-bst.py | kapppa-joe/leetcode-practice | train | 0 | |
2b7b2833cfe463367e53354102656bbdf9e10cec | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WorkbookTable()",
"from .entity import Entity\nfrom .workbook_table_column import WorkbookTableColumn\nfrom .workbook_table_row import WorkbookTableRow\nfrom .workbook_table_sort import WorkbookTableSort\nfrom .workbook_worksheet impor... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WorkbookTable()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .workbook_table_column import WorkbookTableColumn
from .workbook_table_row import WorkbookTableRow... | WorkbookTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbookTable:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookTable:
"""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_75kplus_train_000759 | 6,969 | 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: WorkbookTable",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_001808 | Implement the Python class `WorkbookTable` described below.
Class description:
Implement the WorkbookTable class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookTable: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `WorkbookTable` described below.
Class description:
Implement the WorkbookTable class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookTable: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WorkbookTable:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookTable:
"""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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkbookTable:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookTable:
"""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: WorkbookTabl... | the_stack_v2_python_sparse | msgraph/generated/models/workbook_table.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
37e869cac448280284f8cbd728f29824fb7b8659 | [
"conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, energy_carriers_worksheet = self.read_excel(locator)\nself.ENERGY_CARRIERS = energy_carriers_worksheet\nself.FEEDSTOCKS = feedstocks_worksheets\nself.PIPING = distribution_systems_worksheets['THERMAL_GRID']\nself.PV = conversion... | <|body_start_0|>
conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, energy_carriers_worksheet = self.read_excel(locator)
self.ENERGY_CARRIERS = energy_carriers_worksheet
self.FEEDSTOCKS = feedstocks_worksheets
self.PIPING = distribution_systems_workshe... | Expose the worksheets in supply_systems.xls as pandas.Dataframes. | SupplySystemsDatabase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
<|body_0|>
def read_excel(self, locator):
"""Read in the excel... | stack_v2_sparse_classes_75kplus_train_000760 | 2,919 | permissive | [
{
"docstring": ":param cea.inputlocator.InputLocator locator: provides the path to the",
"name": "__init__",
"signature": "def __init__(self, locator)"
},
{
"docstring": "Read in the excel file, using the cache _locators",
"name": "read_excel",
"signature": "def read_excel(self, locator)... | 2 | stack_v2_sparse_classes_30k_train_010834 | Implement the Python class `SupplySystemsDatabase` described below.
Class description:
Expose the worksheets in supply_systems.xls as pandas.Dataframes.
Method signatures and docstrings:
- def __init__(self, locator): :param cea.inputlocator.InputLocator locator: provides the path to the
- def read_excel(self, locato... | Implement the Python class `SupplySystemsDatabase` described below.
Class description:
Expose the worksheets in supply_systems.xls as pandas.Dataframes.
Method signatures and docstrings:
- def __init__(self, locator): :param cea.inputlocator.InputLocator locator: provides the path to the
- def read_excel(self, locato... | b84bcefdfdfc2bc0e009b5284b74391a957995ac | <|skeleton|>
class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
<|body_0|>
def read_excel(self, locator):
"""Read in the excel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupplySystemsDatabase:
"""Expose the worksheets in supply_systems.xls as pandas.Dataframes."""
def __init__(self, locator):
""":param cea.inputlocator.InputLocator locator: provides the path to the"""
conversion_systems_worksheets, distribution_systems_worksheets, feedstocks_worksheets, e... | the_stack_v2_python_sparse | cea/technologies/supply_systems_database.py | architecture-building-systems/CityEnergyAnalyst | train | 166 |
300bd3b7a8e4c50285412100336b61032ebee791 | [
"self.BATCH_SIZE = self.IMAGES_PER_GPU\nif self.SEGMENTATION_TASK == 'all':\n self.NUM_OUTPUT_CH = len(self.NAMES_CLASSES)\nelse:\n self.NUM_OUTPUT_CH = 1\nif not self.GPU_SERVER and self.MAX_CPU_COUNT > 8:\n self.MAX_CPU_COUNT = 8",
"print('\\nConfigurations:')\nfor a in dir(self):\n if not a.startsw... | <|body_start_0|>
self.BATCH_SIZE = self.IMAGES_PER_GPU
if self.SEGMENTATION_TASK == 'all':
self.NUM_OUTPUT_CH = len(self.NAMES_CLASSES)
else:
self.NUM_OUTPUT_CH = 1
if not self.GPU_SERVER and self.MAX_CPU_COUNT > 8:
self.MAX_CPU_COUNT = 8
<|end_body_0|... | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self):
"""Compute some attributes out of the attributes above"""
<|body_0|>
def display(self):
"""Display configuration"""
<|body_1|>
def write_cfg_to_log(self, path):
"""Log configuration"""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_000761 | 8,248 | permissive | [
{
"docstring": "Compute some attributes out of the attributes above",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display configuration",
"name": "display",
"signature": "def display(self)"
},
{
"docstring": "Log configuration",
"name": "write_cfg... | 3 | stack_v2_sparse_classes_30k_train_053278 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self): Compute some attributes out of the attributes above
- def display(self): Display configuration
- def write_cfg_to_log(self, path): Log configuration | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self): Compute some attributes out of the attributes above
- def display(self): Display configuration
- def write_cfg_to_log(self, path): Log configuration
<|skeleton|>... | a33afcc186d618889df73c7ab2941dfbb63574ac | <|skeleton|>
class Config:
def __init__(self):
"""Compute some attributes out of the attributes above"""
<|body_0|>
def display(self):
"""Display configuration"""
<|body_1|>
def write_cfg_to_log(self, path):
"""Log configuration"""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
def __init__(self):
"""Compute some attributes out of the attributes above"""
self.BATCH_SIZE = self.IMAGES_PER_GPU
if self.SEGMENTATION_TASK == 'all':
self.NUM_OUTPUT_CH = len(self.NAMES_CLASSES)
else:
self.NUM_OUTPUT_CH = 1
if not self.... | the_stack_v2_python_sparse | config/config.py | imsb-uke/podometric_u_net | train | 0 | |
f6e0b997e0ab73243c7e9380538a593e2e0e5dbc | [
"if self._disable:\n return False\nif self.spectrograph is None or self.telescope is None:\n return False\nif self.unknown != 'snr':\n raise NotImplementedError('Only SNR calculations currently supported')\nself._update_snr()",
"if self.verbose:\n msg1 = 'Creating exposure for {} ({})'.format(self.tel... | <|body_start_0|>
if self._disable:
return False
if self.spectrograph is None or self.telescope is None:
return False
if self.unknown != 'snr':
raise NotImplementedError('Only SNR calculations currently supported')
self._update_snr()
<|end_body_0|>
<|b... | A subclass of the base Exposure model, for spectroscopic ETC calculations. | SpectrographicExposure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is c... | stack_v2_sparse_classes_75kplus_train_000762 | 18,852 | no_license | [
{
"docstring": "Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The \"unknown\" attribute controls which of these parameters is calculated.",
"name": "calculate",
"signature": "def calculate(self)"
},
{
"docstring": "Calculate the SNR based on the curr... | 2 | stack_v2_sparse_classes_30k_train_010642 | Implement the Python class `SpectrographicExposure` described below.
Class description:
A subclass of the base Exposure model, for spectroscopic ETC calculations.
Method signatures and docstrings:
- def calculate(self): Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "u... | Implement the Python class `SpectrographicExposure` described below.
Class description:
A subclass of the base Exposure model, for spectroscopic ETC calculations.
Method signatures and docstrings:
- def calculate(self): Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "u... | ccd63cc79671fb333b892c3125861be2128e5ee8 | <|skeleton|>
class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectrographicExposure:
"""A subclass of the base Exposure model, for spectroscopic ETC calculations."""
def calculate(self):
"""Wrapper to calculate the exposure time, SNR, or limiting magnitude, based on the other two. The "unknown" attribute controls which of these parameters is calculated."""... | the_stack_v2_python_sparse | syotools/models/exposure.py | tumlinson/luvoir_simtools | train | 1 |
02fcf800cf414b286f03ff5d7169689f6ef64e31 | [
"if num <= 0:\n return False\nfor d in (2, 3, 5):\n while num % d == 0:\n num //= d\nreturn num == 1",
"if num <= 0:\n return False\nelif num in (1, 2, 3, 5):\n return True\nfor d in (2, 3, 5):\n if num % d == 0:\n return self.isUgly(num // d)\nreturn False"
] | <|body_start_0|>
if num <= 0:
return False
for d in (2, 3, 5):
while num % d == 0:
num //= d
return num == 1
<|end_body_0|>
<|body_start_1|>
if num <= 0:
return False
elif num in (1, 2, 3, 5):
return True
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def isUgly_recursive(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num <= 0:
return False
for d in (2, ... | stack_v2_sparse_classes_75kplus_train_000763 | 1,433 | no_license | [
{
"docstring": ":type num: int :rtype: bool",
"name": "isUgly",
"signature": "def isUgly(self, num)"
},
{
"docstring": ":type num: int :rtype: bool",
"name": "isUgly_recursive",
"signature": "def isUgly_recursive(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011217 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def isUgly_recursive(self, num): :type num: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def isUgly_recursive(self, num): :type num: int :rtype: bool
<|skeleton|>
class Solution:
def isUgly(self, num):
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def isUgly_recursive(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
if num <= 0:
return False
for d in (2, 3, 5):
while num % d == 0:
num //= d
return num == 1
def isUgly_recursive(self, num):
""":type num: int :rtype: bool"""... | the_stack_v2_python_sparse | src/lt_263.py | oxhead/CodingYourWay | train | 0 | |
bc93844f545224d8d80be5a572393365664efbff | [
"self.angles = []\nself.detector_num = 0\nself.wavelength = 0\nself.distance = 0\nself.integrated = 0\nself.sigI = 1.0\nself.peak_width = 0\nself.measurement_num = 0\nself.horizontal = 0\nself.vertical = 0",
"if len(self.angles) >= 3:\n phi, chi, omega = np.rad2deg(self.angles)\n return '%.1f, %.1f, %.1f' %... | <|body_start_0|>
self.angles = []
self.detector_num = 0
self.wavelength = 0
self.distance = 0
self.integrated = 0
self.sigI = 1.0
self.peak_width = 0
self.measurement_num = 0
self.horizontal = 0
self.vertical = 0
<|end_body_0|>
<|body_star... | Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW). | ReflectionRealMeasurement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflectionRealMeasurement:
"""Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW)."""
def __init__(self):
"""Constructor."""
<|body_0|>
def make_sample_orientation_string(self):
"""Return a friendly string of t... | stack_v2_sparse_classes_75kplus_train_000764 | 13,320 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a friendly string of the sample orientation angles.",
"name": "make_sample_orientation_string",
"signature": "def make_sample_orientation_string(self)"
}
] | 2 | null | Implement the Python class `ReflectionRealMeasurement` described below.
Class description:
Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW).
Method signatures and docstrings:
- def __init__(self): Constructor.
- def make_sample_orientation_string(self): Return a... | Implement the Python class `ReflectionRealMeasurement` described below.
Class description:
Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW).
Method signatures and docstrings:
- def __init__(self): Constructor.
- def make_sample_orientation_string(self): Return a... | 454d52fd9694bad6371c9e7c924d897a47c13f00 | <|skeleton|>
class ReflectionRealMeasurement:
"""Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW)."""
def __init__(self):
"""Constructor."""
<|body_0|>
def make_sample_orientation_string(self):
"""Return a friendly string of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReflectionRealMeasurement:
"""Class holds info about a real peak measurement (loaded from an peaks or integrate file produced by ISAW)."""
def __init__(self):
"""Constructor."""
self.angles = []
self.detector_num = 0
self.wavelength = 0
self.distance = 0
se... | the_stack_v2_python_sparse | model/reflections.py | neutrons/CrystalPlan | train | 2 |
08a6bf759ce2a3d37a4e050d90b9e6363ca968f5 | [
"if upper_bnd == 0:\n lower_bnd, upper_bnd = (upper_bnd, lower_bnd)\nreturn (val - lower_bnd) / (upper_bnd - lower_bnd)",
"for index, _ in ndenumerate(sim_map.grid):\n x, y = index\n i = cls.normalize(float(x), float(sim_map.width))\n j = cls.normalize(float(y), float(sim_map.height))\n noise = sno... | <|body_start_0|>
if upper_bnd == 0:
lower_bnd, upper_bnd = (upper_bnd, lower_bnd)
return (val - lower_bnd) / (upper_bnd - lower_bnd)
<|end_body_0|>
<|body_start_1|>
for index, _ in ndenumerate(sim_map.grid):
x, y = index
i = cls.normalize(float(x), float(sim_... | Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin | AleaPerlin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AleaPerlin:
"""Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin"""
def normalize(cls, val, lower_bnd, upper_bnd=0):
"""Transforme une valeur dans un intervalle donné en valeur entre 0 et 1. Exemples : >>> normalize(2, 0, 10) 0.2 >>> normalize(56.... | stack_v2_sparse_classes_75kplus_train_000765 | 2,340 | no_license | [
{
"docstring": "Transforme une valeur dans un intervalle donné en valeur entre 0 et 1. Exemples : >>> normalize(2, 0, 10) 0.2 >>> normalize(56.5, 54.5, 64.5) 0.2 >>> normalize(1000, 500, 1500) 0.5 >>> normalize(1000, 0, 100) 10 Si la borne supérieure est omise, elle est remplacée par la borne inférieure, et la ... | 2 | stack_v2_sparse_classes_30k_test_000452 | Implement the Python class `AleaPerlin` described below.
Class description:
Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin
Method signatures and docstrings:
- def normalize(cls, val, lower_bnd, upper_bnd=0): Transforme une valeur dans un intervalle donné en valeur entre 0 et 1.... | Implement the Python class `AleaPerlin` described below.
Class description:
Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin
Method signatures and docstrings:
- def normalize(cls, val, lower_bnd, upper_bnd=0): Transforme une valeur dans un intervalle donné en valeur entre 0 et 1.... | d1c7395500b2b5c304cc8a587e00b37e85b200e2 | <|skeleton|>
class AleaPerlin:
"""Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin"""
def normalize(cls, val, lower_bnd, upper_bnd=0):
"""Transforme une valeur dans un intervalle donné en valeur entre 0 et 1. Exemples : >>> normalize(2, 0, 10) 0.2 >>> normalize(56.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AleaPerlin:
"""Met a disposition la méthode pour générer une carte à l'aide de l'algorithme de perlin"""
def normalize(cls, val, lower_bnd, upper_bnd=0):
"""Transforme une valeur dans un intervalle donné en valeur entre 0 et 1. Exemples : >>> normalize(2, 0, 10) 0.2 >>> normalize(56.5, 54.5, 64.5... | the_stack_v2_python_sparse | propsim/builder/alea_perlin.py | Thomsch/propagation-simulator | train | 1 |
2fe6b9907dbcb47b467b1c2566b8a85b3b7f4c09 | [
"import collections, bisect\nA = sorted(A)\na = set(A)\ndicts = collections.defaultdict(int)\nfor i in range(len(A)):\n dicts[A[i]] = 1\n k = bisect.bisect_right(A, A[i] ** 0.5)\n for j in range(k):\n if A[i] % A[j] == 0 and A[i] // A[j] in a:\n if A[i] == A[j] ** 2:\n dict... | <|body_start_0|>
import collections, bisect
A = sorted(A)
a = set(A)
dicts = collections.defaultdict(int)
for i in range(len(A)):
dicts[A[i]] = 1
k = bisect.bisect_right(A, A[i] ** 0.5)
for j in range(k):
if A[i] % A[j] == 0 and... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
<|body_0|>
def numBinarydps_1(self, A):
"""562ms :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections, bisect
A = sort... | stack_v2_sparse_classes_75kplus_train_000766 | 2,265 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int 152ms",
"name": "numFactoredBinaryTrees",
"signature": "def numFactoredBinaryTrees(self, A)"
},
{
"docstring": "562ms :param A: :return:",
"name": "numBinarydps_1",
"signature": "def numBinarydps_1(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036626 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int 152ms
- def numBinarydps_1(self, A): 562ms :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFactoredBinaryTrees(self, A): :type A: List[int] :rtype: int 152ms
- def numBinarydps_1(self, A): 562ms :param A: :return:
<|skeleton|>
class Solution:
def numFactor... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
<|body_0|>
def numBinarydps_1(self, A):
"""562ms :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numFactoredBinaryTrees(self, A):
""":type A: List[int] :rtype: int 152ms"""
import collections, bisect
A = sorted(A)
a = set(A)
dicts = collections.defaultdict(int)
for i in range(len(A)):
dicts[A[i]] = 1
k = bisect.bisect_r... | the_stack_v2_python_sparse | BinaryTreesWithFactors_MID_823.py | 953250587/leetcode-python | train | 2 | |
8db92658313ffb4aec61fd84d7bd3a1a4f443b3f | [
"map = {}\nfor i in s:\n print(i)\n if i in map:\n map[i] = map[i] + 1\n else:\n map[i] = 0\nfor index, i in enumerate(s):\n if map[i] == 0:\n return index\nreturn -1",
"dic = collections.Counter(s)\nprint(dic)\nfor i in range(len(s)):\n if dic[s[i]] == 1:\n return i\nre... | <|body_start_0|>
map = {}
for i in s:
print(i)
if i in map:
map[i] = map[i] + 1
else:
map[i] = 0
for index, i in enumerate(s):
if map[i] == 0:
return index
return -1
<|end_body_0|>
<|body_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(s):
"""字符串中的第一个唯一字符 使用切片 :type str: object"""
<|body_0|>
def firstUniqChar02(s):
"""字符串中的第一个唯一字符 使用切片 :type str: object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
map = {}
for i in s:
print(i)
... | stack_v2_sparse_classes_75kplus_train_000767 | 1,347 | no_license | [
{
"docstring": "字符串中的第一个唯一字符 使用切片 :type str: object",
"name": "firstUniqChar",
"signature": "def firstUniqChar(s)"
},
{
"docstring": "字符串中的第一个唯一字符 使用切片 :type str: object",
"name": "firstUniqChar02",
"signature": "def firstUniqChar02(s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035560 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(s): 字符串中的第一个唯一字符 使用切片 :type str: object
- def firstUniqChar02(s): 字符串中的第一个唯一字符 使用切片 :type str: object | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(s): 字符串中的第一个唯一字符 使用切片 :type str: object
- def firstUniqChar02(s): 字符串中的第一个唯一字符 使用切片 :type str: object
<|skeleton|>
class Solution:
def firstUniqChar(s):
... | 74df49d16a41c18b95e56f3b54aaeb57ced0c8e2 | <|skeleton|>
class Solution:
def firstUniqChar(s):
"""字符串中的第一个唯一字符 使用切片 :type str: object"""
<|body_0|>
def firstUniqChar02(s):
"""字符串中的第一个唯一字符 使用切片 :type str: object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstUniqChar(s):
"""字符串中的第一个唯一字符 使用切片 :type str: object"""
map = {}
for i in s:
print(i)
if i in map:
map[i] = map[i] + 1
else:
map[i] = 0
for index, i in enumerate(s):
if map[i] == 0... | the_stack_v2_python_sparse | primary_algorithm/string/firstUniqChar.py | Lwq1997/leetcode-python | train | 0 | |
6dc35c3b7f140e1b57449d2562c9f49c023ec41b | [
"if self.verbose:\n delta = logprob - self.history[-1] if self.history else np.nan\n relative_delta = np.abs(delta / self.history[-1]) if self.history else np.nan\n message = self._template.format(iter=self.iter + 1, logprob=logprob, delta=relative_delta)\n print(message, file=sys.stderr)\nself.history.... | <|body_start_0|>
if self.verbose:
delta = logprob - self.history[-1] if self.history else np.nan
relative_delta = np.abs(delta / self.history[-1]) if self.history else np.nan
message = self._template.format(iter=self.iter + 1, logprob=logprob, delta=relative_delta)
... | A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1. | RelativeConvergenceMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativeConvergenceMonitor:
"""A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1."""
def report(self, logprob):
... | stack_v2_sparse_classes_75kplus_train_000768 | 22,700 | no_license | [
{
"docstring": "Reports convergence to :data:`sys.stderr`. The output consists of three columns: iteration number, log probability of the data at the current iteration and convergence rate. At the first iteration convergence rate is unknown and is thus denoted by NaN. Parameters ---------- logprob : float The l... | 2 | null | Implement the Python class `RelativeConvergenceMonitor` described below.
Class description:
A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1... | Implement the Python class `RelativeConvergenceMonitor` described below.
Class description:
A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1... | a04e357905cacc1efd75ec96ffcb6e293bb71ab9 | <|skeleton|>
class RelativeConvergenceMonitor:
"""A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1."""
def report(self, logprob):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelativeConvergenceMonitor:
"""A modified convergence monitor with more relaxed stopping criteria. Rather than evaluate the tolerance on the difference of likelihoods at iterations t and t_-1, we use the percentage change, i.e. the ratio of (t - t_-1) / t_-1."""
def report(self, logprob):
"""Repo... | the_stack_v2_python_sparse | lab3/lab3/analysis/models/hmm.py | james-priestley/ca1_novelty_analysis | train | 0 |
fa7434d1e859e4d94c2dade90d9bf66a990629cf | [
"if not root:\n return True\nnodes = [root]\nwhile nodes:\n node = nodes.pop()\n if abs(self.maxDepth(node.left) - self.maxDepth(node.right)) > 1:\n return False\n if node.left:\n nodes.append(node.left)\n if node.right:\n nodes.append(node.right)\nreturn True",
"if not root:\n... | <|body_start_0|>
if not root:
return True
nodes = [root]
while nodes:
node = nodes.pop()
if abs(self.maxDepth(node.left) - self.maxDepth(node.right)) > 1:
return False
if node.left:
nodes.append(node.left)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
nodes... | stack_v2_sparse_classes_75kplus_train_000769 | 2,310 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002986 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def isBalanced(self,... | 57080da5fbe5d62cbc0b8a34e362a8b0978d5b59 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
nodes = [root]
while nodes:
node = nodes.pop()
if abs(self.maxDepth(node.left) - self.maxDepth(node.right)) > 1:
return Fal... | the_stack_v2_python_sparse | python/tree/0110_balanced_binary_tree.py | linshaoyong/leetcode | train | 6 | |
7ada38ce3f9e547a2bbc91c707b9c16f68211b33 | [
"view = ElasticListAPIView()\nview.Meta.model = None\nwith self.assertRaises(AssertionError):\n view.get_queryset()",
"expectation = Search().query('match', field='value')\nview = ElasticListAPIView()\nview.Meta.model = MagicMock()\nview.Meta.model.return_value = 'Some'\nview.Meta.model.search.return_value = e... | <|body_start_0|>
view = ElasticListAPIView()
view.Meta.model = None
with self.assertRaises(AssertionError):
view.get_queryset()
<|end_body_0|>
<|body_start_1|>
expectation = Search().query('match', field='value')
view = ElasticListAPIView()
view.Meta.model = ... | View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic. | ViewTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewTests:
"""View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic."""
def test_model_not_set(self):
"""Test handling of no model"""
<|body_0|>
def test_model_set(self):
"""Test handling when model is set"""... | stack_v2_sparse_classes_75kplus_train_000770 | 12,045 | permissive | [
{
"docstring": "Test handling of no model",
"name": "test_model_not_set",
"signature": "def test_model_not_set(self)"
},
{
"docstring": "Test handling when model is set",
"name": "test_model_set",
"signature": "def test_model_set(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021151 | Implement the Python class `ViewTests` described below.
Class description:
View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic.
Method signatures and docstrings:
- def test_model_not_set(self): Test handling of no model
- def test_model_set(self): Test handling... | Implement the Python class `ViewTests` described below.
Class description:
View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic.
Method signatures and docstrings:
- def test_model_not_set(self): Test handling of no model
- def test_model_set(self): Test handling... | 73d334a9f0df7c044c06989977a9a22dd2ff9b7a | <|skeleton|>
class ViewTests:
"""View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic."""
def test_model_not_set(self):
"""Test handling of no model"""
<|body_0|>
def test_model_set(self):
"""Test handling when model is set"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewTests:
"""View testing. Testing the actual get would take a lot of mocking for little value since it is pretty generic."""
def test_model_not_set(self):
"""Test handling of no model"""
view = ElasticListAPIView()
view.Meta.model = None
with self.assertRaises(AssertionE... | the_stack_v2_python_sparse | goldstone/drfes/tests.py | bhuvan-rk/goldstone-server | train | 0 |
4a622fe91a923ad9ee0b5b1b69226941ca9026f2 | [
"logger.logic_log('LOSI00001', 'None')\nself.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name\nself.hostname = gethostname()\nlogger.logic_log('LOSI00002', 'None')",
"logger.logic_log('LOSI00001', 'aryPCB: %s, zabbix_adapter_id: %s' % (aryPCB, zabbix_adapter_id))\ntry:\n file_path = os.path.... | <|body_start_0|>
logger.logic_log('LOSI00001', 'None')
self.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name
self.hostname = gethostname()
logger.logic_log('LOSI00002', 'None')
<|end_body_0|>
<|body_start_1|>
logger.logic_log('LOSI00001', 'aryPCB: %s, zabbix_a... | [クラス概要] ZABBIXアダプタメイン処理クラス | ZabbixAdapterMainModules | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
<|body_0|>
def execute_subprocess(self, aryPCB, zabbix_adapter_id):
"""[概要] Zabbix情報を取得する子プロセスを起動するメソッド"""
<|body_1|>
def do_normal(self, aryPCB):
... | stack_v2_sparse_classes_75kplus_train_000771 | 7,891 | permissive | [
{
"docstring": "[概要] コンストラクタ",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "[概要] Zabbix情報を取得する子プロセスを起動するメソッド",
"name": "execute_subprocess",
"signature": "def execute_subprocess(self, aryPCB, zabbix_adapter_id)"
},
{
"docstring": "ZABBIXアダプタ通常実行",
... | 5 | stack_v2_sparse_classes_30k_train_013196 | Implement the Python class `ZabbixAdapterMainModules` described below.
Class description:
[クラス概要] ZABBIXアダプタメイン処理クラス
Method signatures and docstrings:
- def __init__(self): [概要] コンストラクタ
- def execute_subprocess(self, aryPCB, zabbix_adapter_id): [概要] Zabbix情報を取得する子プロセスを起動するメソッド
- def do_normal(self, aryPCB): ZABBIXアダプ... | Implement the Python class `ZabbixAdapterMainModules` described below.
Class description:
[クラス概要] ZABBIXアダプタメイン処理クラス
Method signatures and docstrings:
- def __init__(self): [概要] コンストラクタ
- def execute_subprocess(self, aryPCB, zabbix_adapter_id): [概要] Zabbix情報を取得する子プロセスを起動するメソッド
- def do_normal(self, aryPCB): ZABBIXアダプ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
<|body_0|>
def execute_subprocess(self, aryPCB, zabbix_adapter_id):
"""[概要] Zabbix情報を取得する子プロセスを起動するメソッド"""
<|body_1|>
def do_normal(self, aryPCB):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZabbixAdapterMainModules:
"""[クラス概要] ZABBIXアダプタメイン処理クラス"""
def __init__(self):
"""[概要] コンストラクタ"""
logger.logic_log('LOSI00001', 'None')
self.last_update_user = User.objects.get(user_id=DB_OASE_USER).user_name
self.hostname = gethostname()
logger.logic_log('LOSI0000... | the_stack_v2_python_sparse | oase-root/backyards/monitoring_adapter/ZABBIX_monitoring.py | exastro-suite/oase | train | 10 |
14d83cee7cdde9bccc0541cee510ae743c5cc64b | [
"self.users = defaultdict(set)\nself.tweets = defaultdict(list)\nself.ts = 0",
"if userId not in self.users:\n self.users[userId].add(userId)\nself.tweets[userId].append((self.ts, tweetId))\nself.ts += 1",
"newsfeed = []\nfor people_present_post in self.users[userId]:\n newsfeed = newsfeed + self.tweets[p... | <|body_start_0|>
self.users = defaultdict(set)
self.tweets = defaultdict(list)
self.ts = 0
<|end_body_0|>
<|body_start_1|>
if userId not in self.users:
self.users[userId].add(userId)
self.tweets[userId].append((self.ts, tweetId))
self.ts += 1
<|end_body_1|>
... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_75kplus_train_000772 | 6,784 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 5 | stack_v2_sparse_classes_30k_train_007747 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | fcc16124cc24a5993e27f5d97e78d8f290e68230 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.users = defaultdict(set)
self.tweets = defaultdict(list)
self.ts = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
if userId not in self.users:... | the_stack_v2_python_sparse | 355. Design Twitter.py | jianhui-ben/leetcode_python | train | 0 | |
644e7f637bbae867f3b761e42a0ae599dbfdcae1 | [
"n = len(nums)\nif not n % 2:\n return True\ndp = [[-1 for _ in xrange(n)] for _ in xrange(n)]\nmaxSum = self.dfs(dp, 0, n - 1, nums)\nreturn 2 * maxSum >= sum(nums)",
"if i > j:\n return 0\nif dp[i][j] != -1:\n return dp[i][j]\na = nums[i] + min(self.dfs(dp, i + 1, j - 1, nums), self.dfs(dp, i + 2, j, n... | <|body_start_0|>
n = len(nums)
if not n % 2:
return True
dp = [[-1 for _ in xrange(n)] for _ in xrange(n)]
maxSum = self.dfs(dp, 0, n - 1, nums)
return 2 * maxSum >= sum(nums)
<|end_body_0|>
<|body_start_1|>
if i > j:
return 0
if dp[i][j] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def dfs(self, dp, i, j, nums):
""":dp: dp table :i: left index :j: right index"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if n... | stack_v2_sparse_classes_75kplus_train_000773 | 802 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "PredictTheWinner",
"signature": "def PredictTheWinner(self, nums)"
},
{
"docstring": ":dp: dp table :i: left index :j: right index",
"name": "dfs",
"signature": "def dfs(self, dp, i, j, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000708 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool
- def dfs(self, dp, i, j, nums): :dp: dp table :i: left index :j: right index | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def PredictTheWinner(self, nums): :type nums: List[int] :rtype: bool
- def dfs(self, dp, i, j, nums): :dp: dp table :i: left index :j: right index
<|skeleton|>
class Solution:
... | 43bf3c594a71535a3f4ee9154cc72344b92b0608 | <|skeleton|>
class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def dfs(self, dp, i, j, nums):
""":dp: dp table :i: left index :j: right index"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def PredictTheWinner(self, nums):
""":type nums: List[int] :rtype: bool"""
n = len(nums)
if not n % 2:
return True
dp = [[-1 for _ in xrange(n)] for _ in xrange(n)]
maxSum = self.dfs(dp, 0, n - 1, nums)
return 2 * maxSum >= sum(nums)
d... | the_stack_v2_python_sparse | python/predictthewinner.py | john15518513/leetcode | train | 0 | |
c611fbe845c124d7062a73f83fe515366d9a8173 | [
"uncond_recodes = [self.schema_type_code_recoder, self.schema_build_id_recoder, self.tabblkst_recoder, self.tabblkcou_recoder, self.tabtractce_recoder, self.tabblkgrpce_recoder, self.tabblk_recoder]\nniu_fill_recodes = [self.rtype_hu_recoder, self.hh_status_recoder]\nfor recode in uncond_recodes:\n row = recode(... | <|body_start_0|>
uncond_recodes = [self.schema_type_code_recoder, self.schema_build_id_recoder, self.tabblkst_recoder, self.tabblkcou_recoder, self.tabtractce_recoder, self.tabblkgrpce_recoder, self.tabblk_recoder]
niu_fill_recodes = [self.rtype_hu_recoder, self.hh_status_recoder]
for recode in ... | H12020MDFHousehold2020Recoder | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_000774 | 22,269 | permissive | [
{
"docstring": "mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object",
"name": "recode",
"signature": "def recode(self, row, nullfill=False)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_val_001969 | Implement the Python class `H12020MDFHousehold2020Recoder` described below.
Class description:
Implement the H12020MDFHousehold2020Recoder class.
Method signatures and docstrings:
- def recode(self, row, nullfill=False): mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the req... | Implement the Python class `H12020MDFHousehold2020Recoder` described below.
Class description:
Implement the H12020MDFHousehold2020Recoder class.
Method signatures and docstrings:
- def recode(self, row, nullfill=False): mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the req... | 7f7ba44055da15d13b191180249e656e1bd398c6 | <|skeleton|>
class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class H12020MDFHousehold2020Recoder:
def recode(self, row, nullfill=False):
"""mapper for Row objects in spark dataframe recodes variables from hh2010 histogram spec to the requested mdf 2020 unit spec Inputs: row: dict - a dictionary representation of the Row object"""
uncond_recodes = [self.schema... | the_stack_v2_python_sparse | das_decennial/programs/writer/hh2010_to_mdfunit2020.py | p-b-j/uscb-das-container-public | train | 1 | |
a012dc598d81c079ed9c9eef4baa6286bc44c48d | [
"self.aaf_file = aaf_file\nself.compositionmob = self.aaf_file.create.CompositionMob()\nself.compositionmob.name = input_otio.name\nself.compositionmob.usage = 'Usage_TopLevel'\nself.aaf_file.content.mobs.append(self.compositionmob)\nself._unique_mastermobs = {}\nself._unique_tapemobs = {}\nself._clip_mob_ids_map =... | <|body_start_0|>
self.aaf_file = aaf_file
self.compositionmob = self.aaf_file.create.CompositionMob()
self.compositionmob.name = input_otio.name
self.compositionmob.usage = 'Usage_TopLevel'
self.aaf_file.content.mobs.append(self.compositionmob)
self._unique_mastermobs = {... | AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs. | AAFFileTranscriber | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AAFFileTranscriber:
"""AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs."""
def __init__(self, input_otio, aaf_file, **kwargs):
"""AAFFileTranscriber requires an ... | stack_v2_sparse_classes_75kplus_train_000775 | 30,972 | permissive | [
{
"docstring": "AAFFileTranscriber requires an input timeline and an output pyaaf2 file handle. Args: input_otio: an input OpenTimelineIO timeline aaf_file: a pyaaf2 file handle to an output file",
"name": "__init__",
"signature": "def __init__(self, input_otio, aaf_file, **kwargs)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_021225 | Implement the Python class `AAFFileTranscriber` described below.
Class description:
AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs.
Method signatures and docstrings:
- def __init__(self, input_o... | Implement the Python class `AAFFileTranscriber` described below.
Class description:
AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs.
Method signatures and docstrings:
- def __init__(self, input_o... | 45c6cfdd2013a270303af6d5ed82887c8d23affc | <|skeleton|>
class AAFFileTranscriber:
"""AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs."""
def __init__(self, input_otio, aaf_file, **kwargs):
"""AAFFileTranscriber requires an ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AAFFileTranscriber:
"""AAFFileTranscriber AAFFileTranscriber manages the file-level knowledge during a conversion from otio to aaf. This includes keeping track of unique tapemobs and mastermobs."""
def __init__(self, input_otio, aaf_file, **kwargs):
"""AAFFileTranscriber requires an input timelin... | the_stack_v2_python_sparse | contrib/opentimelineio_contrib/adapters/aaf_adapter/aaf_writer.py | darbyjohnston/OpenTimelineIO | train | 5 |
c1de5676394a7bed0cfb6384f3335e8de38f692c | [
"self.driver = None\n'\\n name of driver profile (configuration set) overrides it in config\\n '\nself.needs_login = False\n'\\n need to login ot not\\n '\nself.image_format = ImageFormat.JPEG\n'\\n image format\\n '\nself.sleep_time = 0.5\n'\\n duration for scrollin... | <|body_start_0|>
self.driver = None
'\n name of driver profile (configuration set) overrides it in config\n '
self.needs_login = False
'\n need to login ot not\n '
self.image_format = ImageFormat.JPEG
'\n image format\n '
... | AbstractSubConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractSubConfig:
def __init__(self):
"""represents config.json each site part."""
<|body_0|>
def update(self, data):
"""設定情報を更新する @param data 更新するデータ"""
<|body_1|>
def _set_image_format(self, format_):
"""書き出す画像のフォーマットを設定する 使用できるフォーマットは ImageFo... | stack_v2_sparse_classes_75kplus_train_000776 | 10,182 | no_license | [
{
"docstring": "represents config.json each site part.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "設定情報を更新する @param data 更新するデータ",
"name": "update",
"signature": "def update(self, data)"
},
{
"docstring": "書き出す画像のフォーマットを設定する 使用できるフォーマットは ImageFormat... | 4 | stack_v2_sparse_classes_30k_train_014245 | Implement the Python class `AbstractSubConfig` described below.
Class description:
Implement the AbstractSubConfig class.
Method signatures and docstrings:
- def __init__(self): represents config.json each site part.
- def update(self, data): 設定情報を更新する @param data 更新するデータ
- def _set_image_format(self, format_): 書き出す画... | Implement the Python class `AbstractSubConfig` described below.
Class description:
Implement the AbstractSubConfig class.
Method signatures and docstrings:
- def __init__(self): represents config.json each site part.
- def update(self, data): 設定情報を更新する @param data 更新するデータ
- def _set_image_format(self, format_): 書き出す画... | a43887e55a5484a813d944dce22e19ea3bec6c8c | <|skeleton|>
class AbstractSubConfig:
def __init__(self):
"""represents config.json each site part."""
<|body_0|>
def update(self, data):
"""設定情報を更新する @param data 更新するデータ"""
<|body_1|>
def _set_image_format(self, format_):
"""書き出す画像のフォーマットを設定する 使用できるフォーマットは ImageFo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractSubConfig:
def __init__(self):
"""represents config.json each site part."""
self.driver = None
'\n name of driver profile (configuration set) overrides it in config\n '
self.needs_login = False
'\n need to login ot not\n '
sel... | the_stack_v2_python_sparse | config.py | umjammer/K-AutoBook | train | 6 | |
c094e38f7723caa6ffa77bbe686b8da4e7580404 | [
"for v in g.graph[node]:\n g.graph[v].discard(node)\ndel g.graph[node]",
"res_values = [g.max_size_connected_component()]\nfor _ in range(g.number_of_nodes()):\n r = random.choice(list(g.graph.keys()))\n self.remove_node(g, r)\n res_values.append(g.max_size_connected_component())\nreturn res_values",
... | <|body_start_0|>
for v in g.graph[node]:
g.graph[v].discard(node)
del g.graph[node]
<|end_body_0|>
<|body_start_1|>
res_values = [g.max_size_connected_component()]
for _ in range(g.number_of_nodes()):
r = random.choice(list(g.graph.keys()))
self.remov... | Class that contains the attack functions used against the Graph | AttackGraphs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttackGraphs:
"""Class that contains the attack functions used against the Graph"""
def remove_node(self, g: Graph, node: int):
"""Removes the specified node from the graph g"""
<|body_0|>
def casual_attack(self, g: Graph):
""":return: Values of resilience of the... | stack_v2_sparse_classes_75kplus_train_000777 | 2,340 | no_license | [
{
"docstring": "Removes the specified node from the graph g",
"name": "remove_node",
"signature": "def remove_node(self, g: Graph, node: int)"
},
{
"docstring": ":return: Values of resilience of the graph g after disabling each node in a casual order",
"name": "casual_attack",
"signature... | 3 | stack_v2_sparse_classes_30k_train_028880 | Implement the Python class `AttackGraphs` described below.
Class description:
Class that contains the attack functions used against the Graph
Method signatures and docstrings:
- def remove_node(self, g: Graph, node: int): Removes the specified node from the graph g
- def casual_attack(self, g: Graph): :return: Values... | Implement the Python class `AttackGraphs` described below.
Class description:
Class that contains the attack functions used against the Graph
Method signatures and docstrings:
- def remove_node(self, g: Graph, node: int): Removes the specified node from the graph g
- def casual_attack(self, g: Graph): :return: Values... | 810cee78d865275b61e017bb82976b443245db10 | <|skeleton|>
class AttackGraphs:
"""Class that contains the attack functions used against the Graph"""
def remove_node(self, g: Graph, node: int):
"""Removes the specified node from the graph g"""
<|body_0|>
def casual_attack(self, g: Graph):
""":return: Values of resilience of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttackGraphs:
"""Class that contains the attack functions used against the Graph"""
def remove_node(self, g: Graph, node: int):
"""Removes the specified node from the graph g"""
for v in g.graph[node]:
g.graph[v].discard(node)
del g.graph[node]
def casual_attack(s... | the_stack_v2_python_sparse | LAB1/src/AttackGraph.py | linpengzhang/Algoritmi-Avanzati | train | 2 |
edcfa4fb6d8fadd34b0aaebbd74eb7c03aaf3ec9 | [
"self.opt = optimizer\nself.init_lr = init_lr\nself.lr_dacay_fact = lr_dacay_fact\nself.loss = 100000000.0\nself.patience = patience\nself.pat_count = 0\nself.lr = init_lr\nself.logger = logger\npass",
"self.lr = self.lr * self.lr_dacay_fact\nfor param_group in self.opt.param_groups:\n param_group['lr'] = self... | <|body_start_0|>
self.opt = optimizer
self.init_lr = init_lr
self.lr_dacay_fact = lr_dacay_fact
self.loss = 100000000.0
self.patience = patience
self.pat_count = 0
self.lr = init_lr
self.logger = logger
pass
<|end_body_0|>
<|body_start_1|>
... | utils functions to manipulate the learning rate | LearningRate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningRate:
"""utils functions to manipulate the learning rate"""
def __init__(self, optimizer, init_lr=0.001, lr_dacay_fact=0.2, patience=10, logger=None):
""":param logger: Logger to output stuff into file. :param optimizer: Object of the torch optimizer initialized before :param... | stack_v2_sparse_classes_75kplus_train_000778 | 1,951 | permissive | [
{
"docstring": ":param logger: Logger to output stuff into file. :param optimizer: Object of the torch optimizer initialized before :param init_lr: Start lr :param lr_decay_epoch: Epchs after which the learning rate to be decayed :param lr_dacay_fact: Factor by which lr to be decayed :param patience: Number of ... | 3 | stack_v2_sparse_classes_30k_test_000592 | Implement the Python class `LearningRate` described below.
Class description:
utils functions to manipulate the learning rate
Method signatures and docstrings:
- def __init__(self, optimizer, init_lr=0.001, lr_dacay_fact=0.2, patience=10, logger=None): :param logger: Logger to output stuff into file. :param optimizer... | Implement the Python class `LearningRate` described below.
Class description:
utils functions to manipulate the learning rate
Method signatures and docstrings:
- def __init__(self, optimizer, init_lr=0.001, lr_dacay_fact=0.2, patience=10, logger=None): :param logger: Logger to output stuff into file. :param optimizer... | 459ba6a49635badcf0fa50555c69dbcb3912eb0a | <|skeleton|>
class LearningRate:
"""utils functions to manipulate the learning rate"""
def __init__(self, optimizer, init_lr=0.001, lr_dacay_fact=0.2, patience=10, logger=None):
""":param logger: Logger to output stuff into file. :param optimizer: Object of the torch optimizer initialized before :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LearningRate:
"""utils functions to manipulate the learning rate"""
def __init__(self, optimizer, init_lr=0.001, lr_dacay_fact=0.2, patience=10, logger=None):
""":param logger: Logger to output stuff into file. :param optimizer: Object of the torch optimizer initialized before :param init_lr: Sta... | the_stack_v2_python_sparse | src/utils/learn_utils.py | adrelino/CSGNet | train | 1 |
3b04049720fe498660852dba601dd009fd91e225 | [
"d = {}\nmaxl = 0\nfor n in nums:\n if n not in d:\n l = n if n - 1 not in d else d[n - 1][0]\n r = n if n + 1 not in d else d[n + 1][1]\n d[l] = (l, r)\n d[r] = (l, r)\n d[n] = (l, r)\n tmp_l = r - l + 1\n if tmp_l > maxl:\n maxl = tmp_l\nreturn maxl",... | <|body_start_0|>
d = {}
maxl = 0
for n in nums:
if n not in d:
l = n if n - 1 not in d else d[n - 1][0]
r = n if n + 1 not in d else d[n + 1][1]
d[l] = (l, r)
d[r] = (l, r)
d[n] = (l, r)
t... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {}
maxl = 0
... | stack_v2_sparse_classes_75kplus_train_000779 | 1,360 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive_v1",
"signature": "def longestConsecutive_v1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037499 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive_v1(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive_v1(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 2a29426be1d690b6f90bc45b437900deee46d832 | <|skeleton|>
class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestConsecutive_v1(self, nums):
""":type nums: List[int] :rtype: int"""
d = {}
maxl = 0
for n in nums:
if n not in d:
l = n if n - 1 not in d else d[n - 1][0]
r = n if n + 1 not in d else d[n + 1][1]
d... | the_stack_v2_python_sparse | src/leet/Longest Consecutive Sequence.py | sevenseablue/leetcode | train | 0 | |
880e51b5965f8ff091f449f2926c88927e1be818 | [
"ObjectManager.__init__(self)\nself.setters.update({'organization': 'set_foreign_key', 'user': 'set_foreign_key', 'starting_value': 'set_general'})\nself.getters.update({'balance': 'get_balance_from_training_unit_account', 'organization': 'get_foreign_key', 'user': 'get_foreign_key', 'training_unit_transactions': '... | <|body_start_0|>
ObjectManager.__init__(self)
self.setters.update({'organization': 'set_foreign_key', 'user': 'set_foreign_key', 'starting_value': 'set_general'})
self.getters.update({'balance': 'get_balance_from_training_unit_account', 'organization': 'get_foreign_key', 'user': 'get_foreign_key... | Manage TrainingUnitAccounts in the Power Reg system | TrainingUnitAccountManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingUnitAccountManager:
"""Manage TrainingUnitAccounts in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, user=None, organization=None):
"""Create a new TrainingUnitAccount @param user User associated with... | stack_v2_sparse_classes_75kplus_train_000780 | 2,052 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new TrainingUnitAccount @param user User associated with this account. Mutually exclusive with company. @param organization organization associated with this account. Mutually exclusiv... | 2 | stack_v2_sparse_classes_30k_train_001349 | Implement the Python class `TrainingUnitAccountManager` described below.
Class description:
Manage TrainingUnitAccounts in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, user=None, organization=None): Create a new TrainingUnitAccount @param user... | Implement the Python class `TrainingUnitAccountManager` described below.
Class description:
Manage TrainingUnitAccounts in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, user=None, organization=None): Create a new TrainingUnitAccount @param user... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class TrainingUnitAccountManager:
"""Manage TrainingUnitAccounts in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, user=None, organization=None):
"""Create a new TrainingUnitAccount @param user User associated with... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainingUnitAccountManager:
"""Manage TrainingUnitAccounts in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.setters.update({'organization': 'set_foreign_key', 'user': 'set_foreign_key', 'starting_value': 'set_general'})
sel... | the_stack_v2_python_sparse | pr_services/product_system/training_unit_account_manager.py | ninemoreminutes/openassign-server | train | 0 |
e94cafe2da0a691b8a5ea4c6f1a9034643ed3995 | [
"self.d = defaultdict(list)\nfor i, v in enumerate(words):\n self.d[v].append(i)",
"list1 = self.d[word1]\nlist2 = self.d[word2]\ni, j, res = (0, 0, float('inf'))\nwhile i < len(list1) and j < len(list2):\n res = min(res, abs(list1[i] - list2[j]))\n if list1[i] < list2[j]:\n i += 1\n else:\n ... | <|body_start_0|>
self.d = defaultdict(list)
for i, v in enumerate(words):
self.d[v].append(i)
<|end_body_0|>
<|body_start_1|>
list1 = self.d[word1]
list2 = self.d[word2]
i, j, res = (0, 0, float('inf'))
while i < len(list1) and j < len(list2):
res... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_000781 | 1,001 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_val_000706 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 036a29d681cc91f2317d454e04530d7375d55478 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.d = defaultdict(list)
for i, v in enumerate(words):
self.d[v].append(i)
def shortest(self, word1, word2):
"""Adds a word into the data structure. :ty... | the_stack_v2_python_sparse | leetcode/shortest_word_distance_ii_v1.py | myliu/python-algorithm | train | 0 | |
c6c91aaf3aa5341017777ff8955ed8e7aa15d56a | [
"self.cache_root = self._help_cache(cache_root)\nself.training_url = training_url\nself.testing_url = testing_url\nself.validation_url = validation_url\ntraining_path = os.path.join(self.cache_root, name_from_url(self.training_url))\ntesting_path = os.path.join(self.cache_root, name_from_url(self.testing_url))\nval... | <|body_start_0|>
self.cache_root = self._help_cache(cache_root)
self.training_url = training_url
self.testing_url = testing_url
self.validation_url = validation_url
training_path = os.path.join(self.cache_root, name_from_url(self.training_url))
testing_path = os.path.join... | A dataset with all three of train, test, and validation sets as URLs. | UnpackedRemoteDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnpackedRemoteDataset:
"""A dataset with all three of train, test, and validation sets as URLs."""
def __init__(self, training_url: str, testing_url: str, validation_url: str, cache_root: Optional[str]=None, stream: bool=True, force: bool=False, eager: bool=False, create_inverse_triples: boo... | stack_v2_sparse_classes_75kplus_train_000782 | 9,907 | permissive | [
{
"docstring": "Initialize dataset. :param training_url: The URL of the training file :param testing_url: The URL of the testing file :param validation_url: The URL of the validation file :param cache_root: An optional directory to store the extracted files. Is none is given, the default PyKEEN directory is use... | 2 | stack_v2_sparse_classes_30k_train_012368 | Implement the Python class `UnpackedRemoteDataset` described below.
Class description:
A dataset with all three of train, test, and validation sets as URLs.
Method signatures and docstrings:
- def __init__(self, training_url: str, testing_url: str, validation_url: str, cache_root: Optional[str]=None, stream: bool=Tru... | Implement the Python class `UnpackedRemoteDataset` described below.
Class description:
A dataset with all three of train, test, and validation sets as URLs.
Method signatures and docstrings:
- def __init__(self, training_url: str, testing_url: str, validation_url: str, cache_root: Optional[str]=None, stream: bool=Tru... | d731c9990cdd7835f01f129f6134c3bff576821f | <|skeleton|>
class UnpackedRemoteDataset:
"""A dataset with all three of train, test, and validation sets as URLs."""
def __init__(self, training_url: str, testing_url: str, validation_url: str, cache_root: Optional[str]=None, stream: bool=True, force: bool=False, eager: bool=False, create_inverse_triples: boo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnpackedRemoteDataset:
"""A dataset with all three of train, test, and validation sets as URLs."""
def __init__(self, training_url: str, testing_url: str, validation_url: str, cache_root: Optional[str]=None, stream: bool=True, force: bool=False, eager: bool=False, create_inverse_triples: bool=False, load... | the_stack_v2_python_sparse | lp_rp/datasets/codex.py | yunnant/NodePiece | train | 0 |
738d15e91470f60a7aa6f79c68e942a0821b8d39 | [
"super().__init__()\nself.image = pygame.Surface([width, height])\nself.image.fill(color)\nself.rect = self.image.get_rect()\nself.left_boundary = 0\nself.right_boundary = 0\nself.top_boundary = 0\nself.bottom_boundary = 0\nself.change_x = 0\nself.change_y = 0",
"self.rect.x += self.change_x\nself.rect.y += self.... | <|body_start_0|>
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.left_boundary = 0
self.right_boundary = 0
self.top_boundary = 0
self.bottom_boundary = 0
self.change_x = ... | This class represents the ball It derives from the "Sprite" class in Pygame | Block | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block:
"""This class represents the ball It derives from the "Sprite" class in Pygame"""
def __init__(self, color, width, height):
"""Constructor. Pass in the color of the block, and its x and y position."""
<|body_0|>
def update(self):
"""Called each frame."""
... | stack_v2_sparse_classes_75kplus_train_000783 | 11,661 | no_license | [
{
"docstring": "Constructor. Pass in the color of the block, and its x and y position.",
"name": "__init__",
"signature": "def __init__(self, color, width, height)"
},
{
"docstring": "Called each frame.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001499 | Implement the Python class `Block` described below.
Class description:
This class represents the ball It derives from the "Sprite" class in Pygame
Method signatures and docstrings:
- def __init__(self, color, width, height): Constructor. Pass in the color of the block, and its x and y position.
- def update(self): Ca... | Implement the Python class `Block` described below.
Class description:
This class represents the ball It derives from the "Sprite" class in Pygame
Method signatures and docstrings:
- def __init__(self, color, width, height): Constructor. Pass in the color of the block, and its x and y position.
- def update(self): Ca... | 31aa808a5516e653a1e06dec53b4cb74bd820c00 | <|skeleton|>
class Block:
"""This class represents the ball It derives from the "Sprite" class in Pygame"""
def __init__(self, color, width, height):
"""Constructor. Pass in the color of the block, and its x and y position."""
<|body_0|>
def update(self):
"""Called each frame."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Block:
"""This class represents the ball It derives from the "Sprite" class in Pygame"""
def __init__(self, color, width, height):
"""Constructor. Pass in the color of the block, and its x and y position."""
super().__init__()
self.image = pygame.Surface([width, height])
s... | the_stack_v2_python_sparse | sp18_student_games/Natalie Shark Attack/Natlie Sharks.py | fwparkercode/IntroGames | train | 0 |
de5dae48e9d33ffb3866149b035b6f176caa6e46 | [
"m = len(matrix)\nn = len(matrix[0])\ndp = [[0 for _ in range(n)] for _ in range(m)]\nres = 0\nfor i in range(m):\n for j in range(n):\n if i == 0 or j == 0:\n dp[i][j] = 1 if matrix[i][j] == '1' else 0\n elif matrix[i][j] == '1':\n dp[i][j] = min(dp[i - 1][j - 1], dp[i][j - 1... | <|body_start_0|>
m = len(matrix)
n = len(matrix[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
if i == 0 or j == 0:
dp[i][j] = 1 if matrix[i][j] == '1' else 0
elif ma... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquareOnSpace(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(matrix... | stack_v2_sparse_classes_75kplus_train_000784 | 2,505 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquareOnSpace",
"signature": "def maximalSquareOnSpace(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016250 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquareOnSpace(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquareOnSpace(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquareOnSpace(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
m = len(matrix)
n = len(matrix[0])
dp = [[0 for _ in range(n)] for _ in range(m)]
res = 0
for i in range(m):
for j in range(n):
if i == 0 or j ... | the_stack_v2_python_sparse | M/MaximalSquare.py | bssrdf/pyleet | train | 2 | |
21b1bf619c13b19da9f978086cdcbf5a690e4fd5 | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise TypeError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns\nif n_components is not None:\n if isinstance(n_components, int):\n self... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
if n_compone... | PCA_selector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA_selector:
def __init__(self, columns=None, n_components=2, random_state=99):
"""Init log PCA_selector."""
<|body_0|>
def fit(self, X, y=None):
"""Selecting PCA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Datafr... | stack_v2_sparse_classes_75kplus_train_000785 | 11,211 | permissive | [
{
"docstring": "Init log PCA_selector.",
"name": "__init__",
"signature": "def __init__(self, columns=None, n_components=2, random_state=99)"
},
{
"docstring": "Selecting PCA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_sampl... | 3 | stack_v2_sparse_classes_30k_train_024652 | Implement the Python class `PCA_selector` described below.
Class description:
Implement the PCA_selector class.
Method signatures and docstrings:
- def __init__(self, columns=None, n_components=2, random_state=99): Init log PCA_selector.
- def fit(self, X, y=None): Selecting PCA columns from the dataset. Parameters -... | Implement the Python class `PCA_selector` described below.
Class description:
Implement the PCA_selector class.
Method signatures and docstrings:
- def __init__(self, columns=None, n_components=2, random_state=99): Init log PCA_selector.
- def fit(self, X, y=None): Selecting PCA columns from the dataset. Parameters -... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class PCA_selector:
def __init__(self, columns=None, n_components=2, random_state=99):
"""Init log PCA_selector."""
<|body_0|>
def fit(self, X, y=None):
"""Selecting PCA columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Datafr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PCA_selector:
def __init__(self, columns=None, n_components=2, random_state=99):
"""Init log PCA_selector."""
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError... | the_stack_v2_python_sparse | mlearner/preprocessing/reduce_feature.py | jaisenbe58r/MLearner | train | 9 | |
3e89c67fd1334cf40c3f3d8a7745a88fc320a1b8 | [
"super().__init__(*args, **kwargs)\nif 'obj' in kwargs:\n self.condition_id.data = kwargs['obj'].id\nself.is_leader.choices = [('', 'Encadrant ou Participant'), (False, 'Participant'), (True, 'Encadrant')]",
"if self.event_id.data:\n return Event.query.get(self.event_id.data)\nreturn None"
] | <|body_start_0|>
super().__init__(*args, **kwargs)
if 'obj' in kwargs:
self.condition_id.data = kwargs['obj'].id
self.is_leader.choices = [('', 'Encadrant ou Participant'), (False, 'Participant'), (True, 'Encadrant')]
<|end_body_0|>
<|body_start_1|>
if self.event_id.data:
... | Form for creating event conditions in user group forms | GroupEventConditionForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupEventConditionForm:
"""Form for creating event conditions in user group forms"""
def __init__(self, *args, **kwargs):
"""Overloaded constructor"""
<|body_0|>
def event(self) -> Optional[Event]:
""":returns: the event associated with the condition"""
... | stack_v2_sparse_classes_75kplus_train_000786 | 8,270 | no_license | [
{
"docstring": "Overloaded constructor",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": ":returns: the event associated with the condition",
"name": "event",
"signature": "def event(self) -> Optional[Event]"
}
] | 2 | null | Implement the Python class `GroupEventConditionForm` described below.
Class description:
Form for creating event conditions in user group forms
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overloaded constructor
- def event(self) -> Optional[Event]: :returns: the event associated with the ... | Implement the Python class `GroupEventConditionForm` described below.
Class description:
Form for creating event conditions in user group forms
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overloaded constructor
- def event(self) -> Optional[Event]: :returns: the event associated with the ... | 1ae05ae9029a28fd0656c06a2092f67a87a93dcd | <|skeleton|>
class GroupEventConditionForm:
"""Form for creating event conditions in user group forms"""
def __init__(self, *args, **kwargs):
"""Overloaded constructor"""
<|body_0|>
def event(self) -> Optional[Event]:
""":returns: the event associated with the condition"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupEventConditionForm:
"""Form for creating event conditions in user group forms"""
def __init__(self, *args, **kwargs):
"""Overloaded constructor"""
super().__init__(*args, **kwargs)
if 'obj' in kwargs:
self.condition_id.data = kwargs['obj'].id
self.is_leade... | the_stack_v2_python_sparse | collectives/forms/user_group.py | Club-Alpin-Annecy/collectives | train | 12 |
30ed9cbbe4ffdbe540d1303fd0678959e10bb09d | [
"if args.weekday not in consts.WEEKDAYS:\n raise ValueError('Wrong value of weekday.')\nif not re.match('^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$', args.time):\n raise ValueError('Wrong format of time.')\napi.add_meeting(consts.WEEKDAYS.index(args.weekday), args.time)",
"meetings = api.get_meetings()\nif... | <|body_start_0|>
if args.weekday not in consts.WEEKDAYS:
raise ValueError('Wrong value of weekday.')
if not re.match('^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$', args.time):
raise ValueError('Wrong format of time.')
api.add_meeting(consts.WEEKDAYS.index(args.weekday), a... | Meeting | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meeting:
def add(self, api, args):
"""Add meeting."""
<|body_0|>
def list(self, api, args):
"""Show all meetings"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if args.weekday not in consts.WEEKDAYS:
raise ValueError('Wrong value of wee... | stack_v2_sparse_classes_75kplus_train_000787 | 1,786 | permissive | [
{
"docstring": "Add meeting.",
"name": "add",
"signature": "def add(self, api, args)"
},
{
"docstring": "Show all meetings",
"name": "list",
"signature": "def list(self, api, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004180 | Implement the Python class `Meeting` described below.
Class description:
Implement the Meeting class.
Method signatures and docstrings:
- def add(self, api, args): Add meeting.
- def list(self, api, args): Show all meetings | Implement the Python class `Meeting` described below.
Class description:
Implement the Meeting class.
Method signatures and docstrings:
- def add(self, api, args): Add meeting.
- def list(self, api, args): Show all meetings
<|skeleton|>
class Meeting:
def add(self, api, args):
"""Add meeting."""
... | 329ff19074dacf9d84de4947f44de414039d423b | <|skeleton|>
class Meeting:
def add(self, api, args):
"""Add meeting."""
<|body_0|>
def list(self, api, args):
"""Show all meetings"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Meeting:
def add(self, api, args):
"""Add meeting."""
if args.weekday not in consts.WEEKDAYS:
raise ValueError('Wrong value of weekday.')
if not re.match('^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$', args.time):
raise ValueError('Wrong format of time.')
... | the_stack_v2_python_sparse | mlm/commands/meeting.py | andreykurilin/mlm | train | 1 | |
efbd14ddf746b8e02f333883b45079b4c14fb174 | [
"self.searchResults = searchResults\nself.keywords = keywords\nself.originalSearchResults = originalSearchResults",
"results = {}\nfor result in self.searchResults:\n results[result['url']] = result\nscoredResults = {}\nfor entityId in self.originalSearchResults:\n for query in self.originalSearchResults[en... | <|body_start_0|>
self.searchResults = searchResults
self.keywords = keywords
self.originalSearchResults = originalSearchResults
<|end_body_0|>
<|body_start_1|>
results = {}
for result in self.searchResults:
results[result['url']] = result
scoredResults = {}
... | Represents a baseline ranking of the original search results. | BaselineRanking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format:... | stack_v2_sparse_classes_75kplus_train_000788 | 4,766 | no_license | [
{
"docstring": "Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format: [ { 'url': <url> 'preview' : <preview snippet> 'title' : <title> 'description' : <meta description> 'pageRank' : <PageRank, between 0 and 10> 'content' : <page content... | 2 | stack_v2_sparse_classes_30k_train_024081 | Implement the Python class `BaselineRanking` described below.
Class description:
Represents a baseline ranking of the original search results.
Method signatures and docstrings:
- def __init__(self, searchResults, keywords, originalSearchResults): Creates a ranking object with the necessary parameters @param searchRes... | Implement the Python class `BaselineRanking` described below.
Class description:
Represents a baseline ranking of the original search results.
Method signatures and docstrings:
- def __init__(self, searchResults, keywords, originalSearchResults): Creates a ranking object with the necessary parameters @param searchRes... | d702e132994ccfb6fe51a82635d33d67c3a74f81 | <|skeleton|>
class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaselineRanking:
"""Represents a baseline ranking of the original search results."""
def __init__(self, searchResults, keywords, originalSearchResults):
"""Creates a ranking object with the necessary parameters @param searchResults The list of search results, in the following format: [ { 'url': <... | the_stack_v2_python_sparse | src/ranking/BaselineRanking.py | jtedesco/EntityQuerier | train | 1 |
04b8b7e308e105dc0f8b14daa97a0b2ccce1cc55 | [
"res = ACCOUNT.read(_id)\nif not res:\n API.abort(400, 'Conta não encontrada', status={'id': _id}, statusCode='404')\nreturn res",
"res = ACCOUNT.delete(_id)\nif not res:\n API.abort(400, 'Conta não encontrado', status={'id': _id}, statusCode='404')\nreturn ('Conta apagada com sucesso!', 204)",
"res = ACC... | <|body_start_0|>
res = ACCOUNT.read(_id)
if not res:
API.abort(400, 'Conta não encontrada', status={'id': _id}, statusCode='404')
return res
<|end_body_0|>
<|body_start_1|>
res = ACCOUNT.delete(_id)
if not res:
API.abort(400, 'Conta não encontrado', statu... | Exibe um conta e permite a manipulação do mesmo | AccountItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountItem:
"""Exibe um conta e permite a manipulação do mesmo"""
def get(self, _id):
"""Exibe um conta dado seu identificador"""
<|body_0|>
def delete(self, _id):
"""Apaga um conta dado seu identificador"""
<|body_1|>
def put(self, _id):
""... | stack_v2_sparse_classes_75kplus_train_000789 | 4,940 | no_license | [
{
"docstring": "Exibe um conta dado seu identificador",
"name": "get",
"signature": "def get(self, _id)"
},
{
"docstring": "Apaga um conta dado seu identificador",
"name": "delete",
"signature": "def delete(self, _id)"
},
{
"docstring": "Atualiza um conta dado seu identificador",... | 3 | stack_v2_sparse_classes_30k_train_039317 | Implement the Python class `AccountItem` described below.
Class description:
Exibe um conta e permite a manipulação do mesmo
Method signatures and docstrings:
- def get(self, _id): Exibe um conta dado seu identificador
- def delete(self, _id): Apaga um conta dado seu identificador
- def put(self, _id): Atualiza um co... | Implement the Python class `AccountItem` described below.
Class description:
Exibe um conta e permite a manipulação do mesmo
Method signatures and docstrings:
- def get(self, _id): Exibe um conta dado seu identificador
- def delete(self, _id): Apaga um conta dado seu identificador
- def put(self, _id): Atualiza um co... | edd013ba57469a9a20956187a2e980048862f800 | <|skeleton|>
class AccountItem:
"""Exibe um conta e permite a manipulação do mesmo"""
def get(self, _id):
"""Exibe um conta dado seu identificador"""
<|body_0|>
def delete(self, _id):
"""Apaga um conta dado seu identificador"""
<|body_1|>
def put(self, _id):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountItem:
"""Exibe um conta e permite a manipulação do mesmo"""
def get(self, _id):
"""Exibe um conta dado seu identificador"""
res = ACCOUNT.read(_id)
if not res:
API.abort(400, 'Conta não encontrada', status={'id': _id}, statusCode='404')
return res
d... | the_stack_v2_python_sparse | app/mod_account/api.py | felipetac/flask-restplus-started | train | 0 |
f5d80cc6a801e905af28630f91ba6ad41eb5e76c | [
"if not self.rig.node().hasAttr('shapeInfo'):\n self.rig.node().addAttr('shapeInfo', dt='string')\n self.rig.node().shapeInfo.set('{}')\nif not self.rig.built_successfully():\n return\ndata_sets = list()\nfor node in self.rig.control_org().getChildren(ad=True, type='transform'):\n if node.name().startsw... | <|body_start_0|>
if not self.rig.node().hasAttr('shapeInfo'):
self.rig.node().addAttr('shapeInfo', dt='string')
self.rig.node().shapeInfo.set('{}')
if not self.rig.built_successfully():
return
data_sets = list()
for node in self.rig.control_org().getCh... | This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply the sames post build. This mechanism allows a rigger to make control shape adjustme... | ShapeStoreProcess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeStoreProcess:
"""This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply the sames post build. This mechanism a... | stack_v2_sparse_classes_75kplus_train_000790 | 5,865 | permissive | [
{
"docstring": "This is called before the control rig is destroyed, so we will store all the control information here. :return:",
"name": "snapshot",
"signature": "def snapshot(self)"
},
{
"docstring": "This is called after the entire rig has been built, so we will attempt to re-apply the shape ... | 2 | stack_v2_sparse_classes_30k_train_042926 | Implement the Python class `ShapeStoreProcess` described below.
Class description:
This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply... | Implement the Python class `ShapeStoreProcess` described below.
Class description:
This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply... | 5b034fc76150dcc613e69d08d0d807c5461c265b | <|skeleton|>
class ShapeStoreProcess:
"""This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply the sames post build. This mechanism a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShapeStoreProcess:
"""This is an example only plugin showing what a process plugin might be used for. In this case, we're going to snapshot all the NurbsCurve shape nodes within the rig and store that information in a string attribute allowing us to re-apply the sames post build. This mechanism allows a rigge... | the_stack_v2_python_sparse | crab/plugins/processes/shapes.py | mikemalinowski/crab | train | 25 |
78e74a54ba8756cb8186c9fe3d944395bea4634a | [
"adv_neighbor = np.array([1.0, 1.0, 1.0, 0.0, 1.0])\ntarget = np.array([1.0, 1.0, 1.0, 1.0, 1.0])\nadv_loss = regularizer.adv_regularizer(tf.constant(adv_neighbor), tf.constant(target), mock_model_fn, mock_loss_fn)\nactual_loss = self.evaluate(adv_loss)\nself.assertNear(actual_loss, np.sum((adv_neighbor - target) *... | <|body_start_0|>
adv_neighbor = np.array([1.0, 1.0, 1.0, 0.0, 1.0])
target = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
adv_loss = regularizer.adv_regularizer(tf.constant(adv_neighbor), tf.constant(target), mock_model_fn, mock_loss_fn)
actual_loss = self.evaluate(adv_loss)
self.assertNe... | Tests regularizer methods. | RegularizerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegularizerTest:
"""Tests regularizer methods."""
def testAdvRegularizer(self):
"""Tests adv_regularizer returns expected adv_loss."""
<|body_0|>
def testVirtualAdvRegularizer(self):
"""Tests virtual_adv_regularizer returning expected loss."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_000791 | 6,204 | permissive | [
{
"docstring": "Tests adv_regularizer returns expected adv_loss.",
"name": "testAdvRegularizer",
"signature": "def testAdvRegularizer(self)"
},
{
"docstring": "Tests virtual_adv_regularizer returning expected loss.",
"name": "testVirtualAdvRegularizer",
"signature": "def testVirtualAdvRe... | 5 | stack_v2_sparse_classes_30k_train_053991 | Implement the Python class `RegularizerTest` described below.
Class description:
Tests regularizer methods.
Method signatures and docstrings:
- def testAdvRegularizer(self): Tests adv_regularizer returns expected adv_loss.
- def testVirtualAdvRegularizer(self): Tests virtual_adv_regularizer returning expected loss.
-... | Implement the Python class `RegularizerTest` described below.
Class description:
Tests regularizer methods.
Method signatures and docstrings:
- def testAdvRegularizer(self): Tests adv_regularizer returns expected adv_loss.
- def testVirtualAdvRegularizer(self): Tests virtual_adv_regularizer returning expected loss.
-... | 995064233479e806a3187ede8a395319520db75e | <|skeleton|>
class RegularizerTest:
"""Tests regularizer methods."""
def testAdvRegularizer(self):
"""Tests adv_regularizer returns expected adv_loss."""
<|body_0|>
def testVirtualAdvRegularizer(self):
"""Tests virtual_adv_regularizer returning expected loss."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegularizerTest:
"""Tests regularizer methods."""
def testAdvRegularizer(self):
"""Tests adv_regularizer returns expected adv_loss."""
adv_neighbor = np.array([1.0, 1.0, 1.0, 0.0, 1.0])
target = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
adv_loss = regularizer.adv_regularizer(tf.... | the_stack_v2_python_sparse | neural_structured_learning/lib/regularizer_test.py | RubensZimbres/neural-structured-learning | train | 1 |
5a866f7ed3243b014c36d9fffeec10b9cd2b94f3 | [
"if db_field.name == 'author':\n kwargs['initial'] = request.user.id\nreturn super().formfield_for_foreignkey(db_field, request, **kwargs)",
"try:\n profile = Profile.objects.get(user=request.user)\nexcept Profile.DoesNotExist:\n if request.user.is_superuser:\n return Mark.objects.all()\nif profil... | <|body_start_0|>
if db_field.name == 'author':
kwargs['initial'] = request.user.id
return super().formfield_for_foreignkey(db_field, request, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExi... | MarksAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarksAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Set default teacher"""
<|body_0|>
def get_queryset(self, request):
"""Get all marks for current profile"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if db_field.name ... | stack_v2_sparse_classes_75kplus_train_000792 | 2,628 | no_license | [
{
"docstring": "Set default teacher",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Get all marks for current profile",
"name": "get_queryset",
"signature": "def get_queryset(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038709 | Implement the Python class `MarksAdmin` described below.
Class description:
Implement the MarksAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher
- def get_queryset(self, request): Get all marks for current profile | Implement the Python class `MarksAdmin` described below.
Class description:
Implement the MarksAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher
- def get_queryset(self, request): Get all marks for current profile
<|skeleton|>
class ... | 76c0df6f07f41f4baf7346acdbbf316b4dd13ee5 | <|skeleton|>
class MarksAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Set default teacher"""
<|body_0|>
def get_queryset(self, request):
"""Get all marks for current profile"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MarksAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Set default teacher"""
if db_field.name == 'author':
kwargs['initial'] = request.user.id
return super().formfield_for_foreignkey(db_field, request, **kwargs)
def get_queryset(self, request)... | the_stack_v2_python_sparse | journal/admin.py | HallrizonX/api_chpk | train | 3 | |
7d260fc3f3b9de7d635f8b1acfd65fbd72ca8f14 | [
"super().__init__()\nself._h = h\nself._attention_size = attention_size\nself._W_q = nn.Linear(d_model, q * self._h)\nself._W_k = nn.Linear(d_model, q * self._h)\nself._W_v = nn.Linear(d_model, v * self._h)\nself._W_o = nn.Linear(self._h * v, d_model)\nself._scores = None",
"K = query.shape[1]\nqueries = torch.ca... | <|body_start_0|>
super().__init__()
self._h = h
self._attention_size = attention_size
self._W_q = nn.Linear(d_model, q * self._h)
self._W_k = nn.Linear(d_model, q * self._h)
self._W_v = nn.Linear(d_model, v * self._h)
self._W_o = nn.Linear(self._h * v, d_model)
... | Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Parameters ---------- d_model: Dimension of the input vector. q: Dimension of all query m... | MultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Parameters ---------- d_model: Dimension of... | stack_v2_sparse_classes_75kplus_train_000793 | 13,552 | permissive | [
{
"docstring": "Initialize the Multi Head Block.",
"name": "__init__",
"signature": "def __init__(self, d_model: int, q: int, v: int, h: int, attention_size: int=None)"
},
{
"docstring": "Propagate forward the input through the MHB. We compute for each head the queries, keys and values matrices,... | 3 | stack_v2_sparse_classes_30k_train_019001 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Para... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Para... | 0b801d2d2e828ac480d1097cb3bdd82b1e25c15b | <|skeleton|>
class MultiHeadAttention:
"""Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Parameters ---------- d_model: Dimension of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
"""Multi Head Attention block from Attention is All You Need. Given 3 inputs of shape (batch_size, K, d_model), that will be used to compute query, keys and values, we output a self attention tensor of shape (batch_size, K, d_model). Parameters ---------- d_model: Dimension of the input ve... | the_stack_v2_python_sparse | code/deep/adarnn/tst/multiHeadAttention.py | jindongwang/transferlearning | train | 12,773 |
be60462247490fb00bbb1160ce97bfb57c6bb00d | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\ninit_hi... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_bod... | RNN Encoder class | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int)... | stack_v2_sparse_classes_75kplus_train_000794 | 2,215 | no_license | [
{
"docstring": "Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int): the batch size.",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, unit... | 3 | stack_v2_sparse_classes_30k_train_026829 | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (... | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""RNN Encoder class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the input vocabulary. embedding (int): dimensionality of the embedding vector. units (int): number of hidden units in the RNN cell. batch (int): the batch s... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
6a0ffe02ae5f97cef4054f4e0f3c2740bb190ffe | [
"queryset = self.get_queryset().values_list('userid', flat=True)\npage = self.paginate_queryset(queryset)\nif page is not None:\n return self.get_paginated_response({'userid': page})\nserializer = self.get_serializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = self.queryset\nuser = get... | <|body_start_0|>
queryset = self.get_queryset().values_list('userid', flat=True)
page = self.paginate_queryset(queryset)
if page is not None:
return self.get_paginated_response({'userid': page})
serializer = self.get_serializer(queryset, many=True)
return Response(ser... | ViewSet for /api/users/ | UserViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
"""ViewSet for /api/users/"""
def list(self, request):
"""List users."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get one user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = self.get_queryset().values_list('u... | stack_v2_sparse_classes_75kplus_train_000795 | 4,903 | no_license | [
{
"docstring": "List users.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Get one user.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024609 | Implement the Python class `UserViewSet` described below.
Class description:
ViewSet for /api/users/
Method signatures and docstrings:
- def list(self, request): List users.
- def retrieve(self, request, pk=None): Get one user. | Implement the Python class `UserViewSet` described below.
Class description:
ViewSet for /api/users/
Method signatures and docstrings:
- def list(self, request): List users.
- def retrieve(self, request, pk=None): Get one user.
<|skeleton|>
class UserViewSet:
"""ViewSet for /api/users/"""
def list(self, req... | a8593884641b3aa1411260d0be572dde7ae0ae58 | <|skeleton|>
class UserViewSet:
"""ViewSet for /api/users/"""
def list(self, request):
"""List users."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get one user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserViewSet:
"""ViewSet for /api/users/"""
def list(self, request):
"""List users."""
queryset = self.get_queryset().values_list('userid', flat=True)
page = self.paginate_queryset(queryset)
if page is not None:
return self.get_paginated_response({'userid': page... | the_stack_v2_python_sparse | rest/rest/api/views.py | ucb-rit/mybrc-not-user-portal | train | 0 |
7bc476d9def287da9ea035bb6aba2aa17d8691f3 | [
"Frame.__init__(self, master)\nself.pack()\nself.createWidgets()",
"main_frame = Frame(self)\nLabel(main_frame, text='Please input a county').pack()\nself.text_in = Entry(main_frame)\nself.text_in.insert('end', 'Kent')\nself.text_in.pack()\nself.btn_go = Button(main_frame, text='GO!', command=self.handler)\nself.... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createWidgets()
<|end_body_0|>
<|body_start_1|>
main_frame = Frame(self)
Label(main_frame, text='Please input a county').pack()
self.text_in = Entry(main_frame)
self.text_in.insert('end', 'Kent')
... | Application main window class. | Application | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handler(self):
... | stack_v2_sparse_classes_75kplus_train_000796 | 1,927 | permissive | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createWidgets",
"signature": "def createWidgets(self)"
},
{
"docstring": "Runs a ... | 3 | stack_v2_sparse_classes_30k_train_020747 | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handler(self): Runs a db... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handler(self): Runs a db... | a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handler(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
"""Add all the widgets to the main fram... | the_stack_v2_python_sparse | dkr-py310/docker-student-portal-310/course_files/begin_advanced/solution_python2_chapter07_logging_gui.py | pbarton666/virtual_classroom | train | 0 |
01e855c7d9a293fd79de0a25505cf281760a14b2 | [
"Turtle.__init__(self, shape='square', visible=False)\nself.penup()\nself.shapesize(n * 1.25, 0.75, 1)\nself.sety(12.5 * n)\nself.x = Peg.pos\nself.setx(self.x)\nself.showturtle()\nPeg.pos += 200",
"disk.setx(self.x)\ndisk.sety(10 + len(self) * 25)\nself.append(disk)",
"disk = self.pop()\ndisk.sety(300)\nreturn... | <|body_start_0|>
Turtle.__init__(self, shape='square', visible=False)
self.penup()
self.shapesize(n * 1.25, 0.75, 1)
self.sety(12.5 * n)
self.x = Peg.pos
self.setx(self.x)
self.showturtle()
Peg.pos += 200
<|end_body_0|>
<|body_start_1|>
disk.setx(... | Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino | Peg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Peg:
"""Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino"""
def __init__(self, n):
... | stack_v2_sparse_classes_75kplus_train_000797 | 2,822 | no_license | [
{
"docstring": "Inicializa um pino para n discos",
"name": "__init__",
"signature": "def __init__(self, n)"
},
{
"docstring": "Coloca disco em torno do pino",
"name": "push",
"signature": "def push(self, disk)"
},
{
"docstring": "Remove disco do topo do pino e o retorna",
"na... | 3 | stack_v2_sparse_classes_30k_train_021217 | Implement the Python class `Peg` described below.
Class description:
Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco ... | Implement the Python class `Peg` described below.
Class description:
Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco ... | 5d4eec368be91c18f0ae5c17d342e6eb0f1c79be | <|skeleton|>
class Peg:
"""Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino"""
def __init__(self, n):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Peg:
"""Classe de pino da torre de Hanói, herda de Turtle e list ________________________________________________________ __init__(self, n) Inicializa um pino para n discos pop(self) Remove o disco de cima do pino e o retorna push(self, disk) coloca o disco no pino"""
def __init__(self, n):
"""In... | the_stack_v2_python_sparse | Semana3/turtle_hanoi.py | ju-c-lopes/Univesp_Algoritmos_II | train | 0 |
46c9af1862c1c4a2cdfaf72d705da1a8c289cc08 | [
"super(SampleEmbeddingHelper, self).__init__(embedding, start_tokens, end_token)\nself._softmax_temperature = softmax_temperature\nself._seed = seed",
"del time, state\nif not isinstance(outputs, ops.Tensor):\n raise TypeError('Expected outputs to be a single Tensor, got: %s' % type(outputs))\nif self._softmax... | <|body_start_0|>
super(SampleEmbeddingHelper, self).__init__(embedding, start_tokens, end_token)
self._softmax_temperature = softmax_temperature
self._seed = seed
<|end_body_0|>
<|body_start_1|>
del time, state
if not isinstance(outputs, ops.Tensor):
raise TypeError(... | A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input. | SampleEmbeddingHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleEmbeddingHelper:
"""A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding, start_tokens, end_token, softmax_temperature=None, seed=None):
"... | stack_v2_sparse_classes_75kplus_train_000798 | 26,004 | permissive | [
{
"docstring": "Initializer. Args: embedding: A callable that takes a vector tensor of `ids` (argmax ids), or the `params` argument for `embedding_lookup`. The returned tensor will be passed to the decoder input. start_tokens: `int32` vector shaped `[batch_size]`, the start tokens. end_token: `int32` scalar, th... | 2 | stack_v2_sparse_classes_30k_train_052676 | Implement the Python class `SampleEmbeddingHelper` described below.
Class description:
A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input.
Method signatures and docstrings:
- def __init__(self, embedding, star... | Implement the Python class `SampleEmbeddingHelper` described below.
Class description:
A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input.
Method signatures and docstrings:
- def __init__(self, embedding, star... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class SampleEmbeddingHelper:
"""A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding, start_tokens, end_token, softmax_temperature=None, seed=None):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleEmbeddingHelper:
"""A helper for use during inference. Uses sampling (from a distribution) instead of argmax and passes the result through an embedding layer to get the next input."""
def __init__(self, embedding, start_tokens, end_token, softmax_temperature=None, seed=None):
"""Initializer... | the_stack_v2_python_sparse | Tensorflow/source/tensorflow/contrib/seq2seq/python/ops/helper.py | ryfeus/lambda-packs | train | 1,283 |
6c905590b4d8407d9a4e1e333c1457eb2a8676df | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RetentionEvent()",
"from ..entity import Entity\nfrom ..identity_set import IdentitySet\nfrom .event_propagation_result import EventPropagationResult\nfrom .event_query import EventQuery\nfrom .retention_event_status import RetentionEv... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RetentionEvent()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from ..identity_set import IdentitySet
from .event_propagation_result import EventPropagationResult
... | RetentionEvent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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 Retur... | stack_v2_sparse_classes_75kplus_train_000799 | 6,338 | 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: RetentionEvent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_045993 | Implement the Python class `RetentionEvent` described below.
Class description:
Implement the RetentionEvent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `RetentionEvent` described below.
Class description:
Implement the RetentionEvent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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 Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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: RetentionE... | the_stack_v2_python_sparse | msgraph/generated/models/security/retention_event.py | microsoftgraph/msgraph-sdk-python | train | 135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.