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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
020f680e8b4899f3efe2c3fecd65f5e23fb48f57 | [
"some_categories = create_some_categories()\nsome_tags = create_some_tags()\nfuture_test = create_test(category=some_categories[0], tags=some_tags[2:], name='Тест с будущей датой публикации', publishing_days_offset=30)\nresponse = self.client.get(reverse('test_detail', args=(future_test.id,)))\nself.assertRedirects... | <|body_start_0|>
some_categories = create_some_categories()
some_tags = create_some_tags()
future_test = create_test(category=some_categories[0], tags=some_tags[2:], name='Тест с будущей датой публикации', publishing_days_offset=30)
response = self.client.get(reverse('test_detail', args=... | Класс с тестами для представления test_detail | TestDetailViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDetailViewTests:
"""Класс с тестами для представления test_detail"""
def test_detail_view_with_a_future_test(self):
"""Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать перенаправление"""
<|body_0|>
def test_detail... | stack_v2_sparse_classes_75kplus_train_000800 | 43,023 | no_license | [
{
"docstring": "Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать перенаправление",
"name": "test_detail_view_with_a_future_test",
"signature": "def test_detail_view_with_a_future_test(self)"
},
{
"docstring": "Подробное представление, странич... | 2 | stack_v2_sparse_classes_30k_train_013460 | Implement the Python class `TestDetailViewTests` described below.
Class description:
Класс с тестами для представления test_detail
Method signatures and docstrings:
- def test_detail_view_with_a_future_test(self): Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать п... | Implement the Python class `TestDetailViewTests` described below.
Class description:
Класс с тестами для представления test_detail
Method signatures and docstrings:
- def test_detail_view_with_a_future_test(self): Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать п... | b4f7557cadb70a4688ce7e76992917c610f2b3c1 | <|skeleton|>
class TestDetailViewTests:
"""Класс с тестами для представления test_detail"""
def test_detail_view_with_a_future_test(self):
"""Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать перенаправление"""
<|body_0|>
def test_detail... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDetailViewTests:
"""Класс с тестами для представления test_detail"""
def test_detail_view_with_a_future_test(self):
"""Подробное представление, страничка теста с будущей либо отсутствующей датой публикации должно выдавать перенаправление"""
some_categories = create_some_categories()
... | the_stack_v2_python_sparse | octapp/tests.py | Cheltigmashev/oct | train | 0 |
dd50d263bc895efde61bbaef02bb68baacff985d | [
"if os.path.isfile(file_path_name):\n os.remove(file_path_name)\nself.logger = logging.getLogger('losses_logger')\nself.logger.setLevel(1)\nfile_handler = logging.FileHandler(file_path_name)\nfile_handler.setLevel(1)\nself.logger.addHandler(file_handler)\nheader = ','.join(['Epoch', 'Train Loss', 'Valid Loss', '... | <|body_start_0|>
if os.path.isfile(file_path_name):
os.remove(file_path_name)
self.logger = logging.getLogger('losses_logger')
self.logger.setLevel(1)
file_handler = logging.FileHandler(file_path_name)
file_handler.setLevel(1)
self.logger.addHandler(file_handl... | Class definition for objects to write data to log files in a form which is then easy to be plotted. | LossesLogger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LossesLogger:
"""Class definition for objects to write data to log files in a form which is then easy to be plotted."""
def __init__(self, file_path_name):
"""Create a logger to store information for plotting."""
<|body_0|>
def log(self, epoch, storer):
"""Write ... | stack_v2_sparse_classes_75kplus_train_000801 | 6,647 | permissive | [
{
"docstring": "Create a logger to store information for plotting.",
"name": "__init__",
"signature": "def __init__(self, file_path_name)"
},
{
"docstring": "Write to the log file.",
"name": "log",
"signature": "def log(self, epoch, storer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052127 | Implement the Python class `LossesLogger` described below.
Class description:
Class definition for objects to write data to log files in a form which is then easy to be plotted.
Method signatures and docstrings:
- def __init__(self, file_path_name): Create a logger to store information for plotting.
- def log(self, e... | Implement the Python class `LossesLogger` described below.
Class description:
Class definition for objects to write data to log files in a form which is then easy to be plotted.
Method signatures and docstrings:
- def __init__(self, file_path_name): Create a logger to store information for plotting.
- def log(self, e... | ce26ce718cf5cf18a18d38f273a84324dbd5f4b2 | <|skeleton|>
class LossesLogger:
"""Class definition for objects to write data to log files in a form which is then easy to be plotted."""
def __init__(self, file_path_name):
"""Create a logger to store information for plotting."""
<|body_0|>
def log(self, epoch, storer):
"""Write ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LossesLogger:
"""Class definition for objects to write data to log files in a form which is then easy to be plotted."""
def __init__(self, file_path_name):
"""Create a logger to store information for plotting."""
if os.path.isfile(file_path_name):
os.remove(file_path_name)
... | the_stack_v2_python_sparse | flexehr/training.py | medical-projects/flexible-ehr | train | 0 |
c49df98b05b9612f059943212829f5edcb6880ca | [
"if not root:\n return []\nqueue = []\nresult = []\nqueue.append(root)\nwhile len(queue) > 0:\n temp_val = []\n temp_queue = []\n while len(queue) > 0:\n root = queue.pop(0)\n temp_val.append(root.val)\n if root.left:\n temp_queue.append(root.left)\n if root.right:... | <|body_start_0|>
if not root:
return []
queue = []
result = []
queue.append(root)
while len(queue) > 0:
temp_val = []
temp_queue = []
while len(queue) > 0:
root = queue.pop(0)
temp_val.append(root.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
""":param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
queu... | stack_v2_sparse_classes_75kplus_train_000802 | 1,615 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": ":param root: :return:",
"name": "levelOrder2",
"signature": "def levelOrder2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016955 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): :param root: :return:
<|skeleton|>
class Solution:
def levelOrder(se... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
""":param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
queue = []
result = []
queue.append(root)
while len(queue) > 0:
temp_val = []
temp_queue = []
while le... | the_stack_v2_python_sparse | leetcode/tree/code/level.py | skyxyz-lang/CS_Note | train | 0 | |
897fbe15b4915c216ea5e4d98c3e4faa4676b9a2 | [
"user = self._val_service.validate_user_model(data)\ntoken = self._auth_service.get_token(user.email)\nuser.access_token = token\nuser.updated_at = dt.datetime.utcnow()\nuser.save()\nreturn user",
"email = data['email']\npassword = data['password']\nif email is None:\n raise ValueError('Email is required.')\ni... | <|body_start_0|>
user = self._val_service.validate_user_model(data)
token = self._auth_service.get_token(user.email)
user.access_token = token
user.updated_at = dt.datetime.utcnow()
user.save()
return user
<|end_body_0|>
<|body_start_1|>
email = data['email']
... | AuthRepository | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
<|body_0|>
def login(self, data: dict) -> User:
"""Allows a user to login with email and password."""
<|body_1|>
def logout(self, context: dict) -... | stack_v2_sparse_classes_75kplus_train_000803 | 2,377 | permissive | [
{
"docstring": "Allows a user to register a new account.",
"name": "register_user",
"signature": "def register_user(self, data: dict) -> User"
},
{
"docstring": "Allows a user to login with email and password.",
"name": "login",
"signature": "def login(self, data: dict) -> User"
},
{... | 3 | stack_v2_sparse_classes_30k_train_028381 | Implement the Python class `AuthRepository` described below.
Class description:
Implement the AuthRepository class.
Method signatures and docstrings:
- def register_user(self, data: dict) -> User: Allows a user to register a new account.
- def login(self, data: dict) -> User: Allows a user to login with email and pas... | Implement the Python class `AuthRepository` described below.
Class description:
Implement the AuthRepository class.
Method signatures and docstrings:
- def register_user(self, data: dict) -> User: Allows a user to register a new account.
- def login(self, data: dict) -> User: Allows a user to login with email and pas... | 41f76fe698380aa946e35d9879dd3997a4ac5520 | <|skeleton|>
class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
<|body_0|>
def login(self, data: dict) -> User:
"""Allows a user to login with email and password."""
<|body_1|>
def logout(self, context: dict) -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
user = self._val_service.validate_user_model(data)
token = self._auth_service.get_token(user.email)
user.access_token = token
user.updated_at = dt.datetime.utcnow... | the_stack_v2_python_sparse | app/modules/core/auth/repository.py | CraigWhitley/ariadne-mongo-server | train | 2 | |
f66bde4d72d03a576050278898d97c8f7af35d41 | [
"head = ListNode(0)\ndummy = head\nwhile l1 and l2:\n if l1.val <= l2.val:\n dummy.next = l1\n l1 = l1.next\n else:\n dummy.next = l2\n l2 = l2.next\n dummy = dummy.next\ndummy.next = l1 if l1 else l2\nreturn head.next",
"if not l1:\n return l2\nelif not l2:\n return l1\... | <|body_start_0|>
head = ListNode(0)
dummy = head
while l1 and l2:
if l1.val <= l2.val:
dummy.next = l1
l1 = l1.next
else:
dummy.next = l2
l2 = l2.next
dummy = dummy.next
dummy.next = l1 if... | TwoSorted | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoSorted:
def merge(self, l1: ListNode, l2: ListNode):
"""Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:"""
<|body_0|>
def merge_(self, l1: ListNode, l2: ListNode):
"""Approach: Recursion Time Complexity: O(N + M)... | stack_v2_sparse_classes_75kplus_train_000804 | 1,203 | no_license | [
{
"docstring": "Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:",
"name": "merge",
"signature": "def merge(self, l1: ListNode, l2: ListNode)"
},
{
"docstring": "Approach: Recursion Time Complexity: O(N + M) Space Complexity: O(N + M) :param l1:... | 2 | stack_v2_sparse_classes_30k_train_018531 | Implement the Python class `TwoSorted` described below.
Class description:
Implement the TwoSorted class.
Method signatures and docstrings:
- def merge(self, l1: ListNode, l2: ListNode): Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:
- def merge_(self, l1: ListNode... | Implement the Python class `TwoSorted` described below.
Class description:
Implement the TwoSorted class.
Method signatures and docstrings:
- def merge(self, l1: ListNode, l2: ListNode): Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:
- def merge_(self, l1: ListNode... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class TwoSorted:
def merge(self, l1: ListNode, l2: ListNode):
"""Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:"""
<|body_0|>
def merge_(self, l1: ListNode, l2: ListNode):
"""Approach: Recursion Time Complexity: O(N + M)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoSorted:
def merge(self, l1: ListNode, l2: ListNode):
"""Approach: Iteration Time Complexity: O(N + M) Space Complexity: O(1) :param l1: :param l2: :return:"""
head = ListNode(0)
dummy = head
while l1 and l2:
if l1.val <= l2.val:
dummy.next = l1
... | the_stack_v2_python_sparse | revisited_2021/linked_list/merge_two_sorted_list.py | Shiv2157k/leet_code | train | 1 | |
8c238a4c20b4359c7a2da6753b0288a99f6c0b4e | [
"buyer = request.user\nproduct = get_object_or_404(Product, pk=pk)\nTrade.objects.get_or_create(product=product, seller=product.seller, buyer=buyer)\nreturn Response(status=status.HTTP_206_PARTIAL_CONTENT)",
"buyer = request.user\ntrades = self.get_queryset().filter(buyer=buyer, status=1)\nif trades.filter(produc... | <|body_start_0|>
buyer = request.user
product = get_object_or_404(Product, pk=pk)
Trade.objects.get_or_create(product=product, seller=product.seller, buyer=buyer)
return Response(status=status.HTTP_206_PARTIAL_CONTENT)
<|end_body_0|>
<|body_start_1|>
buyer = request.user
... | TradeViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TradeViewSet:
def bagging(self, request, pk):
"""[DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated"""
<|body_0|>
def cart(self, request):
"""[DEPRECATED 2020.07.01] for 1차 출시 카트 조... | stack_v2_sparse_classes_75kplus_train_000805 | 25,148 | no_license | [
{
"docstring": "[DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated",
"name": "bagging",
"signature": "def bagging(self, request, pk)"
},
{
"docstring": "[DEPRECATED 2020.07.01] for 1차 출시 카트 조회 api 입니다. return ... | 4 | null | Implement the Python class `TradeViewSet` described below.
Class description:
Implement the TradeViewSet class.
Method signatures and docstrings:
- def bagging(self, request, pk): [DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated
... | Implement the Python class `TradeViewSet` described below.
Class description:
Implement the TradeViewSet class.
Method signatures and docstrings:
- def bagging(self, request, pk): [DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated
... | 5cd920b49aa169070c10ec0ad7f38a6bcad27065 | <|skeleton|>
class TradeViewSet:
def bagging(self, request, pk):
"""[DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated"""
<|body_0|>
def cart(self, request):
"""[DEPRECATED 2020.07.01] for 1차 출시 카트 조... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TradeViewSet:
def bagging(self, request, pk):
"""[DEPRECATED 2020.07.01] for 1차 출시 장바구니 담은 api 입니다. api: PUT api/v1/trade/{id}/bagging/ * id: product id :return 404 not found 206 updated"""
buyer = request.user
product = get_object_or_404(Product, pk=pk)
Trade.objects.get_or_cr... | the_stack_v2_python_sparse | siiot/payment/views.py | mondeique/SIIOT-main-server | train | 0 | |
c45931b6822566d5ab3f70c3c2b836d420352207 | [
"from ArmisEventCollector import fetch_events\nmocker.patch.object(Client, 'fetch_by_aql_query', return_value=response)\nmocker.patch.dict(EVENT_TYPES, {'Events': EVENT_TYPE('unique_id', 'events_query', 'events')})\nassert fetch_events(dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch) == (e... | <|body_start_0|>
from ArmisEventCollector import fetch_events
mocker.patch.object(Client, 'fetch_by_aql_query', return_value=response)
mocker.patch.dict(EVENT_TYPES, {'Events': EVENT_TYPE('unique_id', 'events_query', 'events')})
assert fetch_events(dummy_client, max_fetch, last_run, fetc... | TestFetchFlow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events w... | stack_v2_sparse_classes_75kplus_train_000806 | 18,429 | permissive | [
{
"docstring": "Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events with different timestamps. - Case 3: Second fetch with duplicated, some events in the response have same timestamps as last fetch. - Case 4: Second fetch with empty respon... | 2 | stack_v2_sparse_classes_30k_train_035624 | Implement the Python class `TestFetchFlow` described below.
Class description:
Implement the TestFetchFlow class.
Method signatures and docstrings:
- def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run): Given: - Case 1: First f... | Implement the Python class `TestFetchFlow` described below.
Class description:
Implement the TestFetchFlow class.
Method signatures and docstrings:
- def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run): Given: - Case 1: First f... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestFetchFlow:
def test_fetch_flow_cases(self, mocker, dummy_client, max_fetch, last_run, fetch_start_time, event_types_to_fetch, response, events, next_run):
"""Given: - Case 1: First fetch, response has 3 events with different timestamps. - Case 2: Second fetch, response has 3 events with different ... | the_stack_v2_python_sparse | Packs/Armis/Integrations/ArmisEventCollector/ArmisEventCollector_test.py | demisto/content | train | 1,023 | |
bce387afd68d0faea7093c71aa29f4d5353e296a | [
"item_id = self.request.GET.get('id', None)\nmetadata_format = self.request.GET.get('format', None)\nif item_id and metadata_format:\n response = HttpResponse(content=self.get_metadata(item_id, metadata_format), content_type=self.formats[metadata_format]['type'])\n response['Content-Disposition'] = 'filename=... | <|body_start_0|>
item_id = self.request.GET.get('id', None)
metadata_format = self.request.GET.get('format', None)
if item_id and metadata_format:
response = HttpResponse(content=self.get_metadata(item_id, metadata_format), content_type=self.formats[metadata_format]['type'])
... | Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for more details. https://web.archive.org/web/20140331070802/http://unapi.info/spec... | UnAPIView | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnAPIView:
"""Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for more details. https://web.archive.org/web/... | stack_v2_sparse_classes_75kplus_train_000807 | 2,961 | permissive | [
{
"docstring": "Override get to check if id and format are specified; if they are, return the requested metadata. Otherwise, falls back to normal template view behavior and displays format information.",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "pass formats... | 3 | stack_v2_sparse_classes_30k_test_000246 | Implement the Python class `UnAPIView` described below.
Class description:
Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for mor... | Implement the Python class `UnAPIView` described below.
Class description:
Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for mor... | 99e751b0d656d0d28c7e995cc44c351622313593 | <|skeleton|>
class UnAPIView:
"""Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for more details. https://web.archive.org/web/... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnAPIView:
"""Simple unAPI service endpoint. With no parameters or only id, provides a list of available metadata formats. If id and format are specified, returns the metadata for the specified item in the requested format. See archived unAPI website for more details. https://web.archive.org/web/2014033107080... | the_stack_v2_python_sparse | ppa/unapi/views.py | Princeton-CDH/ppa-django | train | 5 |
50f87ab499fd627e1dd1286eb718ba88739ff0bb | [
"with self.assertRaisesRegex(TypeError, expected_regex='must be a list'):\n cluster_state.excited_cluster_states('junk')\nwith self.assertRaisesRegex(ValueError, expected_regex='cirq.GridQubit'):\n cluster_state.excited_cluster_states([cirq.NamedQubit('bob')])\nwith self.assertRaisesRegex(ValueError, expected... | <|body_start_0|>
with self.assertRaisesRegex(TypeError, expected_regex='must be a list'):
cluster_state.excited_cluster_states('junk')
with self.assertRaisesRegex(ValueError, expected_regex='cirq.GridQubit'):
cluster_state.excited_cluster_states([cirq.NamedQubit('bob')])
... | Small test to make sure dataset for ClusterState works. | ClusterStateDataTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterStateDataTest:
"""Small test to make sure dataset for ClusterState works."""
def test_errors(self):
"""Test that it errors on invalid qubits."""
<|body_0|>
def test_creation(self):
"""Test that it returns the correct number of circuits."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_000808 | 2,123 | permissive | [
{
"docstring": "Test that it errors on invalid qubits.",
"name": "test_errors",
"signature": "def test_errors(self)"
},
{
"docstring": "Test that it returns the correct number of circuits.",
"name": "test_creation",
"signature": "def test_creation(self)"
}
] | 2 | null | Implement the Python class `ClusterStateDataTest` described below.
Class description:
Small test to make sure dataset for ClusterState works.
Method signatures and docstrings:
- def test_errors(self): Test that it errors on invalid qubits.
- def test_creation(self): Test that it returns the correct number of circuits... | Implement the Python class `ClusterStateDataTest` described below.
Class description:
Small test to make sure dataset for ClusterState works.
Method signatures and docstrings:
- def test_errors(self): Test that it errors on invalid qubits.
- def test_creation(self): Test that it returns the correct number of circuits... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class ClusterStateDataTest:
"""Small test to make sure dataset for ClusterState works."""
def test_errors(self):
"""Test that it errors on invalid qubits."""
<|body_0|>
def test_creation(self):
"""Test that it returns the correct number of circuits."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterStateDataTest:
"""Small test to make sure dataset for ClusterState works."""
def test_errors(self):
"""Test that it errors on invalid qubits."""
with self.assertRaisesRegex(TypeError, expected_regex='must be a list'):
cluster_state.excited_cluster_states('junk')
... | the_stack_v2_python_sparse | tensorflow_quantum/datasets/cluster_state_test.py | tensorflow/quantum | train | 1,799 |
c3ee8a38a79865f238b73b5f83c3a60b50f50629 | [
"assert html_tag in ('li', 'div', 'span', None)\nself.html_tag = html_tag\nself.prefix_label = prefix_label\nself.with_label = with_label\nself.class_ = class_",
"if self.with_label:\n if self.prefix_label:\n return '%s: %s' % (subfield.label, subfield())\n else:\n return '%s %s' % (subfield()... | <|body_start_0|>
assert html_tag in ('li', 'div', 'span', None)
self.html_tag = html_tag
self.prefix_label = prefix_label
self.with_label = with_label
self.class_ = class_
<|end_body_0|>
<|body_start_1|>
if self.with_label:
if self.prefix_label:
... | Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed. | ListItemWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_labe... | stack_v2_sparse_classes_75kplus_train_000809 | 15,429 | no_license | [
{
"docstring": "Initialize list item with html tag. :param html_tag: name of html tag can be 'li', 'div', or 'span'.",
"name": "__init__",
"signature": "def __init__(self, html_tag='li', with_label=True, prefix_label=True, class_=None)"
},
{
"docstring": "Render subfield.",
"name": "render_s... | 5 | stack_v2_sparse_classes_30k_train_022803 | Implement the Python class `ListItemWidget` described below.
Class description:
Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed.
Method signatures and docstrin... | Implement the Python class `ListItemWidget` described below.
Class description:
Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed.
Method signatures and docstrin... | 90032ba4825c6c4dda78c9c2b1d3edf18692b9dc | <|skeleton|>
class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_labe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_label=True, class... | the_stack_v2_python_sparse | inspirehep/modules/forms/field_widgets.py | spirosdelviniotis/inspire-next | train | 1 |
eb10e921db75f9aa354529048d947ba00b264b42 | [
"super().__init__()\nself.shared_conv = nn.Sequential(nn.Conv2d(self.in_channels, self.task_in_channels, kernel_size=3, padding=1, bias=True), nn.BatchNorm2d(self.task_in_channels), nn.ReLU(inplace=True))\nself.tasks = nn.ModuleList([DeformableDetectionHead(len(task), deepcopy(self.common_heads), self.task_in_chann... | <|body_start_0|>
super().__init__()
self.shared_conv = nn.Sequential(nn.Conv2d(self.in_channels, self.task_in_channels, kernel_size=3, padding=1, bias=True), nn.BatchNorm2d(self.task_in_channels), nn.ReLU(inplace=True))
self.tasks = nn.ModuleList([DeformableDetectionHead(len(task), deepcopy(self... | CenterHead class for keypoint classification and regression. | CenterHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterHead:
"""CenterHead class for keypoint classification and regression."""
def __post_init__(self) -> None:
"""Initialize network modules."""
<|body_0|>
def forward(self, x: Tensor, y: RegularGridData) -> Tuple[List[TaskOutputs], CenterPointLoss]:
"""Network ... | stack_v2_sparse_classes_75kplus_train_000810 | 4,237 | permissive | [
{
"docstring": "Initialize network modules.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Network forward pass. Args: x: (B,C,H,W) Network outputs. y: Data passed to the network --- includes targets. Returns: Processed data.",
"name": "forward",... | 3 | stack_v2_sparse_classes_30k_train_053819 | Implement the Python class `CenterHead` described below.
Class description:
CenterHead class for keypoint classification and regression.
Method signatures and docstrings:
- def __post_init__(self) -> None: Initialize network modules.
- def forward(self, x: Tensor, y: RegularGridData) -> Tuple[List[TaskOutputs], Cente... | Implement the Python class `CenterHead` described below.
Class description:
CenterHead class for keypoint classification and regression.
Method signatures and docstrings:
- def __post_init__(self) -> None: Initialize network modules.
- def forward(self, x: Tensor, y: RegularGridData) -> Tuple[List[TaskOutputs], Cente... | 27c35f791f1c618c036cf0e4481d7fa0fe13bb29 | <|skeleton|>
class CenterHead:
"""CenterHead class for keypoint classification and regression."""
def __post_init__(self) -> None:
"""Initialize network modules."""
<|body_0|>
def forward(self, x: Tensor, y: RegularGridData) -> Tuple[List[TaskOutputs], CenterPointLoss]:
"""Network ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterHead:
"""CenterHead class for keypoint classification and regression."""
def __post_init__(self) -> None:
"""Initialize network modules."""
super().__init__()
self.shared_conv = nn.Sequential(nn.Conv2d(self.in_channels, self.task_in_channels, kernel_size=3, padding=1, bias=T... | the_stack_v2_python_sparse | src/torchbox3d/nn/heads/center.py | benjaminrwilson/torchbox3d | train | 13 |
a77178b6300f4d67a242e57599942c56d2c6956d | [
"self.num_features = num_features\nself.filter_func_list = filter_func_list\nself.word_pattern = re.compile('[a-z]{3,}')",
"tf = self._countTermFrequency(raw_instance)\nfeatures = []\nfor word in self.order:\n if word in tf:\n features += [tf[word] * self.idf[word]]\n else:\n features += [0]\n... | <|body_start_0|>
self.num_features = num_features
self.filter_func_list = filter_func_list
self.word_pattern = re.compile('[a-z]{3,}')
<|end_body_0|>
<|body_start_1|>
tf = self._countTermFrequency(raw_instance)
features = []
for word in self.order:
if word in... | Extracts a bag of words representation with TFIDF scores from raw text. | BagOfWordsFiltered | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BagOfWordsFiltered:
"""Extracts a bag of words representation with TFIDF scores from raw text."""
def __init__(self, num_features, filter_func_list):
"""Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]"""
... | stack_v2_sparse_classes_75kplus_train_000811 | 4,111 | no_license | [
{
"docstring": "Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]",
"name": "__init__",
"signature": "def __init__(self, num_features, filter_func_list)"
},
{
"docstring": "Creates a new instance in the feature-space fr... | 6 | stack_v2_sparse_classes_30k_train_026891 | Implement the Python class `BagOfWordsFiltered` described below.
Class description:
Extracts a bag of words representation with TFIDF scores from raw text.
Method signatures and docstrings:
- def __init__(self, num_features, filter_func_list): Constructor. @param num_features: The number of features to extract. @para... | Implement the Python class `BagOfWordsFiltered` described below.
Class description:
Extracts a bag of words representation with TFIDF scores from raw text.
Method signatures and docstrings:
- def __init__(self, num_features, filter_func_list): Constructor. @param num_features: The number of features to extract. @para... | fe417881ea523a64e9ab05b975b86cc3357835db | <|skeleton|>
class BagOfWordsFiltered:
"""Extracts a bag of words representation with TFIDF scores from raw text."""
def __init__(self, num_features, filter_func_list):
"""Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BagOfWordsFiltered:
"""Extracts a bag of words representation with TFIDF scores from raw text."""
def __init__(self, num_features, filter_func_list):
"""Constructor. @param num_features: The number of features to extract. @param param: filter_func_list [terms filter function,..]"""
self.n... | the_stack_v2_python_sparse | src/s_bag_of_words.py | gzvulon/IAI3-LM | train | 0 |
71f97bf398cb905fd2191a6679d545615a3954d5 | [
"super(PositionalEncoding, self).__init__()\nself.dropout = nn.Dropout(p=dropout)\npe = torch.zeros(max_len, d_model)\nposition = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\ndiv_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\npe[:, 0::2] = torch.sin(position * d... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) /... | PositionalEncoding | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model: int, dropout: Optional[float]=0.1, max_len: Optional[int]=5000) -> None:
"""Positional encoding. Code from: https://pytorch.org/tutorials/beginner/transformer_tutorial.html :param d_model: Input dimensionality :type d_model: int :param drop... | stack_v2_sparse_classes_75kplus_train_000812 | 1,733 | permissive | [
{
"docstring": "Positional encoding. Code from: https://pytorch.org/tutorials/beginner/transformer_tutorial.html :param d_model: Input dimensionality :type d_model: int :param dropout: Dropout for the encoding, defaults to 0.1. :type dropout: float, optional :param max_len: Maximum sequence length, defaults to ... | 2 | stack_v2_sparse_classes_30k_train_041106 | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: Optional[float]=0.1, max_len: Optional[int]=5000) -> None: Positional encoding. Code from: https://pytorch.org/tutor... | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: Optional[float]=0.1, max_len: Optional[int]=5000) -> None: Positional encoding. Code from: https://pytorch.org/tutor... | c78458ac0887851a743b7f47101b0fff97724b4f | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model: int, dropout: Optional[float]=0.1, max_len: Optional[int]=5000) -> None:
"""Positional encoding. Code from: https://pytorch.org/tutorials/beginner/transformer_tutorial.html :param d_model: Input dimensionality :type d_model: int :param drop... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
def __init__(self, d_model: int, dropout: Optional[float]=0.1, max_len: Optional[int]=5000) -> None:
"""Positional encoding. Code from: https://pytorch.org/tutorials/beginner/transformer_tutorial.html :param d_model: Input dimensionality :type d_model: int :param dropout: Dropout f... | the_stack_v2_python_sparse | modules/positional_encoding.py | audio-captioning/wavetransformer | train | 0 | |
045900bf89057e4fae9a7a2120d5c3e602de28d0 | [
"super().__init__()\nself.left = left\nself.right = right\nself.op = op",
"right = self.right.make_il(il_code, symbol_table, c)\nlvalue = self.left.lvalue(il_code, symbol_table, c)\nif lvalue and lvalue.modable():\n return lvalue.set_to(right, il_code, self.op.r)\nelse:\n err = \"expression on left of '=' i... | <|body_start_0|>
super().__init__()
self.left = left
self.right = right
self.op = op
<|end_body_0|>
<|body_start_1|>
right = self.right.make_il(il_code, symbol_table, c)
lvalue = self.left.lvalue(il_code, symbol_table, c)
if lvalue and lvalue.modable():
... | Expression that is an assignment. | Equals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Equals:
"""Expression that is an assignment."""
def __init__(self, left, right, op):
"""Initialize node."""
<|body_0|>
def make_il(self, il_code, symbol_table, c):
"""Make code for this node."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_75kplus_train_000813 | 45,651 | permissive | [
{
"docstring": "Initialize node.",
"name": "__init__",
"signature": "def __init__(self, left, right, op)"
},
{
"docstring": "Make code for this node.",
"name": "make_il",
"signature": "def make_il(self, il_code, symbol_table, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032259 | Implement the Python class `Equals` described below.
Class description:
Expression that is an assignment.
Method signatures and docstrings:
- def __init__(self, left, right, op): Initialize node.
- def make_il(self, il_code, symbol_table, c): Make code for this node. | Implement the Python class `Equals` described below.
Class description:
Expression that is an assignment.
Method signatures and docstrings:
- def __init__(self, left, right, op): Initialize node.
- def make_il(self, il_code, symbol_table, c): Make code for this node.
<|skeleton|>
class Equals:
"""Expression that... | 6232136be38a29e8c18beae3d23e49ecfb7906fd | <|skeleton|>
class Equals:
"""Expression that is an assignment."""
def __init__(self, left, right, op):
"""Initialize node."""
<|body_0|>
def make_il(self, il_code, symbol_table, c):
"""Make code for this node."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Equals:
"""Expression that is an assignment."""
def __init__(self, left, right, op):
"""Initialize node."""
super().__init__()
self.left = left
self.right = right
self.op = op
def make_il(self, il_code, symbol_table, c):
"""Make code for this node."""
... | the_stack_v2_python_sparse | shivyc/tree/expr_nodes.py | ShivamSarodia/ShivyC | train | 1,072 |
81e7a1ac52704e8601e93aafdf7e0cdc579385b3 | [
"LoginPage(browser).login(data['user'], data['pwd'])\nmsg = LoginPage(browser).erro_msg()\nassert data['msg'] == msg",
"LoginPage(browser).login(ld.ID_1['user'], ld.ID_1['pwd'])\nmsg = HomePage(browser).is_user_link_exists()\nassert msg == True",
"HomePage(browser).logout()\nmsg = HomePage(browser).is_user_link... | <|body_start_0|>
LoginPage(browser).login(data['user'], data['pwd'])
msg = LoginPage(browser).erro_msg()
assert data['msg'] == msg
<|end_body_0|>
<|body_start_1|>
LoginPage(browser).login(ld.ID_1['user'], ld.ID_1['pwd'])
msg = HomePage(browser).is_user_link_exists()
asse... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
<|body_0|>
def test_login_2_sucess(self, browser):
"""名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。"""
<... | stack_v2_sparse_classes_75kplus_train_000814 | 1,787 | no_license | [
{
"docstring": "名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。",
"name": "test_login_1_error",
"signature": "def test_login_1_error(self, data, browser)"
},
{
"docstring": "名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。",
"name": "test_login_2_suc... | 3 | stack_v2_sparse_classes_30k_train_036875 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1_error(self, data, browser): 名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。
- def test_login_2_sucess(self, browser): 名称:使用正确的账号密码信息登录 步骤: 1... | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_1_error(self, data, browser): 名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。
- def test_login_2_sucess(self, browser): 名称:使用正确的账号密码信息登录 步骤: 1... | e10910b4317f8effacedb3f861ede88d252d828f | <|skeleton|>
class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
<|body_0|>
def test_login_2_sucess(self, browser):
"""名称:使用正确的账号密码信息登录 步骤: 1、打开浏览器 2、输入正确账号密码 3、点击登录按钮 检查点: * 检查页面右侧的账户名是否存在。"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLogin:
def test_login_1_error(self, data, browser):
"""名称:使用错误的账号密码信息登录 步骤: 1、打开浏览器 2、输入账号密码 3、点击登录按钮 检查点: * 检查页面弹出的提示信息。"""
LoginPage(browser).login(data['user'], data['pwd'])
msg = LoginPage(browser).erro_msg()
assert data['msg'] == msg
def test_login_2_sucess(self, ... | the_stack_v2_python_sparse | TestCases/login/test_1_login.py | liqi629/yy_echo | train | 0 | |
3787765c40e349748f7c34fd2247f31a3e33c505 | [
"self.queue = [None] * q_size\nself.head = 0\nself.tail = 0\nself.q_size = q_size",
"res = False\nif self.__size() == self.q_size - 1:\n print('Queue Full!')\nelse:\n self.queue[self.tail] = data\n self.tail = (self.tail + 1) % self.q_size\n res = True\nreturn res",
"data = False\nif self.__size() =... | <|body_start_0|>
self.queue = [None] * q_size
self.head = 0
self.tail = 0
self.q_size = q_size
<|end_body_0|>
<|body_start_1|>
res = False
if self.__size() == self.q_size - 1:
print('Queue Full!')
else:
self.queue[self.tail] = data
... | [implements a circular queue] | CQueue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
<|body_0|>
def enqueue(self, data):
"""[Insert an element i... | stack_v2_sparse_classes_75kplus_train_000815 | 4,027 | permissive | [
{
"docstring": "[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})",
"name": "__init__",
"signature": "def __init__(self, q_size=32)"
},
{
"docstring": "[Insert an element into the queue.] Decorators: synchro Synchronizes th... | 5 | stack_v2_sparse_classes_30k_train_025477 | Implement the Python class `CQueue` described below.
Class description:
[implements a circular queue]
Method signatures and docstrings:
- def __init__(self, q_size=32): [Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})
- def enqueue(self, data):... | Implement the Python class `CQueue` described below.
Class description:
[implements a circular queue]
Method signatures and docstrings:
- def __init__(self, q_size=32): [Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})
- def enqueue(self, data):... | 4a0029efab2fa15cdd26575f87d7fb02f570ac73 | <|skeleton|>
class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
<|body_0|>
def enqueue(self, data):
"""[Insert an element i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
self.queue = [None] * q_size
self.head = 0
self.tail = 0
self... | the_stack_v2_python_sparse | data_structures/cqueue.py | devwarrior/python_coding | train | 0 |
d1de51861655c5b6f23ac101ab5a67507e31988a | [
"self.shooters_total = difficulty\nself.asteroids_total = difficulty\nsuper().__init__(**kwargs)",
"player = GamePlayer.random()\nshooters = HunterGroup.random(n=self.shooters_total)\nshooters.spread(100)\nplayers = PlayerGroup(player, activate=True, shooting=True)\nspaceships = SuperSpaceShipGroup(players, shoot... | <|body_start_0|>
self.shooters_total = difficulty
self.asteroids_total = difficulty
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
player = GamePlayer.random()
shooters = HunterGroup.random(n=self.shooters_total)
shooters.spread(100)
players = PlayerG... | Level in which the goal is to destroy all hunters. | DestroyHunters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestroyHunters:
"""Level in which the goal is to destroy all hunters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
<|body_0|>
def start(self):
"""Start the game by creating the game group with hunters."""
<|b... | stack_v2_sparse_classes_75kplus_train_000816 | 10,293 | no_license | [
{
"docstring": "Create the level by creating the groups.",
"name": "__init__",
"signature": "def __init__(self, difficulty, **kwargs)"
},
{
"docstring": "Start the game by creating the game group with hunters.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "S... | 3 | stack_v2_sparse_classes_30k_train_037566 | Implement the Python class `DestroyHunters` described below.
Class description:
Level in which the goal is to destroy all hunters.
Method signatures and docstrings:
- def __init__(self, difficulty, **kwargs): Create the level by creating the groups.
- def start(self): Start the game by creating the game group with hu... | Implement the Python class `DestroyHunters` described below.
Class description:
Level in which the goal is to destroy all hunters.
Method signatures and docstrings:
- def __init__(self, difficulty, **kwargs): Create the level by creating the groups.
- def start(self): Start the game by creating the game group with hu... | ebfcaaf4a028eddb36bbc99184eb3f7a86eb24ed | <|skeleton|>
class DestroyHunters:
"""Level in which the goal is to destroy all hunters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
<|body_0|>
def start(self):
"""Start the game by creating the game group with hunters."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DestroyHunters:
"""Level in which the goal is to destroy all hunters."""
def __init__(self, difficulty, **kwargs):
"""Create the level by creating the groups."""
self.shooters_total = difficulty
self.asteroids_total = difficulty
super().__init__(**kwargs)
def start(se... | the_stack_v2_python_sparse | Game Structure/geometry/version5/myasteroidgame.py | MarcPartensky/Python-Games | train | 2 |
060fc36b6364031f5d57e26d0e41eb57d28aeedc | [
"self._image = image\nself._autoremove = autoremove\nself._container_id: Optional[str] = None\nself._runtime: Optional[str] = runtime\nself._env: Dict = env or {}\nself._mounts: Dict = bind_mounts or {}\nself._ports: Dict = ports or {}\nself._command: Optional[List[str]] = command",
"command = ['run', '-d']\nfor ... | <|body_start_0|>
self._image = image
self._autoremove = autoremove
self._container_id: Optional[str] = None
self._runtime: Optional[str] = runtime
self._env: Dict = env or {}
self._mounts: Dict = bind_mounts or {}
self._ports: Dict = ports or {}
self._comm... | Helper class for running and managing docker containers. | DockerContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerContainer:
"""Helper class for running and managing docker containers."""
def __init__(self, image: DockerImage, autoremove: bool=True, runtime: Optional[str]=None, env: Optional[Dict[str, str]]=None, bind_mounts: Optional[Dict[str, str]]=None, ports: Optional[Dict[int, int]]=None, com... | stack_v2_sparse_classes_75kplus_train_000817 | 4,533 | permissive | [
{
"docstring": "Initialize :py:class:`DockerContainer`. :param image: container :py:class:`DockerImage` :param autoremove: remove the container after it is stopped :param runtime: docker runtime flag (e.g. ``nvidia``) :param env: additional environment variables :param bind_mounts: optional host->container bind... | 5 | stack_v2_sparse_classes_30k_train_035869 | Implement the Python class `DockerContainer` described below.
Class description:
Helper class for running and managing docker containers.
Method signatures and docstrings:
- def __init__(self, image: DockerImage, autoremove: bool=True, runtime: Optional[str]=None, env: Optional[Dict[str, str]]=None, bind_mounts: Opti... | Implement the Python class `DockerContainer` described below.
Class description:
Helper class for running and managing docker containers.
Method signatures and docstrings:
- def __init__(self, image: DockerImage, autoremove: bool=True, runtime: Optional[str]=None, env: Optional[Dict[str, str]]=None, bind_mounts: Opti... | 0847c9885584378dd68a48c40d03f9bb02b2b57c | <|skeleton|>
class DockerContainer:
"""Helper class for running and managing docker containers."""
def __init__(self, image: DockerImage, autoremove: bool=True, runtime: Optional[str]=None, env: Optional[Dict[str, str]]=None, bind_mounts: Optional[Dict[str, str]]=None, ports: Optional[Dict[int, int]]=None, com... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DockerContainer:
"""Helper class for running and managing docker containers."""
def __init__(self, image: DockerImage, autoremove: bool=True, runtime: Optional[str]=None, env: Optional[Dict[str, str]]=None, bind_mounts: Optional[Dict[str, str]]=None, ports: Optional[Dict[int, int]]=None, command: Optiona... | the_stack_v2_python_sparse | shepherd/docker/container.py | iterait/shepherd | train | 6 |
b2ff4aed725ad5ec848ee14cccb0767b4ed659e6 | [
"self.jsonReaderWriter = jsonReaderWriter\nself.staticBoundingBoxes = staticBoundingBoxes\nself.configReader = configReader\nself.detectorThreshold = configReader.pp_detectorThreshold\nself.nonBackgroundClassIds = configReader.ci_nonBackgroundClassIds\nself.classPixelMaps = {}",
"self.jsonReaderWriter.initializeL... | <|body_start_0|>
self.jsonReaderWriter = jsonReaderWriter
self.staticBoundingBoxes = staticBoundingBoxes
self.configReader = configReader
self.detectorThreshold = configReader.pp_detectorThreshold
self.nonBackgroundClassIds = configReader.ci_nonBackgroundClassIds
self.cla... | FramePostProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FramePostProcessor:
def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader):
"""Initialize values"""
<|body_0|>
def run(self):
"""Collect and analyze detection results"""
<|body_1|>
def saveLocalizations(self, numpyFileBaseName):
... | stack_v2_sparse_classes_75kplus_train_000818 | 3,115 | no_license | [
{
"docstring": "Initialize values",
"name": "__init__",
"signature": "def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader)"
},
{
"docstring": "Collect and analyze detection results",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Save localizati... | 3 | null | Implement the Python class `FramePostProcessor` described below.
Class description:
Implement the FramePostProcessor class.
Method signatures and docstrings:
- def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader): Initialize values
- def run(self): Collect and analyze detection results
- def saveLo... | Implement the Python class `FramePostProcessor` described below.
Class description:
Implement the FramePostProcessor class.
Method signatures and docstrings:
- def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader): Initialize values
- def run(self): Collect and analyze detection results
- def saveLo... | b0bcfc0b753215bf56a437b8caf0faf48ed72ee4 | <|skeleton|>
class FramePostProcessor:
def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader):
"""Initialize values"""
<|body_0|>
def run(self):
"""Collect and analyze detection results"""
<|body_1|>
def saveLocalizations(self, numpyFileBaseName):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FramePostProcessor:
def __init__(self, jsonReaderWriter, staticBoundingBoxes, configReader):
"""Initialize values"""
self.jsonReaderWriter = jsonReaderWriter
self.staticBoundingBoxes = staticBoundingBoxes
self.configReader = configReader
self.detectorThreshold = configR... | the_stack_v2_python_sparse | Logo/PipelineMath/FramePostProcessor.py | zigvu/khajuri | train | 0 | |
19061058277b741103d22274c44cc76a4c9ff706 | [
"self.InstanceModel = calls.Call.all()\nself.AllowedMethods = ['GET']\nself.AllowedFilters = {'GET': [['To', '='], ['From', '='], ['Status', '='], ['StartTime', '='], ['EndTime', '=']]}\nself.ListName = 'Calls'\nself.InstanceModelName = 'Call'",
"format = response.response_format(self.request.path.split('/')[-1])... | <|body_start_0|>
self.InstanceModel = calls.Call.all()
self.AllowedMethods = ['GET']
self.AllowedFilters = {'GET': [['To', '='], ['From', '='], ['Status', '='], ['StartTime', '='], ['EndTime', '=']]}
self.ListName = 'Calls'
self.InstanceModelName = 'Call'
<|end_body_0|>
<|body_s... | CallList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallList:
def __init__(self):
"""To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing, in-progress, completed, failed, busy, or no-answer. StartTime Only show calls that started on th... | stack_v2_sparse_classes_75kplus_train_000819 | 7,459 | no_license | [
{
"docstring": "To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing, in-progress, completed, failed, busy, or no-answer. StartTime Only show calls that started on this date, given as YYYY-MM-DD. Also suppor... | 2 | stack_v2_sparse_classes_30k_train_035715 | Implement the Python class `CallList` described below.
Class description:
Implement the CallList class.
Method signatures and docstrings:
- def __init__(self): To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing,... | Implement the Python class `CallList` described below.
Class description:
Implement the CallList class.
Method signatures and docstrings:
- def __init__(self): To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing,... | 857f919d9190aceb1273ea5b357e6eeef1a0d36f | <|skeleton|>
class CallList:
def __init__(self):
"""To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing, in-progress, completed, failed, busy, or no-answer. StartTime Only show calls that started on th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CallList:
def __init__(self):
"""To Only show calls to this phone number. From Only show calls from this phone number. Status Only show calls currently in this status. May be queued, ringing, in-progress, completed, failed, busy, or no-answer. StartTime Only show calls that started on this date, given... | the_stack_v2_python_sparse | handlers/calls.py | youngj/Fake-Twilio-Api | train | 0 | |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(InTriggerDistanceToNextIntersection, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._distance = distance\nself._map = self._actor.get_world().get_map()\nwaypoint = self._map.get_waypoint(self._actor.get_location())\nwhile not waypoint.is_intersec... | <|body_start_0|>
super(InTriggerDistanceToNextIntersection, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._distance = distance
self._map = self._actor.get_world().get_map()
waypoint = self._map.get_waypoint(self... | This class contains the trigger (condition) for a distance to the next intersection of a scenario | InTriggerDistanceToNextIntersection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario"""
def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection'):
"""Setup trigger distance"""
<|body_0|>
def updat... | stack_v2_sparse_classes_75kplus_train_000820 | 25,380 | permissive | [
{
"docstring": "Setup trigger distance",
"name": "__init__",
"signature": "def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection')"
},
{
"docstring": "Check if the actor is within trigger distance to the intersection",
"name": "update",
"signature": "def update(se... | 2 | stack_v2_sparse_classes_30k_train_019318 | Implement the Python class `InTriggerDistanceToNextIntersection` described below.
Class description:
This class contains the trigger (condition) for a distance to the next intersection of a scenario
Method signatures and docstrings:
- def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection'): Se... | Implement the Python class `InTriggerDistanceToNextIntersection` described below.
Class description:
This class contains the trigger (condition) for a distance to the next intersection of a scenario
Method signatures and docstrings:
- def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection'): Se... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario"""
def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection'):
"""Setup trigger distance"""
<|body_0|>
def updat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario"""
def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection'):
"""Setup trigger distance"""
super(InTriggerDistanceToNextIntersect... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
a63fd1e5ce74cc53afb63c8c9a159ff2e8617bea | [
"super(SimpleCNN, self).__init__()\nself.embed_x = nn.Embedding(opt.n_words, opt.embed_size)\nself.embed_x.weight.data = self.embed_x.weight.data + torch.tensor(opt.W_emb, requires_grad=False)\nself.convs = nn.ModuleList([nn.Conv2d(in_channels=1, out_channels=opt.n_filters, kernel_size=(fs, opt.embed_size)) for fs ... | <|body_start_0|>
super(SimpleCNN, self).__init__()
self.embed_x = nn.Embedding(opt.n_words, opt.embed_size)
self.embed_x.weight.data = self.embed_x.weight.data + torch.tensor(opt.W_emb, requires_grad=False)
self.convs = nn.ModuleList([nn.Conv2d(in_channels=1, out_channels=opt.n_filters, ... | SimpleCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleCNN:
def __init__(self, opt):
"""CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen = 305 opt.n_words = None opt.embed_size = 300 opt.batch_size = 40 opt.max_epochs = 30 opt.dropout ... | stack_v2_sparse_classes_75kplus_train_000821 | 2,812 | permissive | [
{
"docstring": "CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen = 305 opt.n_words = None opt.embed_size = 300 opt.batch_size = 40 opt.max_epochs = 30 opt.dropout = 0.5 opt.ngram = 31 # Currently only support o... | 2 | stack_v2_sparse_classes_30k_train_015817 | Implement the Python class `SimpleCNN` described below.
Class description:
Implement the SimpleCNN class.
Method signatures and docstrings:
- def __init__(self, opt): CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen ... | Implement the Python class `SimpleCNN` described below.
Class description:
Implement the SimpleCNN class.
Method signatures and docstrings:
- def __init__(self, opt): CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen ... | 08f08cbe3d8afe27a2ad005cf8046a129c42bf78 | <|skeleton|>
class SimpleCNN:
def __init__(self, opt):
"""CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen = 305 opt.n_words = None opt.embed_size = 300 opt.batch_size = 40 opt.max_epochs = 30 opt.dropout ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleCNN:
def __init__(self, opt):
"""CNN constructor. Define the embedding layer, 3 conv3D layer with different window sizes followed one dense layer. @param: opt: type, object opt.maxlen = 305 opt.n_words = None opt.embed_size = 300 opt.batch_size = 40 opt.max_epochs = 30 opt.dropout = 0.5 opt.ngra... | the_stack_v2_python_sparse | MH-Term-Project-master/src/CNN_2classes/model.py | voghoei/DL-Fundation | train | 5 | |
cc17d071b4a5186f64619792d23a41a1018ffd9c | [
"self.clustering = clustering\nself.cluster_stabilities = cluster_stabilities\nself._descendant_cache = dict()",
"cache_id = (cluster_id_1, cluster_id_2)\nif cache_id in self._descendant_cache:\n return self._descendant_cache[cache_id]\ncluster_intersection = self.clustering[cluster_id_1] & self.clustering[clu... | <|body_start_0|>
self.clustering = clustering
self.cluster_stabilities = cluster_stabilities
self._descendant_cache = dict()
<|end_body_0|>
<|body_start_1|>
cache_id = (cluster_id_1, cluster_id_2)
if cache_id in self._descendant_cache:
return self._descendant_cache[c... | Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent. | ClusterDeduper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collec... | stack_v2_sparse_classes_75kplus_train_000822 | 4,546 | permissive | [
{
"docstring": ":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collections.Hashable]] :param cluster_stabilities: :type cluster_stabilities: dict[int, numbers.Real]",
"name": "__init__",
"signature": "def __init__(self, clustering, cluster_stabilities)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_val_000221 | Implement the Python class `ClusterDeduper` described below.
Class description:
Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent.
Method signatures and docstrings:
- def __init__(self, clustering, cluster_stabilities): :param clustering: cluster_i... | Implement the Python class `ClusterDeduper` described below.
Class description:
Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent.
Method signatures and docstrings:
- def __init__(self, clustering, cluster_stabilities): :param clustering: cluster_i... | bbf24fa7b80d32fae4b8c973a8fc3654eb63cadf | <|skeleton|>
class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterDeduper:
"""Finds child-parent relationships and removes children if parent is better than worse child, otherwise it removes parent."""
def __init__(self, clustering, cluster_stabilities):
""":param clustering: cluster_id -> set of points :type clustering: dict[int, set[collections.Hashabl... | the_stack_v2_python_sparse | python/analysis/ClusterDeduper.py | nog642/himag-release-asonam | train | 0 |
a580e0a51d4af0fab4505ddffc9ab2cfced35a95 | [
"if not root:\n return root\nnode = root\nwhile node:\n if node.left:\n rightmost = node.left\n while rightmost.right:\n rightmost = rightmost.right\n rightmost.right = node.right\n node.right = node.left\n node.left = None\n node = node.right\nreturn node",
... | <|body_start_0|>
if not root:
return root
node = root
while node:
if node.left:
rightmost = node.left
while rightmost.right:
rightmost = rightmost.right
rightmost.right = node.right
node.r... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def flatten(self, root: 'TreeNode') -> 'TreeNode':
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def flatten_(self, root: 'TreeNode') -> 'TreeNode':
"""Approach: DFS Time Complexity: O(N) Sp... | stack_v2_sparse_classes_75kplus_train_000823 | 1,397 | no_license | [
{
"docstring": "Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:",
"name": "flatten",
"signature": "def flatten(self, root: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "Approach: DFS Time Complexity: O(N) Space Comlexity: O(N) :param root: :return:",... | 2 | stack_v2_sparse_classes_30k_train_042111 | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def flatten(self, root: 'TreeNode') -> 'TreeNode': Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def flatten_(self, root: 'T... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def flatten(self, root: 'TreeNode') -> 'TreeNode': Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def flatten_(self, root: 'T... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class BinaryTree:
def flatten(self, root: 'TreeNode') -> 'TreeNode':
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def flatten_(self, root: 'TreeNode') -> 'TreeNode':
"""Approach: DFS Time Complexity: O(N) Sp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryTree:
def flatten(self, root: 'TreeNode') -> 'TreeNode':
"""Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
if not root:
return root
node = root
while node:
if node.left:
rightmost = ... | the_stack_v2_python_sparse | revisited/trees/flatten_bst.py | Shiv2157k/leet_code | train | 1 | |
50fbd1041198fbd05fd2c8c54a1eb0dfc2d9e081 | [
"self._center = center\nassert width is not None or width_fun is not None, 'Must specify width'\nif isinstance(center, numpy.ndarray) and width is not None:\n assert center.shape[0] == width.shape[0], 'for N element center, width must be Nx2'\n assert width.ndim == 2, 'for N element center, width must be Nx2'... | <|body_start_0|>
self._center = center
assert width is not None or width_fun is not None, 'Must specify width'
if isinstance(center, numpy.ndarray) and width is not None:
assert center.shape[0] == width.shape[0], 'for N element center, width must be Nx2'
assert width.ndim... | Implement a deadband | Deadband | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deadband:
"""Implement a deadband"""
def __init__(self, center, width=None, width_fun=None):
"""Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable upper / lower bounds. If center is a N vector then this ... | stack_v2_sparse_classes_75kplus_train_000824 | 5,273 | permissive | [
{
"docstring": "Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable upper / lower bounds. If center is a N vector then this should be Nx2 matrix of bounds. Optional (can specify fun) width_fun: width function, evaluates a point and ... | 3 | stack_v2_sparse_classes_30k_train_035611 | Implement the Python class `Deadband` described below.
Class description:
Implement a deadband
Method signatures and docstrings:
- def __init__(self, center, width=None, width_fun=None): Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable... | Implement the Python class `Deadband` described below.
Class description:
Implement a deadband
Method signatures and docstrings:
- def __init__(self, center, width=None, width_fun=None): Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class Deadband:
"""Implement a deadband"""
def __init__(self, center, width=None, width_fun=None):
"""Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable upper / lower bounds. If center is a N vector then this ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Deadband:
"""Implement a deadband"""
def __init__(self, center, width=None, width_fun=None):
"""Constructor Arguments: center: center of the deadband width: width, can be a scalar for symmetric deadband or a vector for variable upper / lower bounds. If center is a N vector then this should be Nx2... | the_stack_v2_python_sparse | pybots/src/filters/nonlinearities.py | aivian/robots | train | 0 |
fb39fcedec5da31ca04121de232b516c391cf017 | [
"self.server = MasterNode(debug=True, starting_task_port=12228)\nself.server.initialize()\nself.debug = debug",
"if self.debug:\n print(bcolors.INFO + '[Info]' + bcolors.ENDC + ' Waiting for a connection...')\nself.server.wait_for_connection()\nif self.debug:\n print(bcolors.INFO + '[Info]' + bcolors.ENDC +... | <|body_start_0|>
self.server = MasterNode(debug=True, starting_task_port=12228)
self.server.initialize()
self.debug = debug
<|end_body_0|>
<|body_start_1|>
if self.debug:
print(bcolors.INFO + '[Info]' + bcolors.ENDC + ' Waiting for a connection...')
self.server.wait_... | Creates a server to run an optimization through | OptimizerServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerServer:
"""Creates a server to run an optimization through"""
def __init__(self, debug):
"""Initializes the server"""
<|body_0|>
def serve(self, scenarios, img_directory):
"""Run the optimization server to optimize the scenarios to a set of images. :para... | stack_v2_sparse_classes_75kplus_train_000825 | 1,630 | permissive | [
{
"docstring": "Initializes the server",
"name": "__init__",
"signature": "def __init__(self, debug)"
},
{
"docstring": "Run the optimization server to optimize the scenarios to a set of images. :param images: The images to optimize the scenarios to :param scenarios: The scenarios to use during ... | 2 | stack_v2_sparse_classes_30k_train_009959 | Implement the Python class `OptimizerServer` described below.
Class description:
Creates a server to run an optimization through
Method signatures and docstrings:
- def __init__(self, debug): Initializes the server
- def serve(self, scenarios, img_directory): Run the optimization server to optimize the scenarios to a... | Implement the Python class `OptimizerServer` described below.
Class description:
Creates a server to run an optimization through
Method signatures and docstrings:
- def __init__(self, debug): Initializes the server
- def serve(self, scenarios, img_directory): Run the optimization server to optimize the scenarios to a... | fc31dd8de624f4a71c2c4b1bfe47a18f0b5d2f84 | <|skeleton|>
class OptimizerServer:
"""Creates a server to run an optimization through"""
def __init__(self, debug):
"""Initializes the server"""
<|body_0|>
def serve(self, scenarios, img_directory):
"""Run the optimization server to optimize the scenarios to a set of images. :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptimizerServer:
"""Creates a server to run an optimization through"""
def __init__(self, debug):
"""Initializes the server"""
self.server = MasterNode(debug=True, starting_task_port=12228)
self.server.initialize()
self.debug = debug
def serve(self, scenarios, img_dir... | the_stack_v2_python_sparse | SUASImageParser/optimizers/server.py | peterhusisian/SUAS-Competition | train | 0 |
714657246d76eacbe20505e9e7a984409673dcef | [
"self._fcn = fcn\nself._fixed_state = fixed_state\nself._idcs = idcs",
"state = self._fixed_state.clone()\nstate = state.repeat(varying.shape[0], varying.shape[1], 1)\nstate[:, :, self._idcs] = varying\nreturn self._fcn(state)"
] | <|body_start_0|>
self._fcn = fcn
self._fixed_state = fixed_state
self._idcs = idcs
<|end_body_0|>
<|body_start_1|>
state = self._fixed_state.clone()
state = state.repeat(varying.shape[0], varying.shape[1], 1)
state[:, :, self._idcs] = varying
return self._fcn(sta... | Wrap the values function to be able to only pass a subset of the state. | wrap_value_fcn | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wrap_value_fcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state valu... | stack_v2_sparse_classes_75kplus_train_000826 | 4,027 | permissive | [
{
"docstring": "Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values held constant for the evaluation, dimension matches the Module's input layer :param idcs: indices of the state dimensions where the `fixed_state` is replaced which values from ou... | 2 | stack_v2_sparse_classes_30k_train_041692 | Implement the Python class `wrap_value_fcn` described below.
Class description:
Wrap the values function to be able to only pass a subset of the state.
Method signatures and docstrings:
- def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list): Constructor :param fcn: function to wrap with an input dim... | Implement the Python class `wrap_value_fcn` described below.
Class description:
Wrap the values function to be able to only pass a subset of the state.
Method signatures and docstrings:
- def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list): Constructor :param fcn: function to wrap with an input dim... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class wrap_value_fcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wrap_value_fcn:
"""Wrap the values function to be able to only pass a subset of the state."""
def __init__(self, fcn: nn.Module, fixed_state: to.Tensor, idcs: list):
"""Constructor :param fcn: function to wrap with an input dimension >= `len(args.idcs)` :param fixed_state: state values held const... | the_stack_v2_python_sparse | Pyrado/scripts/plotting/plot_value_fcn.py | jacarvalho/SimuRLacra | train | 0 |
ab2505776a3967f7e4f497ce64dfd80e1ce3d398 | [
"cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'\ntry:\n tx.run(cql, node_value=node_value)\nexcept Exception as e:\n print(str(e))",
"if node_value_1 is None and node_type_1 is None:\n cql = 'MATCH ()-[u:' + relationship + ']-(w:' + node_type_2 + '{name:$node_value_2}) DELETE u;'\... | <|body_start_0|>
cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'
try:
tx.run(cql, node_value=node_value)
except Exception as e:
print(str(e))
<|end_body_0|>
<|body_start_1|>
if node_value_1 is None and node_type_1 is None:
cql =... | This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplate code and allows for a clear separation ... | DeleteTransactionFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_75kplus_train_000827 | 12,659 | no_license | [
{
"docstring": "Delete node and all respective relationships :param tx: :param node_value: :param node_type: :return:",
"name": "delete_node",
"signature": "def delete_node(tx, node_value, node_type)"
},
{
"docstring": "Delete Utterance Relationship, based on input nodes :param tx: :param name1:... | 2 | stack_v2_sparse_classes_30k_train_029352 | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplat... | the_stack_v2_python_sparse | deliverable/SourceCode/streaming/src/graph/transaction_functions.py | eldrad294/ICS5114_Practical_Assignment | train | 0 |
5d1b586568c68f216ce7a401ef9343ed1b4b4a0d | [
"self.s1 = []\nself.s2 = []\nself.size1 = 0\nself.size2 = 0",
"self.s1.append(x)\nif self.size2 > 0:\n minV, minInd = self.s2[self.size2 - 1]\n if x <= minV:\n self.s2.append((x, self.size1))\n self.size2 += 1\nelse:\n self.s2.append((x, self.size1))\n self.size2 += 1\nself.size1 += 1",
... | <|body_start_0|>
self.s1 = []
self.s2 = []
self.size1 = 0
self.size2 = 0
<|end_body_0|>
<|body_start_1|>
self.s1.append(x)
if self.size2 > 0:
minV, minInd = self.s2[self.size2 - 1]
if x <= minV:
self.s2.append((x, self.size1))
... | use two stack stack1: all the current elements stack2: the mininum element of history | MinStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinStack:
"""use two stack stack1: all the current elements stack2: the mininum element of history"""
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self... | stack_v2_sparse_classes_75kplus_train_000828 | 2,096 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type x: int :rtype: void",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: void",
"name": "pop",
"signature": "def ... | 5 | null | Implement the Python class `MinStack` described below.
Class description:
use two stack stack1: all the current elements stack2: the mininum element of history
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :... | Implement the Python class `MinStack` described below.
Class description:
use two stack stack1: all the current elements stack2: the mininum element of history
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: void
- def pop(self): :... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class MinStack:
"""use two stack stack1: all the current elements stack2: the mininum element of history"""
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: void"""
<|body_1|>
def pop(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinStack:
"""use two stack stack1: all the current elements stack2: the mininum element of history"""
def __init__(self):
"""initialize your data structure here."""
self.s1 = []
self.s2 = []
self.size1 = 0
self.size2 = 0
def push(self, x):
""":type x: ... | the_stack_v2_python_sparse | leetcode/155.py | liuweilin17/algorithm | train | 3 |
71886b7239dada55420d84dbe55c5e989f442cd2 | [
"self.func = func\nself.as_string = as_string\nself.unpack_list = unpack_list",
"if isinstance(value, list) and self.unpack_list:\n return [self(v) for v in value]\nif not isinstance(value, str):\n if self.as_string:\n return self.func(str(value))\n raise ValueError('invalid argument {}'.format(va... | <|body_start_0|>
self.func = func
self.as_string = as_string
self.unpack_list = unpack_list
<|end_body_0|>
<|body_start_1|>
if isinstance(value, list) and self.unpack_list:
return [self(v) for v in value]
if not isinstance(value, str):
if self.as_string:
... | Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function to compute the final result. | StringFunction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringFunction:
"""Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function to compute the final result."""
d... | stack_v2_sparse_classes_75kplus_train_000829 | 9,837 | permissive | [
{
"docstring": "Initialize the object properties. Parameters ---------- func: callable String function that is executed on given argument values. as_string: bool, optional Use string representation for non-string values. unpack_list: bool, default=False Unpack list values if set to True.",
"name": "__init__... | 2 | null | Implement the Python class `StringFunction` described below.
Class description:
Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function... | Implement the Python class `StringFunction` described below.
Class description:
Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class StringFunction:
"""Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function to compute the final result."""
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringFunction:
"""Evaluate a given string function on a given scalar value. This class is a wrapper for common string functions that (i) allows to defined behavior for arguments that are not strings, and (ii) pass the modified value on to a wrapped function to compute the final result."""
def __init__(s... | the_stack_v2_python_sparse | openclean/function/eval/text.py | Denisfench/openclean-core | train | 0 |
2b896966bd93afb60e6662b5400c54aa3edef7ff | [
"full_layer_specs = []\nfor i, layer_spec in enumerate(layer_specs):\n stride = 2 if i == 0 else 1\n full_layer_spec = [3, layer_spec[0], layer_spec[1], stride]\n full_layer_specs.append(full_layer_spec)\nsuper().__init__(name=name, layer_specs=full_layer_specs, activation_fn=activation_fn, last_activation... | <|body_start_0|>
full_layer_specs = []
for i, layer_spec in enumerate(layer_specs):
stride = 2 if i == 0 else 1
full_layer_spec = [3, layer_spec[0], layer_spec[1], stride]
full_layer_specs.append(full_layer_spec)
super().__init__(name=name, layer_specs=full_la... | DownSamplingConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [nu... | stack_v2_sparse_classes_75kplus_train_000830 | 6,555 | no_license | [
{
"docstring": ":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_output_features, dilation]. :param activation_fn: Tensorflow activation function. This will not be applied on the la... | 2 | stack_v2_sparse_classes_30k_train_033845 | Implement the Python class `DownSamplingConnection` described below.
Class description:
Implement the DownSamplingConnection class.
Method signatures and docstrings:
- def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None): :param name: Str. For variable scoping. :param layer_specs: Array o... | Implement the Python class `DownSamplingConnection` described below.
Class description:
Implement the DownSamplingConnection class.
Method signatures and docstrings:
- def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None): :param name: Str. For variable scoping. :param layer_specs: Array o... | 494d503c729ba018614fc742f1aee1e48d37127e | <|skeleton|>
class DownSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DownSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_output_featu... | the_stack_v2_python_sparse | context_interp/gridnet/connections/connections.py | NeedsMorePie/interpolator | train | 2 | |
7d96dfa1689dbd19f6c00abe9da23a14f7436c5d | [
"log.info('Starting Infrastructure Layer...')\nself.topology = None\nsuper(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)",
"log.debug('Initializing Infrastructure Layer...')\nCONFIG.set_layer_loaded(self._core_name)\nmn_opts = CONFIG.get_mn_network_opts()\noptional_topo = getattr(self, '_topo', Non... | <|body_start_0|>
log.info('Starting Infrastructure Layer...')
self.topology = None
super(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)
<|end_body_0|>
<|body_start_1|>
log.debug('Initializing Infrastructure Layer...')
CONFIG.set_layer_loaded(self._core_name)
... | Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point. | InfrastructureLayerAPI | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_75kplus_train_000831 | 4,274 | permissive | [
{
"docstring": ".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractAPI.__init__>`",
"name": "__init__",
"signature": "def __init__(self, standalone=False, **kwargs)"
},
{
"docstring": ".. seealso:: :func:`AbstractAPI.initialize() <escape.util.api.AbstractAPI.initialize>`",
"... | 4 | stack_v2_sparse_classes_30k_train_000240 | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractA... | the_stack_v2_python_sparse | escape/escape/infr/il_API.py | JerryLX/escape | train | 0 |
89b4b214fc339562aa1cd68f9db9cc29d676fc1d | [
"if X_mean is None or X_std is None:\n X_mean = np.array(X).mean(axis=axis)\n X_std = np.array(X).std(axis=axis)\n X = (X - X_mean) / X_std\nelse:\n X = (X - X_mean) / X_std\nreturn (X, X_mean, X_std)",
"if X_mean is None or X_std is None:\n X_mean = np.array(X).mean()\n X_std = np.array(X).std(... | <|body_start_0|>
if X_mean is None or X_std is None:
X_mean = np.array(X).mean(axis=axis)
X_std = np.array(X).std(axis=axis)
X = (X - X_mean) / X_std
else:
X = (X - X_mean) / X_std
return (X, X_mean, X_std)
<|end_body_0|>
<|body_start_1|>
... | Preprocessing mixin for static data | StaticPrepMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticPrepMixin:
"""Preprocessing mixin for static data"""
def normalize(self, X, X_mean=None, X_std=None, axis=0):
"""Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Scalar X_std : Scalar"""
<|body_0|>
def global_... | stack_v2_sparse_classes_75kplus_train_000832 | 8,485 | no_license | [
{
"docstring": "Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Scalar X_std : Scalar",
"name": "normalize",
"signature": "def normalize(self, X, X_mean=None, X_std=None, axis=0)"
},
{
"docstring": "Globally normalize X into zero mean and ... | 3 | stack_v2_sparse_classes_30k_train_010179 | Implement the Python class `StaticPrepMixin` described below.
Class description:
Preprocessing mixin for static data
Method signatures and docstrings:
- def normalize(self, X, X_mean=None, X_std=None, axis=0): Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Sca... | Implement the Python class `StaticPrepMixin` described below.
Class description:
Preprocessing mixin for static data
Method signatures and docstrings:
- def normalize(self, X, X_mean=None, X_std=None, axis=0): Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Sca... | 94fe4208f6450d603d37e5a376dc85d988c9f639 | <|skeleton|>
class StaticPrepMixin:
"""Preprocessing mixin for static data"""
def normalize(self, X, X_mean=None, X_std=None, axis=0):
"""Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Scalar X_std : Scalar"""
<|body_0|>
def global_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StaticPrepMixin:
"""Preprocessing mixin for static data"""
def normalize(self, X, X_mean=None, X_std=None, axis=0):
"""Globally normalize X into zero mean and unit variance Parameters ---------- X : list or ndArray X_mean : Scalar X_std : Scalar"""
if X_mean is None or X_std is None:
... | the_stack_v2_python_sparse | cle/data/prep.py | kyunghyuncho/cle | train | 1 |
e309c12860d4be371f119cbd0df795238ac86d4d | [
"n = len(M)\ncircelNum = 0\nvisited = [0] * n\n\ndef dfs(visited, i):\n for j in range(0, n):\n if M[i][j] == 1 and visited[j] == 0:\n visited[j] = 1\n dfs(visited, j)\nfor i in range(0, n):\n if visited[i] == 0:\n dfs(visited, i)\n circelNum += 1\nreturn circelNum",... | <|body_start_0|>
n = len(M)
circelNum = 0
visited = [0] * n
def dfs(visited, i):
for j in range(0, n):
if M[i][j] == 1 and visited[j] == 0:
visited[j] = 1
dfs(visited, j)
for i in range(0, n):
if vis... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_1(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(M)
circelNum = 0
... | stack_v2_sparse_classes_75kplus_train_000833 | 2,521 | permissive | [
{
"docstring": ":type M: List[List[int]] :rtype: int",
"name": "findCircleNum",
"signature": "def findCircleNum(self, M)"
},
{
"docstring": ":type M: List[List[int]] :rtype: int",
"name": "findCircleNum_1",
"signature": "def findCircleNum_1(self, M)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026424 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_1(self, M): :type M: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_1(self, M): :type M: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def findC... | 7870a50311e67f431fa3907c7c6a74453f0795a5 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_1(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
n = len(M)
circelNum = 0
visited = [0] * n
def dfs(visited, i):
for j in range(0, n):
if M[i][j] == 1 and visited[j] == 0:
visited[j] = 1
... | the_stack_v2_python_sparse | searchAlgorith/findCircleNumber_547.py | soarflighting/LeetCode_Notes | train | 0 | |
9c6ad9f90f4ff81446f9cd48d5acd418456d3215 | [
"new_head, pointer = (None, head)\nwhile k:\n next_node = pointer.next\n pointer.next = new_head\n new_head = pointer\n pointer = next_node\n k -= 1\nreturn new_head",
"pointer, count = (head, 0)\nwhile count < k and pointer:\n pointer = pointer.next\n count += 1\nif count == k:\n reverse_... | <|body_start_0|>
new_head, pointer = (None, head)
while k:
next_node = pointer.next
pointer.next = new_head
new_head = pointer
pointer = next_node
k -= 1
return new_head
<|end_body_0|>
<|body_start_1|>
pointer, count = (head, 0... | KGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KGroup:
def reverse_linked_list(self, head: ListNode, k: int) -> ListNode:
"""Reverse the list from k nodes :param head: :param k: :return:"""
<|body_0|>
def reverse_k_group_(self, head: ListNode, k: int) -> ListNode:
"""Approach: Recursion Time Complexity: O(N) Spac... | stack_v2_sparse_classes_75kplus_train_000834 | 3,145 | no_license | [
{
"docstring": "Reverse the list from k nodes :param head: :param k: :return:",
"name": "reverse_linked_list",
"signature": "def reverse_linked_list(self, head: ListNode, k: int) -> ListNode"
},
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(N/ k) :param head: :par... | 3 | stack_v2_sparse_classes_30k_test_001902 | Implement the Python class `KGroup` described below.
Class description:
Implement the KGroup class.
Method signatures and docstrings:
- def reverse_linked_list(self, head: ListNode, k: int) -> ListNode: Reverse the list from k nodes :param head: :param k: :return:
- def reverse_k_group_(self, head: ListNode, k: int) ... | Implement the Python class `KGroup` described below.
Class description:
Implement the KGroup class.
Method signatures and docstrings:
- def reverse_linked_list(self, head: ListNode, k: int) -> ListNode: Reverse the list from k nodes :param head: :param k: :return:
- def reverse_k_group_(self, head: ListNode, k: int) ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class KGroup:
def reverse_linked_list(self, head: ListNode, k: int) -> ListNode:
"""Reverse the list from k nodes :param head: :param k: :return:"""
<|body_0|>
def reverse_k_group_(self, head: ListNode, k: int) -> ListNode:
"""Approach: Recursion Time Complexity: O(N) Spac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KGroup:
def reverse_linked_list(self, head: ListNode, k: int) -> ListNode:
"""Reverse the list from k nodes :param head: :param k: :return:"""
new_head, pointer = (None, head)
while k:
next_node = pointer.next
pointer.next = new_head
new_head = point... | the_stack_v2_python_sparse | data_structures/linked_list/reverse_node_in_k_group.py | Shiv2157k/leet_code | train | 1 | |
6d7e0847a3fdb9b19b4f774763186fab032739a3 | [
"self.total = total\nself.length = length\nself.decimals = decimals\nself.fill = fill",
"percent = ('{0:.' + str(self.decimals) + 'f}').format(100 * (iteration / float(self.total)))\nfill_len = self.length * iteration // self.total\nbar = self.fill * fill_len + ' ' * (self.length - fill_len)\nprint(f'\\r{prefix} ... | <|body_start_0|>
self.total = total
self.length = length
self.decimals = decimals
self.fill = fill
<|end_body_0|>
<|body_start_1|>
percent = ('{0:.' + str(self.decimals) + 'f}').format(100 * (iteration / float(self.total)))
fill_len = self.length * iteration // self.tota... | ProgressBar | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressBar:
def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='='):
""":param total: total iterations :param length: character length of bar :param decimals: positive number of decimals in percent complete :param fill: bar fill character"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_000835 | 8,380 | permissive | [
{
"docstring": ":param total: total iterations :param length: character length of bar :param decimals: positive number of decimals in percent complete :param fill: bar fill character",
"name": "__init__",
"signature": "def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='=')"
},
... | 2 | null | Implement the Python class `ProgressBar` described below.
Class description:
Implement the ProgressBar class.
Method signatures and docstrings:
- def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='='): :param total: total iterations :param length: character length of bar :param decimals: posit... | Implement the Python class `ProgressBar` described below.
Class description:
Implement the ProgressBar class.
Method signatures and docstrings:
- def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='='): :param total: total iterations :param length: character length of bar :param decimals: posit... | 01c3fc3406ebf19798cedcddbe829ae5339e1424 | <|skeleton|>
class ProgressBar:
def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='='):
""":param total: total iterations :param length: character length of bar :param decimals: positive number of decimals in percent complete :param fill: bar fill character"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgressBar:
def __init__(self, total: int, length: int=40, decimals: int=1, fill: str='='):
""":param total: total iterations :param length: character length of bar :param decimals: positive number of decimals in percent complete :param fill: bar fill character"""
self.total = total
s... | the_stack_v2_python_sparse | merlion/utils/misc.py | salesforce/Merlion | train | 2,905 | |
fb8f07ce47cd5e35911bc23911a20393a1d01004 | [
"def helper(root):\n res = [0, 0]\n if not root:\n return res\n left, right = (helper(root.left), helper(root.right))\n res[0] = max(left) + max(right)\n res[1] = root.val + left[0] + right[0]\n return res\nreturn max(helper(root))",
"def helper(root, mem):\n if not root:\n retu... | <|body_start_0|>
def helper(root):
res = [0, 0]
if not root:
return res
left, right = (helper(root.left), helper(root.right))
res[0] = max(left) + max(right)
res[1] = root.val + left[0] + right[0]
return res
return m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rob2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def rob3(self, root):
""":type root: TreeNode :rtype: int"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_000836 | 3,633 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob",
"signature": "def rob(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob2",
"signature": "def rob2(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob3",... | 3 | stack_v2_sparse_classes_30k_train_003117 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, root): :type root: TreeNode :rtype: int
- def rob2(self, root): :type root: TreeNode :rtype: int
- def rob3(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 rob(self, root): :type root: TreeNode :rtype: int
- def rob2(self, root): :type root: TreeNode :rtype: int
- def rob3(self, root): :type root: TreeNode :rtype: int
<|skeleto... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rob2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def rob3(self, root):
""":type root: TreeNode :rtype: int"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
def helper(root):
res = [0, 0]
if not root:
return res
left, right = (helper(root.left), helper(root.right))
res[0] = max(left) + max(right)
res[1] ... | the_stack_v2_python_sparse | code337HouseRobberIII.py | cybelewang/leetcode-python | train | 0 | |
1924a55670854374c9a2db135cb0dd31ffcbf783 | [
"super(EthereumConnector, self).__init__(config, eth_registry_instance, eth_worker_instance, eth_work_order_instance, eth_wo_receipt_instance)\nself._config = config\nself._wo_evt = wo_contract_instance_evt",
"def workorder_event_handler_func(event, account, contract):\n \"\"\"\n The function retrie... | <|body_start_0|>
super(EthereumConnector, self).__init__(config, eth_registry_instance, eth_worker_instance, eth_work_order_instance, eth_wo_receipt_instance)
self._config = config
self._wo_evt = wo_contract_instance_evt
<|end_body_0|>
<|body_start_1|>
def workorder_event_handler_func(e... | This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to Avalon on behalf of the client. The service also invokes smart contract APIs (eg: wor... | EthereumConnector | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EthereumConnector:
"""This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to Avalon on behalf of the client. The serv... | stack_v2_sparse_classes_75kplus_train_000837 | 4,288 | permissive | [
{
"docstring": "initialize connector @param config - dict containing config params @param eth_registry_instance - object of EthereumWorkerRegistryListImpl @param eth_worker_instance - object of EthereumWorkerRegistryImpl @param eth_work_order_instance - object of EthereumWorkOrderProxyImpl @param eth_wo_receipt... | 2 | stack_v2_sparse_classes_30k_train_015846 | Implement the Python class `EthereumConnector` described below.
Class description:
This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to A... | Implement the Python class `EthereumConnector` described below.
Class description:
This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to A... | 8afeab63a04b681bc44c66e807e70c27c8f1e589 | <|skeleton|>
class EthereumConnector:
"""This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to Avalon on behalf of the client. The serv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EthereumConnector:
"""This class is the bridge between the Ethereum blockchain and the Avalon core. It listens for events generated by the Ethereum blockchain. It handles event data corresponding to the event (eg: workOrderSubmitted and submits requests to Avalon on behalf of the client. The service also invo... | the_stack_v2_python_sparse | blockchain_connector/ethereum/ethereum_connector/ethereum_connector.py | stephmackenz/avalon | train | 1 |
effc8683fe60022859a981c31552c62242154274 | [
"team = Team.get_if_exists(team_id)\nuser = User.get_if_exists(user_id)\nTribe.validate_access(team.tribe_id, current_user)\nif int(team_id) in user.managing_ids():\n response = Response()\n response.status_code = 204\n return response\nmanager_link = TeamUserLink(team_id=team_id, user_id=user_id, manager=... | <|body_start_0|>
team = Team.get_if_exists(team_id)
user = User.get_if_exists(user_id)
Tribe.validate_access(team.tribe_id, current_user)
if int(team_id) in user.managing_ids():
response = Response()
response.status_code = 204
return response
m... | Single team manager resource. | TeamManagerRes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamManagerRes:
"""Single team manager resource."""
def put(self, team_id, user_id):
"""Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id required: true description: Id of the team. schema: - type:... | stack_v2_sparse_classes_75kplus_train_000838 | 18,061 | permissive | [
{
"docstring": "Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id required: true description: Id of the team. schema: - type: integer - in: path name: user_id required: true description: Id of the user. schema: - type: intege... | 2 | stack_v2_sparse_classes_30k_train_047738 | Implement the Python class `TeamManagerRes` described below.
Class description:
Single team manager resource.
Method signatures and docstrings:
- def put(self, team_id, user_id): Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id re... | Implement the Python class `TeamManagerRes` described below.
Class description:
Single team manager resource.
Method signatures and docstrings:
- def put(self, team_id, user_id): Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id re... | d77224054f99579fbdab4e302871cd33a611e249 | <|skeleton|>
class TeamManagerRes:
"""Single team manager resource."""
def put(self, team_id, user_id):
"""Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id required: true description: Id of the team. schema: - type:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamManagerRes:
"""Single team manager resource."""
def put(self, team_id, user_id):
"""Add manager to the team. Roles allowed: admin, editor. --- tags: - teams security: - bearerAuth: [] properties: - in: path name: team_id required: true description: Id of the team. schema: - type: integer - in... | the_stack_v2_python_sparse | backend/resources/teams.py | nokia-wroclaw/innovativeproject-health-care | train | 5 |
73ee1bcd02aad80363ad70b5a71c5e1ab11ef13f | [
"self.kernel_fn = kernel_fn\nself.verbose = verbose\nself.random_state = check_random_state(random_state)",
"x_vector = weighted_data\nalphas, _, coefs = lars_path(x_vector, weighted_labels, method='lasso', verbose=False)\nreturn (alphas, coefs)",
"clf = Ridge(alpha=0, fit_intercept=True, random_state=self.rand... | <|body_start_0|>
self.kernel_fn = kernel_fn
self.verbose = verbose
self.random_state = check_random_state(random_state)
<|end_body_0|>
<|body_start_1|>
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector, weighted_labels, method='lasso', verbose=False)
return ... | Class for learning a locally linear sparse model from perturbed data | LimeBase | [
"MIT",
"BSD-2-Clause",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimeBase:
"""Class for learning a locally linear sparse model from perturbed data"""
def __init__(self, kernel_fn, verbose=False, random_state=None):
"""Init function Args: kernel_fn: function that transforms an array of distances into an array of proximity values (floats). verbose: ... | stack_v2_sparse_classes_75kplus_train_000839 | 8,448 | permissive | [
{
"docstring": "Init function Args: kernel_fn: function that transforms an array of distances into an array of proximity values (floats). verbose: if true, print local prediction values from linear model. random_state: an integer or numpy.RandomState that will be used to generate random numbers. If None, the ra... | 5 | stack_v2_sparse_classes_30k_train_029187 | Implement the Python class `LimeBase` described below.
Class description:
Class for learning a locally linear sparse model from perturbed data
Method signatures and docstrings:
- def __init__(self, kernel_fn, verbose=False, random_state=None): Init function Args: kernel_fn: function that transforms an array of distan... | Implement the Python class `LimeBase` described below.
Class description:
Class for learning a locally linear sparse model from perturbed data
Method signatures and docstrings:
- def __init__(self, kernel_fn, verbose=False, random_state=None): Init function Args: kernel_fn: function that transforms an array of distan... | f59730dc7a8735232ef417685800652372c3b5dd | <|skeleton|>
class LimeBase:
"""Class for learning a locally linear sparse model from perturbed data"""
def __init__(self, kernel_fn, verbose=False, random_state=None):
"""Init function Args: kernel_fn: function that transforms an array of distances into an array of proximity values (floats). verbose: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LimeBase:
"""Class for learning a locally linear sparse model from perturbed data"""
def __init__(self, kernel_fn, verbose=False, random_state=None):
"""Init function Args: kernel_fn: function that transforms an array of distances into an array of proximity values (floats). verbose: if true, prin... | the_stack_v2_python_sparse | tensorwatch/saliency/lime/lime_base.py | microsoft/tensorwatch | train | 3,626 |
80b5da13b1e40084ad2e43d0d0ba440ef628f746 | [
"winH = 0\nwinW = 400\nfor line in msg_list:\n winH += line[1] + line[1] / 2\nwinH += 70\nself.win = GraphWin('Help for Dice Poker', winW, winH)\nself.win.setBackground(color_rgb(80, 0, 0))\nline_pos = 30\nprev_line_ht = msg_list[0][1]\nself.display_msg(winW / 2, line_pos, msg_list[0][0], 'white', 'white', prev_... | <|body_start_0|>
winH = 0
winW = 400
for line in msg_list:
winH += line[1] + line[1] / 2
winH += 70
self.win = GraphWin('Help for Dice Poker', winW, winH)
self.win.setBackground(color_rgb(80, 0, 0))
line_pos = 30
prev_line_ht = msg_list[0][1]
... | HelpScreen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpScreen:
def __init__(self, msg_list):
"""HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]"""
<|body_0|>
def display_msg(self, x, y, m, c, o, s):
"""Helper method to display a... | stack_v2_sparse_classes_75kplus_train_000840 | 2,584 | no_license | [
{
"docstring": "HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]",
"name": "__init__",
"signature": "def __init__(self, msg_list)"
},
{
"docstring": "Helper method to display a message :param x: int/float ->... | 3 | stack_v2_sparse_classes_30k_train_019402 | Implement the Python class `HelpScreen` described below.
Class description:
Implement the HelpScreen class.
Method signatures and docstrings:
- def __init__(self, msg_list): HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]
- def ... | Implement the Python class `HelpScreen` described below.
Class description:
Implement the HelpScreen class.
Method signatures and docstrings:
- def __init__(self, msg_list): HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]
- def ... | 6588c0ebfa932fbae7eec11c20270e4a8e969377 | <|skeleton|>
class HelpScreen:
def __init__(self, msg_list):
"""HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]"""
<|body_0|>
def display_msg(self, x, y, m, c, o, s):
"""Helper method to display a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HelpScreen:
def __init__(self, msg_list):
"""HelpScreen class for the GUI Dice Poker game :param msg: list -> lines of text to display [[line 1, font size], [line 2, font size], ...]"""
winH = 0
winW = 400
for line in msg_list:
winH += line[1] + line[1] / 2
... | the_stack_v2_python_sparse | Chapter12/U12_Ex01_DicePoker/U12_Ex01_HelpScreen.py | billm79/COOP2018 | train | 3 | |
529a3f31a04033bd3da99b20a8c6df469fe7f466 | [
"tails_pcr = TargetEnrichmentType.objects.get(name='PCR_with_tails')\ntargets = [target for target in target_names]\nfor tgt in Target.objects.filter(name__in=targets):\n for te in tgt.targetenrichment_set.all().filter(type=tails_pcr):\n for mpx in te.primersmultiplex_set.all():\n try:\n ... | <|body_start_0|>
tails_pcr = TargetEnrichmentType.objects.get(name='PCR_with_tails')
targets = [target for target in target_names]
for tgt in Target.objects.filter(name__in=targets):
for te in tgt.targetenrichment_set.all().filter(type=tails_pcr):
for mpx in te.primer... | CLineageWebServices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLineageWebServices:
def get_targets_data(ctx, target_names):
"""Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output columns: # Target name # Target: MS/Other Mutation # Basic Unit size # Expected Number of repeats # Basic Un... | stack_v2_sparse_classes_75kplus_train_000841 | 14,071 | no_license | [
{
"docstring": "Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output columns: # Target name # Target: MS/Other Mutation # Basic Unit size # Expected Number of repeats # Basic Unit Type # Chromosome # Length MS # Primer sequence - Left # Primer Tm - L... | 5 | stack_v2_sparse_classes_30k_train_012967 | Implement the Python class `CLineageWebServices` described below.
Class description:
Implement the CLineageWebServices class.
Method signatures and docstrings:
- def get_targets_data(ctx, target_names): Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output ... | Implement the Python class `CLineageWebServices` described below.
Class description:
Implement the CLineageWebServices class.
Method signatures and docstrings:
- def get_targets_data(ctx, target_names): Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output ... | e11a4aeec69d65c6d9fa74516ee48f50eccbef21 | <|skeleton|>
class CLineageWebServices:
def get_targets_data(ctx, target_names):
"""Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output columns: # Target name # Target: MS/Other Mutation # Basic Unit size # Expected Number of repeats # Basic Un... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CLineageWebServices:
def get_targets_data(ctx, target_names):
"""Elaborate query for targets. MATLAB example: get_targets_data(service_obj, struct('string',{{'Seq05944'}})) output columns: # Target name # Target: MS/Other Mutation # Basic Unit size # Expected Number of repeats # Basic Unit Type # Chro... | the_stack_v2_python_sparse | soap/views.py | shapirolab/clineage | train | 4 | |
24ef36fea0ae11af52da6ec553893a71854d273f | [
"if projects_directory is None:\n self.projects_directory = self.Defaults.projects_directory\nelse:\n self.projects_directory = projects_directory",
"if projects_directory is None:\n projects_directory = self.projects_directory\nname = support.ensure_end(_string, '.sublime-project')\nreturn name in self.... | <|body_start_0|>
if projects_directory is None:
self.projects_directory = self.Defaults.projects_directory
else:
self.projects_directory = projects_directory
<|end_body_0|>
<|body_start_1|>
if projects_directory is None:
projects_directory = self.projects_dir... | Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory). | OpenProjectFromName | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenProjectFromName:
"""Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory)."""
def __init__(self, projects_directory=None):
"""Input is project file, in standard directory for subli... | stack_v2_sparse_classes_75kplus_train_000842 | 8,112 | permissive | [
{
"docstring": "Input is project file, in standard directory for sublime-project files.",
"name": "__init__",
"signature": "def __init__(self, projects_directory=None)"
},
{
"docstring": "@type: _string: str @returns: bool",
"name": "matches",
"signature": "def matches(self, _string, pro... | 4 | stack_v2_sparse_classes_30k_train_040045 | Implement the Python class `OpenProjectFromName` described below.
Class description:
Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).
Method signatures and docstrings:
- def __init__(self, projects_directory=None... | Implement the Python class `OpenProjectFromName` described below.
Class description:
Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory).
Method signatures and docstrings:
- def __init__(self, projects_directory=None... | 6504a00e70e9c6be365f92dad69f4f4d5df41cf9 | <|skeleton|>
class OpenProjectFromName:
"""Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory)."""
def __init__(self, projects_directory=None):
"""Input is project file, in standard directory for subli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenProjectFromName:
"""Attempt to open a project file by looking in a standardized location for all project files (usually located in the user's SublimeText packages directory)."""
def __init__(self, projects_directory=None):
"""Input is project file, in standard directory for sublime-project fi... | the_stack_v2_python_sparse | sublp/dispatch_cases.py | OaklandPeters/sublp | train | 0 |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(IQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=... | <|body_start_0|>
super(IQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = FCE... | IQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[n... | stack_v2_sparse_classes_75kplus_train_000843 | 30,380 | permissive | [
{
"docstring": "Overview: Init the IQN Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to p... | 2 | stack_v2_sparse_classes_30k_train_041612 | Implement the Python class `IQN` described below.
Class description:
Implement the IQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None,... | Implement the Python class `IQN` described below.
Class description:
Implement the IQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None,... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class IQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, quantile_embedding_size: int=128, activation: Optional[nn.Module]=nn.R... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
91742a30faed492ffb6aa44a7b797276e22b919a | [
"self.coefficients = asfunction(coefficients)\nself.x = asfunction(x)\nif null is None:\n self.null = Constant(0.0)\nelse:\n self.null = asfunction(null)",
"coefficients = self.coefficients(ps)\nx = self.x(ps)\nnull = self.null(ps)\nresult = null\nfor order, coefficient in enumerate(coefficients):\n resu... | <|body_start_0|>
self.coefficients = asfunction(coefficients)
self.x = asfunction(x)
if null is None:
self.null = Constant(0.0)
else:
self.null = asfunction(null)
<|end_body_0|>
<|body_start_1|>
coefficients = self.coefficients(ps)
x = self.x(ps)
... | Implements polynomials with Functions a coefficients and argument. | Polynomial | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Polynomial:
"""Implements polynomials with Functions a coefficients and argument."""
def __init__(self, coefficients, x=None, null=None):
"""*coefficients* gives the coefficients of the polynomial. *x* gives the argument of the polynomial. *null* is the null with respect to +, and ``... | stack_v2_sparse_classes_75kplus_train_000844 | 1,013 | permissive | [
{
"docstring": "*coefficients* gives the coefficients of the polynomial. *x* gives the argument of the polynomial. *null* is the null with respect to +, and ``None`` means ordinary 0.0.",
"name": "__init__",
"signature": "def __init__(self, coefficients, x=None, null=None)"
},
{
"docstring": "Re... | 2 | null | Implement the Python class `Polynomial` described below.
Class description:
Implements polynomials with Functions a coefficients and argument.
Method signatures and docstrings:
- def __init__(self, coefficients, x=None, null=None): *coefficients* gives the coefficients of the polynomial. *x* gives the argument of the... | Implement the Python class `Polynomial` described below.
Class description:
Implements polynomials with Functions a coefficients and argument.
Method signatures and docstrings:
- def __init__(self, coefficients, x=None, null=None): *coefficients* gives the coefficients of the polynomial. *x* gives the argument of the... | 7941a06d43bbbb63e45496044040a163ab97d78d | <|skeleton|>
class Polynomial:
"""Implements polynomials with Functions a coefficients and argument."""
def __init__(self, coefficients, x=None, null=None):
"""*coefficients* gives the coefficients of the polynomial. *x* gives the argument of the polynomial. *null* is the null with respect to +, and ``... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Polynomial:
"""Implements polynomials with Functions a coefficients and argument."""
def __init__(self, coefficients, x=None, null=None):
"""*coefficients* gives the coefficients of the polynomial. *x* gives the argument of the polynomial. *null* is the null with respect to +, and ``None`` means ... | the_stack_v2_python_sparse | moviemaker3/math/polynomial.py | friedrichromstedt/moviemaker3 | train | 2 |
56757bc99b4d91e9b098cf867d5dd18355fa8ad3 | [
"atq = pd.read_csv('/Users/Clair/PycharmProjects/HKP_ML_DL/Hyperopt_LightGBM/niq_main.csv', usecols=['gvkey', 'datacqtr', 'atq'])\natq['datacqtr'] = pd.to_datetime(atq['datacqtr'])\ndf = df.filter(['gvkey', 'fpedats', 'medest', 'meanest', 'actual'])\ndf.columns = ['gvkey', 'datacqtr', 'medest', 'meanest', 'actual']... | <|body_start_0|>
atq = pd.read_csv('/Users/Clair/PycharmProjects/HKP_ML_DL/Hyperopt_LightGBM/niq_main.csv', usecols=['gvkey', 'datacqtr', 'atq'])
atq['datacqtr'] = pd.to_datetime(atq['datacqtr'])
df = df.filter(['gvkey', 'fpedats', 'medest', 'meanest', 'actual'])
df.columns = ['gvkey', '... | convert | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class convert:
def __init__(self, df):
"""input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'"""
<|body_0|>
def drop_nonseq(self, df):
"""fill in NaN for no recording period"""
<|body_1|>
def qoq(self):
"""for QTR estimation... | stack_v2_sparse_classes_75kplus_train_000845 | 16,407 | no_license | [
{
"docstring": "input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'",
"name": "__init__",
"signature": "def __init__(self, df)"
},
{
"docstring": "fill in NaN for no recording period",
"name": "drop_nonseq",
"signature": "def drop_nonseq(self, df)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_028523 | Implement the Python class `convert` described below.
Class description:
Implement the convert class.
Method signatures and docstrings:
- def __init__(self, df): input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'
- def drop_nonseq(self, df): fill in NaN for no recording period
- def qoq(s... | Implement the Python class `convert` described below.
Class description:
Implement the convert class.
Method signatures and docstrings:
- def __init__(self, df): input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'
- def drop_nonseq(self, df): fill in NaN for no recording period
- def qoq(s... | 2f124f3b90371e373fe47955e5d178d3d91067ce | <|skeleton|>
class convert:
def __init__(self, df):
"""input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'"""
<|body_0|>
def drop_nonseq(self, df):
"""fill in NaN for no recording period"""
<|body_1|>
def qoq(self):
"""for QTR estimation... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class convert:
def __init__(self, df):
"""input last observation estimation -> rename columns -> drop_nonseq -> add 'atq'"""
atq = pd.read_csv('/Users/Clair/PycharmProjects/HKP_ML_DL/Hyperopt_LightGBM/niq_main.csv', usecols=['gvkey', 'datacqtr', 'atq'])
atq['datacqtr'] = pd.to_datetime(atq['... | the_stack_v2_python_sparse | Preprocessing/Consensus_ibes.py | stepchoi/HKP_ML_DL | train | 0 | |
754503282e85f93da799d11aaa717818f1a7e263 | [
"super(Triplet_unit, self).__init__()\nself.relu = nn.ReLU()\nself.conv = depthwise_separable_conv_general(inplanes, outplanes, stride, kernel_size=kernel_size)\nself.bn = nn.BatchNorm2d(outplanes)\nself.dropout_p = dropout_p\nif dropout_p > 0:\n self.dropout = nn.Dropout(dropout_p)",
"out = self.relu(x)\nout ... | <|body_start_0|>
super(Triplet_unit, self).__init__()
self.relu = nn.ReLU()
self.conv = depthwise_separable_conv_general(inplanes, outplanes, stride, kernel_size=kernel_size)
self.bn = nn.BatchNorm2d(outplanes)
self.dropout_p = dropout_p
if dropout_p > 0:
self... | Node operation unit in the bottom-level graph. | Triplet_unit | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Triplet_unit:
"""Node operation unit in the bottom-level graph."""
def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3):
"""Initialize Triplet_unit."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_000846 | 2,586 | permissive | [
{
"docstring": "Initialize Triplet_unit.",
"name": "__init__",
"signature": "def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3)"
},
{
"docstring": "Implement forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020538 | Implement the Python class `Triplet_unit` described below.
Class description:
Node operation unit in the bottom-level graph.
Method signatures and docstrings:
- def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3): Initialize Triplet_unit.
- def forward(self, x): Implement forward. | Implement the Python class `Triplet_unit` described below.
Class description:
Node operation unit in the bottom-level graph.
Method signatures and docstrings:
- def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3): Initialize Triplet_unit.
- def forward(self, x): Implement forward.
<|skeleto... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class Triplet_unit:
"""Node operation unit in the bottom-level graph."""
def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3):
"""Initialize Triplet_unit."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Triplet_unit:
"""Node operation unit in the bottom-level graph."""
def __init__(self, inplanes, outplanes, dropout_p=0, stride=1, kernel_size=3):
"""Initialize Triplet_unit."""
super(Triplet_unit, self).__init__()
self.relu = nn.ReLU()
self.conv = depthwise_separable_conv_... | the_stack_v2_python_sparse | vega/networks/pytorch/customs/utils/ops.py | huawei-noah/vega | train | 850 |
171b2ab34532a7287083a7e811a0c5fd4ec05290 | [
"end_date = super(DayEventsListView, self).get_end_date()\nif not end_date:\n start_date = self.get_start_date()\n end_date = start_date + timedelta(days=1) - timedelta(seconds=1)\n self.end_date = end_date\nreturn end_date",
"context = super(DayEventsListView, self).get_context_data(**kwargs)\nstart_dat... | <|body_start_0|>
end_date = super(DayEventsListView, self).get_end_date()
if not end_date:
start_date = self.get_start_date()
end_date = start_date + timedelta(days=1) - timedelta(seconds=1)
self.end_date = end_date
return end_date
<|end_body_0|>
<|body_start... | Events listing for a day. | DayEventsListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DayEventsListView:
"""Events listing for a day."""
def get_end_date(self):
"""Returns the end date that is one day past today."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Overrides the list title if the events are from today."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_000847 | 38,061 | no_license | [
{
"docstring": "Returns the end date that is one day past today.",
"name": "get_end_date",
"signature": "def get_end_date(self)"
},
{
"docstring": "Overrides the list title if the events are from today.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}... | 2 | null | Implement the Python class `DayEventsListView` described below.
Class description:
Events listing for a day.
Method signatures and docstrings:
- def get_end_date(self): Returns the end date that is one day past today.
- def get_context_data(self, **kwargs): Overrides the list title if the events are from today. | Implement the Python class `DayEventsListView` described below.
Class description:
Events listing for a day.
Method signatures and docstrings:
- def get_end_date(self): Returns the end date that is one day past today.
- def get_context_data(self, **kwargs): Overrides the list title if the events are from today.
<|sk... | 736565a0a9869311c938959d3efc1d10fe493b16 | <|skeleton|>
class DayEventsListView:
"""Events listing for a day."""
def get_end_date(self):
"""Returns the end date that is one day past today."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Overrides the list title if the events are from today."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DayEventsListView:
"""Events listing for a day."""
def get_end_date(self):
"""Returns the end date that is one day past today."""
end_date = super(DayEventsListView, self).get_end_date()
if not end_date:
start_date = self.get_start_date()
end_date = start_d... | the_stack_v2_python_sparse | events/views/event_views.py | UCF/unify-events | train | 3 |
39ec88baf51bc5ec82ba83cad60b2db1f7713aa6 | [
"SED.__init__(self, webapp=webapp, config=config, **kwargs)\nspectra_file = os.path.join(default_refdata_directory, 'sed', self.spectra['config'])\nself.spectra = read_json(spectra_file)\nself.wave, self.flux = self.get_spectrum()\nself.wmin = self.wave.min()\nself.wmax = self.wave.max()",
"if self.webapp:\n i... | <|body_start_0|>
SED.__init__(self, webapp=webapp, config=config, **kwargs)
spectra_file = os.path.join(default_refdata_directory, 'sed', self.spectra['config'])
self.spectra = read_json(spectra_file)
self.wave, self.flux = self.get_spectrum()
self.wmin = self.wave.min()
... | Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data. | Parameterized | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameterized:
"""Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data."""
def __init__(self, webapp=False, co... | stack_v2_sparse_classes_75kplus_train_000848 | 19,414 | no_license | [
{
"docstring": "How an SED is configured depends on the defaults and any input configuration. Parameters ---------- webapp: bool Determines whether strict API checks should be performed config: dict Extra configuration information in engine input API dict format **kwargs: keyword/value pairs Extra configuration... | 2 | null | Implement the Python class `Parameterized` described below.
Class description:
Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data.
Met... | Implement the Python class `Parameterized` described below.
Class description:
Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data.
Met... | e1ab201afc74c3a19ddcdd8f9157dd254481ff28 | <|skeleton|>
class Parameterized:
"""Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data."""
def __init__(self, webapp=False, co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parameterized:
"""Class implementing SED's that are calculated from a model using a set of input parameters. The parameters can either come from a specfied set contained within a configured catalog (usual for webapp mode) or as input configuration data."""
def __init__(self, webapp=False, config={}, **kw... | the_stack_v2_python_sparse | pandeia/engine/sed.py | migueldvb/pandeia | train | 0 |
49cfbcc2474c9a96800be2b2946d1e9d55cad26a | [
"x = numpy.arange(self.nelx + 1)\nbotx_to_id = numpy.vectorize(lambda x: xy_to_id(x, self.nely, self.nelx, self.nely))\nids = 2 * botx_to_id(x)\nfixed = numpy.union1d(ids, ids + 1)\nreturn fixed",
"ndof = 2 * (self.nelx + 1) * (self.nely + 1)\nx = numpy.arange(0, self.nelx + 1, 10)\ntopx_to_id = numpy.vectorize(l... | <|body_start_0|>
x = numpy.arange(self.nelx + 1)
botx_to_id = numpy.vectorize(lambda x: xy_to_id(x, self.nely, self.nelx, self.nely))
ids = 2 * botx_to_id(x)
fixed = numpy.union1d(ids, ids + 1)
return fixed
<|end_body_0|>
<|body_start_1|>
ndof = 2 * (self.nelx + 1) * (se... | Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary. | HoleBoundaryConditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HoleBoundaryConditions:
"""Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary."""
def fixed_nodes(self):
"""Return a list of fixed nodes for the problem."""
<|body_0|>
def forces(self):
"""Return the forc... | stack_v2_sparse_classes_75kplus_train_000849 | 5,017 | no_license | [
{
"docstring": "Return a list of fixed nodes for the problem.",
"name": "fixed_nodes",
"signature": "def fixed_nodes(self)"
},
{
"docstring": "Return the force vector for the problem.",
"name": "forces",
"signature": "def forces(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012330 | Implement the Python class `HoleBoundaryConditions` described below.
Class description:
Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary.
Method signatures and docstrings:
- def fixed_nodes(self): Return a list of fixed nodes for the problem.
- def forces(s... | Implement the Python class `HoleBoundaryConditions` described below.
Class description:
Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary.
Method signatures and docstrings:
- def fixed_nodes(self): Return a list of fixed nodes for the problem.
- def forces(s... | 067bf9b768e020b3de15fc1dee06c2ca36875619 | <|skeleton|>
class HoleBoundaryConditions:
"""Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary."""
def fixed_nodes(self):
"""Return a list of fixed nodes for the problem."""
<|body_0|>
def forces(self):
"""Return the forc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HoleBoundaryConditions:
"""Boundary conditions for the hole tool. The bottom boundary is fixed and loads are applied to the top boundary."""
def fixed_nodes(self):
"""Return a list of fixed nodes for the problem."""
x = numpy.arange(self.nelx + 1)
botx_to_id = numpy.vectorize(lamb... | the_stack_v2_python_sparse | tools/hole_tool.py | carloshernangarrido/topopt1 | train | 0 |
036f876c635b42a7abcec5ca77c2380bcbf72877 | [
"length = len(nums)\nfor i in range(1, length):\n for j in range(0, i):\n if nums[i] == nums[j]:\n return nums[i]",
"length = len(nums)\nnums_count = [0] * (length - 1)\nfor i in range(length):\n if nums_count[nums[i] - 1] == 1:\n return nums[i]\n else:\n nums_count[nums[i... | <|body_start_0|>
length = len(nums)
for i in range(1, length):
for j in range(0, i):
if nums[i] == nums[j]:
return nums[i]
<|end_body_0|>
<|body_start_1|>
length = len(nums)
nums_count = [0] * (length - 1)
for i in range(length):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_000850 | 750 | no_license | [
{
"docstring": "Time Limit Exceeded :type nums: List[int] :rtype: int",
"name": "findDuplicate1",
"signature": "def findDuplicate1(self, nums)"
},
{
"docstring": "Time Limit Exceeded :type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"... | 2 | stack_v2_sparse_classes_30k_train_052844 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate1(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
- def findDuplicate(self, nums): Time Limit Exceeded :type nums: List[int] :rtype: int
<|sk... | 8cde0af5a9de3f01e71093e5cdbe58908db16c69 | <|skeleton|>
class Solution:
def findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate(self, nums):
"""Time Limit Exceeded :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 findDuplicate1(self, nums):
"""Time Limit Exceeded :type nums: List[int] :rtype: int"""
length = len(nums)
for i in range(1, length):
for j in range(0, i):
if nums[i] == nums[j]:
return nums[i]
def findDuplicate(self, n... | the_stack_v2_python_sparse | test_287.py | huangbenyu/leetcode | train | 0 | |
2e6cb3cb1dc77b921076bbe9fd13881d26cb0677 | [
"self.filename = filename\nself.fps = fps\nself.frame_fill = frame_fill\nself.fourcc = cv2.VideoWriter_fourcc('I', 'Y', 'U', 'V')",
"self.writer = cv2.VideoWriter(self.filename, self.fourcc, self.fps, size, 1)\nself.video_time = 0.0\nself.start_time = time.time()",
"if not self.writer:\n self.init_writer(img... | <|body_start_0|>
self.filename = filename
self.fps = fps
self.frame_fill = frame_fill
self.fourcc = cv2.VideoWriter_fourcc('I', 'Y', 'U', 'V')
<|end_body_0|>
<|body_start_1|>
self.writer = cv2.VideoWriter(self.filename, self.fourcc, self.fps, size, 1)
self.video_time = 0... | Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want to do this:: # note these are default v... | VideoStream | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want ... | stack_v2_sparse_classes_75kplus_train_000851 | 9,045 | permissive | [
{
"docstring": "TODO: details :param filename: :param fps: :param frame_fill:",
"name": "__init__",
"signature": "def __init__(self, filename, fps=25, frame_fill=True)"
},
{
"docstring": "TODO: details :param size: :return:",
"name": "init_writer",
"signature": "def init_writer(self, siz... | 3 | stack_v2_sparse_classes_30k_train_031637 | Implement the Python class `VideoStream` described below.
Class description:
Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to... | Implement the Python class `VideoStream` described below.
Class description:
Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to... | f312569ec983b5f27c75846b34debc04fe7bdf98 | <|skeleton|>
class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoStream:
"""Allows user save video files in different formats. You can initialize it by specifying the file you want to output:: vs = VideoStream("hello.avi") You can also specify a framerate, and if you want to "fill" in missed frames. So if you want to record a real time video you may want to do this:: ... | the_stack_v2_python_sparse | PhloxAR/core/stream.py | PhloxAR/PhloxAR | train | 1 |
3333992e505313ed9fc9aae097bde974a125dbc2 | [
"HodgkinHuxley.__init__(self, vna, vk, vl, gna, gk, gl, C)\nself.dt = time_step\nself.sigma = sigma\nself.sigma_external = sigma_external",
"alpha = 0.1 * ((25.0 - v) / (np.exp((25.0 - v) / 10.0) - 1))\nbeta = 4.0 * np.exp(-v / 18.0)\ndw = np.random.normal(0, np.sqrt(self.dt), size=x.size)\nzeros = np.zeros(x.siz... | <|body_start_0|>
HodgkinHuxley.__init__(self, vna, vk, vl, gna, gk, gl, C)
self.dt = time_step
self.sigma = sigma
self.sigma_external = sigma_external
<|end_body_0|>
<|body_start_1|>
alpha = 0.1 * ((25.0 - v) / (np.exp((25.0 - v) / 10.0) - 1))
beta = 4.0 * np.exp(-v / 18... | The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck equation (stochastic differential equations). | SDE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDE:
"""The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck equation (stochastic differential equatio... | stack_v2_sparse_classes_75kplus_train_000852 | 17,828 | permissive | [
{
"docstring": "The constructor method. Args: Hodgkin-Huxley Parameters: vna, vk, vl, gna, gk, gl and C. timeStep: time step for the Euler-Maruyama Method sigma_external: the stochastic voltage term strengh sigma: the stochastic term strengh",
"name": "__init__",
"signature": "def __init__(self, time_st... | 6 | null | Implement the Python class `SDE` described below.
Class description:
The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck eq... | Implement the Python class `SDE` described below.
Class description:
The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck eq... | 01d5acfddaedb3cbf7fa9247a88108530547e155 | <|skeleton|>
class SDE:
"""The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck equation (stochastic differential equatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SDE:
"""The Stochastic Differential Equations of the Hodgkin-Huxley Model Class. This class takes the Hodgkin-Huxley dynamical system equations (V, M, N and H) also the chemical neurotransmitters proportion (Y) and transform them into a Ornstein-Uhlenbeck equation (stochastic differential equations)."""
... | the_stack_v2_python_sparse | nsc/neurons/hodgkinhuxley.py | GuilhermeToso/masters-project | train | 1 |
3c131adc8bb9b2f648808ee0bf0d15d2235ac28a | [
"self.extrapolated = [list(zip(self.coordinates[0], self.coordinates[1])), list(zip(self.coordinates[-2], self.coordinates[-1]))]\nself.coordinates.insert(0, [2 * a - b for a, b in zip(self.coordinates[0], self.coordinates[1])])\nself.coordinates.append([2 * a - b for a, b in zip(self.coordinates[-1], self.coordina... | <|body_start_0|>
self.extrapolated = [list(zip(self.coordinates[0], self.coordinates[1])), list(zip(self.coordinates[-2], self.coordinates[-1]))]
self.coordinates.insert(0, [2 * a - b for a, b in zip(self.coordinates[0], self.coordinates[1])])
self.coordinates.append([2 * a - b for a, b in zip(s... | Interpolate with B-spline. | InterpolatorBSpline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolatorBSpline:
"""Interpolate with B-spline."""
def adjust_endpoints(self) -> None:
"""Adjust endpoints such that they are clamped and can handle extrapolation."""
<|body_0|>
def setup(self) -> None:
"""Optional setup."""
<|body_1|>
def interpo... | stack_v2_sparse_classes_75kplus_train_000853 | 3,888 | permissive | [
{
"docstring": "Adjust endpoints such that they are clamped and can handle extrapolation.",
"name": "adjust_endpoints",
"signature": "def adjust_endpoints(self) -> None"
},
{
"docstring": "Optional setup.",
"name": "setup",
"signature": "def setup(self) -> None"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_test_000213 | Implement the Python class `InterpolatorBSpline` described below.
Class description:
Interpolate with B-spline.
Method signatures and docstrings:
- def adjust_endpoints(self) -> None: Adjust endpoints such that they are clamped and can handle extrapolation.
- def setup(self) -> None: Optional setup.
- def interpolate... | Implement the Python class `InterpolatorBSpline` described below.
Class description:
Interpolate with B-spline.
Method signatures and docstrings:
- def adjust_endpoints(self) -> None: Adjust endpoints such that they are clamped and can handle extrapolation.
- def setup(self) -> None: Optional setup.
- def interpolate... | ad4d779bff57a65b7c77cda0b79c10cf904eb817 | <|skeleton|>
class InterpolatorBSpline:
"""Interpolate with B-spline."""
def adjust_endpoints(self) -> None:
"""Adjust endpoints such that they are clamped and can handle extrapolation."""
<|body_0|>
def setup(self) -> None:
"""Optional setup."""
<|body_1|>
def interpo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpolatorBSpline:
"""Interpolate with B-spline."""
def adjust_endpoints(self) -> None:
"""Adjust endpoints such that they are clamped and can handle extrapolation."""
self.extrapolated = [list(zip(self.coordinates[0], self.coordinates[1])), list(zip(self.coordinates[-2], self.coordinat... | the_stack_v2_python_sparse | lib/coloraide/interpolate/bspline.py | facelessuser/ColorHelper | train | 279 |
553ca9fa99ca8b43426479473f82f6a6d5328902 | [
"controller = Controller()\nbuyers = controller.get()\nreturn buyers",
"data = api.payload\ncontroller = Controller()\ncontroller.insert(data)"
] | <|body_start_0|>
controller = Controller()
buyers = controller.get()
return buyers
<|end_body_0|>
<|body_start_1|>
data = api.payload
controller = Controller()
controller.insert(data)
<|end_body_1|>
| BuyerList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuyerList:
def get(self):
"""Return buyers list. :return:"""
<|body_0|>
def post(self):
"""Create new buyer :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
controller = Controller()
buyers = controller.get()
return buyers
<|... | stack_v2_sparse_classes_75kplus_train_000854 | 957 | no_license | [
{
"docstring": "Return buyers list. :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create new buyer :return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052472 | Implement the Python class `BuyerList` described below.
Class description:
Implement the BuyerList class.
Method signatures and docstrings:
- def get(self): Return buyers list. :return:
- def post(self): Create new buyer :return: | Implement the Python class `BuyerList` described below.
Class description:
Implement the BuyerList class.
Method signatures and docstrings:
- def get(self): Return buyers list. :return:
- def post(self): Create new buyer :return:
<|skeleton|>
class BuyerList:
def get(self):
"""Return buyers list. :retur... | 19d96756925e61e31833adf4b49714d7fbfa4868 | <|skeleton|>
class BuyerList:
def get(self):
"""Return buyers list. :return:"""
<|body_0|>
def post(self):
"""Create new buyer :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuyerList:
def get(self):
"""Return buyers list. :return:"""
controller = Controller()
buyers = controller.get()
return buyers
def post(self):
"""Create new buyer :return:"""
data = api.payload
controller = Controller()
controller.insert(dat... | the_stack_v2_python_sparse | app/buyer/view_buyer.py | ladin157/flask_rest_orm_example | train | 0 | |
481fc74bd6554dd9d789b51443e65f6149a4a46e | [
"self.start = torch.cuda.Event(enable_timing=True)\nself.end = torch.cuda.Event(enable_timing=True)\nself.start.record()\nself.sum = 0\nreturn self",
"self.end.record()\ntorch.cuda.synchronize()\nself.sum = self.start.elapsed_time(self.end) / 1000.0"
] | <|body_start_0|>
self.start = torch.cuda.Event(enable_timing=True)
self.end = torch.cuda.Event(enable_timing=True)
self.start.record()
self.sum = 0
return self
<|end_body_0|>
<|body_start_1|>
self.end.record()
torch.cuda.synchronize()
self.sum = self.star... | GPUTimer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPUTimer:
def __enter__(self):
"""Start a new timer as a context manager"""
<|body_0|>
def __exit__(self, *exc_info):
"""Stop the context manager timer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.start = torch.cuda.Event(enable_timing=True)... | stack_v2_sparse_classes_75kplus_train_000855 | 18,393 | permissive | [
{
"docstring": "Start a new timer as a context manager",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "Stop the context manager timer",
"name": "__exit__",
"signature": "def __exit__(self, *exc_info)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037162 | Implement the Python class `GPUTimer` described below.
Class description:
Implement the GPUTimer class.
Method signatures and docstrings:
- def __enter__(self): Start a new timer as a context manager
- def __exit__(self, *exc_info): Stop the context manager timer | Implement the Python class `GPUTimer` described below.
Class description:
Implement the GPUTimer class.
Method signatures and docstrings:
- def __enter__(self): Start a new timer as a context manager
- def __exit__(self, *exc_info): Stop the context manager timer
<|skeleton|>
class GPUTimer:
def __enter__(self)... | 3075d63177e8ac04ee91784d5b0c56379335740f | <|skeleton|>
class GPUTimer:
def __enter__(self):
"""Start a new timer as a context manager"""
<|body_0|>
def __exit__(self, *exc_info):
"""Stop the context manager timer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPUTimer:
def __enter__(self):
"""Start a new timer as a context manager"""
self.start = torch.cuda.Event(enable_timing=True)
self.end = torch.cuda.Event(enable_timing=True)
self.start.record()
self.sum = 0
return self
def __exit__(self, *exc_info):
... | the_stack_v2_python_sparse | fairnr/data/data_utils.py | wi1k1n/nrf-accelerations | train | 1 | |
b8af3765dae98f045558f84bbd21d997241bd44e | [
"shortcut = data\nbn1 = BatchNormalization(axis=chanDim, momentum=bnMom, epsilon=bnEps)(data)\nact1 = Activation('relu')(bn1)\nconv1 = Conv2D(filters=int(K * 0.25), kernel_size=(1, 1), use_bias=False, kernel_regularizer=l2(reg))(act1)\nbn2 = BatchNormalization(axis=chanDim, momentum=bnMom, epsilon=bnEps)(bn1)\nact2... | <|body_start_0|>
shortcut = data
bn1 = BatchNormalization(axis=chanDim, momentum=bnMom, epsilon=bnEps)(data)
act1 = Activation('relu')(bn1)
conv1 = Conv2D(filters=int(K * 0.25), kernel_size=(1, 1), use_bias=False, kernel_regularizer=l2(reg))(act1)
bn2 = BatchNormalization(axis=ch... | ResNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-networks :param data: input to residual model (prev layer) :param K: Filters in the convultions 1x... | stack_v2_sparse_classes_75kplus_train_000856 | 5,494 | no_license | [
{
"docstring": "see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-networks :param data: input to residual model (prev layer) :param K: Filters in the convultions 1x1x(K/4) -> 3x3x(K/4) -> 1x1xK :param stride: stride in convolutions :param chanDim: Channel Dimension (first or l... | 2 | stack_v2_sparse_classes_30k_train_027800 | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9): see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-net... | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9): see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-net... | 46cda997697c80e6e9d1ca51218d5e8d1620eb29 | <|skeleton|>
class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-networks :param data: input to residual model (prev layer) :param K: Filters in the convultions 1x... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet:
def residual_module(data, K, stride, chanDim, red=False, reg=0.0001, bnEps=2e-05, bnMom=0.9):
"""see DL4CV [46] Kaiming He. Deep Residual Networks github.com/KaimingHe/deep-residual-networks :param data: input to residual model (prev layer) :param K: Filters in the convultions 1x1x(K/4) -> 3x3... | the_stack_v2_python_sparse | BlogTutorials/pyimagesearch/nn/conv/resnet.py | mplefort/Python_Learning | train | 0 | |
b700e9313650e95a3d629ebc97eba716267c1878 | [
"l = []\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n l.append([i, j])\nreturn l",
"d = {}\nfor i, num in enumerate(nums):\n if target - num in d:\n return [d[target - num], i]\n d[num] = i"
] | <|body_start_0|>
l = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
l.append([i, j])
return l
<|end_body_0|>
<|body_start_1|>
d = {}
for i, num in enumerate(nums):
if tar... | 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]"""
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_000857 | 1,373 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum1",
"signature": "def twoSum1(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_test_001591 | Implement the Python class `Solution` described below.
Class description:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type targ... | Implement the Python class `Solution` described below.
Class description:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type targ... | 40bca64cf3ed2fbc670b9e2cdf4f88d6c7b68134 | <|skeleton|>
class Solution:
"""给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]"""
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]"""
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
l = []
for i in range(len... | the_stack_v2_python_sparse | Array/nine.py | okliou/lcode | train | 0 |
a1fe1caa826c744feb3141079b9f4d5050531ecb | [
"if not param:\n param = Credit.credit_param()\nresult = 0.0\nresult_details = {}\nfor factor, p in param.iteritems():\n user_data = profile.get_credit_data(factor)\n if not user_data:\n c_data = p.default_value\n else:\n c_data = p.get_data_level(user_data)\n result += c_data * p.weigh... | <|body_start_0|>
if not param:
param = Credit.credit_param()
result = 0.0
result_details = {}
for factor, p in param.iteritems():
user_data = profile.get_credit_data(factor)
if not user_data:
c_data = p.default_value
else:
... | Credit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
<|body_0|>
def credit_param(source='weibo'):
"""取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not param:
param = Credit.credit_para... | stack_v2_sparse_classes_75kplus_train_000858 | 2,678 | no_license | [
{
"docstring": "计算用户的信用评分",
"name": "get_profile_credit",
"signature": "def get_profile_credit(profile, param=None)"
},
{
"docstring": "取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]",
"name": "credit_param",
"signature": "def credit_param(source='weibo')"
}
] | 2 | stack_v2_sparse_classes_30k_train_002417 | Implement the Python class `Credit` described below.
Class description:
Implement the Credit class.
Method signatures and docstrings:
- def get_profile_credit(profile, param=None): 计算用户的信用评分
- def credit_param(source='weibo'): 取得信用评分参数 参数名:[1,2,3,4,5,6,7,10] | Implement the Python class `Credit` described below.
Class description:
Implement the Credit class.
Method signatures and docstrings:
- def get_profile_credit(profile, param=None): 计算用户的信用评分
- def credit_param(source='weibo'): 取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]
<|skeleton|>
class Credit:
def get_profile_credit(pro... | 96ed049eb398c4c188a688e9c1bc2fe8cd2dc80b | <|skeleton|>
class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
<|body_0|>
def credit_param(source='weibo'):
"""取得信用评分参数 参数名:[1,2,3,4,5,6,7,10]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Credit:
def get_profile_credit(profile, param=None):
"""计算用户的信用评分"""
if not param:
param = Credit.credit_param()
result = 0.0
result_details = {}
for factor, p in param.iteritems():
user_data = profile.get_credit_data(factor)
if not u... | the_stack_v2_python_sparse | other_projects/python/WeiboAds/src/Weibo/credit/credit_service.py | github188/demodemo | train | 1 | |
1e78fb593976798c604b74277e5196ac48a4878b | [
"url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'\nres = self.get(url_user_get, {'next_openid': None})\nreturn res['data']['openid']",
"url_user_info = 'https://api.weixin.qq.com/cgi-bin/user/info'\nparams = {'openid': openid, 'lang': 'zh_CN'}\nreturn self.get(url_user_info, params)",
"url_user_batch... | <|body_start_0|>
url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'
res = self.get(url_user_get, {'next_openid': None})
return res['data']['openid']
<|end_body_0|>
<|body_start_1|>
url_user_info = 'https://api.weixin.qq.com/cgi-bin/user/info'
params = {'openid': openid,... | 微信用户管理 | WxUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
<|body_0|>
def user_info(self, openid: str):
"""获取用户信息"""
<|body_1|>
def user_batch(self, users: list):
"""批量获取用户信息,最多支持一次拉取100条。 :param users: open... | stack_v2_sparse_classes_75kplus_train_000859 | 3,667 | no_license | [
{
"docstring": "获取用户列表,一次最多返回10000条 :return: openid 列表",
"name": "user_list",
"signature": "def user_list(self)"
},
{
"docstring": "获取用户信息",
"name": "user_info",
"signature": "def user_info(self, openid: str)"
},
{
"docstring": "批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :ret... | 4 | stack_v2_sparse_classes_30k_train_046405 | Implement the Python class `WxUserManager` described below.
Class description:
微信用户管理
Method signatures and docstrings:
- def user_list(self): 获取用户列表,一次最多返回10000条 :return: openid 列表
- def user_info(self, openid: str): 获取用户信息
- def user_batch(self, users: list): 批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :return:
... | Implement the Python class `WxUserManager` described below.
Class description:
微信用户管理
Method signatures and docstrings:
- def user_list(self): 获取用户列表,一次最多返回10000条 :return: openid 列表
- def user_info(self, openid: str): 获取用户信息
- def user_batch(self, users: list): 批量获取用户信息,最多支持一次拉取100条。 :param users: openid 列表 :return:
... | 7316880e2444a8af02e2f44af38dd7ae708ccbb6 | <|skeleton|>
class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
<|body_0|>
def user_info(self, openid: str):
"""获取用户信息"""
<|body_1|>
def user_batch(self, users: list):
"""批量获取用户信息,最多支持一次拉取100条。 :param users: open... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WxUserManager:
"""微信用户管理"""
def user_list(self):
"""获取用户列表,一次最多返回10000条 :return: openid 列表"""
url_user_get = 'https://api.weixin.qq.com/cgi-bin/user/get'
res = self.get(url_user_get, {'next_openid': None})
return res['data']['openid']
def user_info(self, openid: str):... | the_stack_v2_python_sparse | web_flask/weixin/user.py | aiportal/zb123 | train | 0 |
535b5d7cf024d5adb881ec2baac166e2fef981ba | [
"cleaned_data = super(CampaignForm, self).clean()\nif cleaned_data.get('is_electoral') and cleaned_data.get('election_date') is None:\n self.add_error('election_date', forms.ValidationError('Required for electoral campaigns.'))\nreturn cleaned_data",
"the_date = self.cleaned_data['election_date']\nif the_date ... | <|body_start_0|>
cleaned_data = super(CampaignForm, self).clean()
if cleaned_data.get('is_electoral') and cleaned_data.get('election_date') is None:
self.add_error('election_date', forms.ValidationError('Required for electoral campaigns.'))
return cleaned_data
<|end_body_0|>
<|body_... | Use this form to create and edit Campaign instances. | CampaignForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignForm:
"""Use this form to create and edit Campaign instances."""
def clean(self):
"""If is_electoral is true, the 'election_date' field is required."""
<|body_0|>
def clean_election_date(self):
"""A valid date cannot be in the past."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_000860 | 2,146 | no_license | [
{
"docstring": "If is_electoral is true, the 'election_date' field is required.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "A valid date cannot be in the past.",
"name": "clean_election_date",
"signature": "def clean_election_date(self)"
}
] | 2 | null | Implement the Python class `CampaignForm` described below.
Class description:
Use this form to create and edit Campaign instances.
Method signatures and docstrings:
- def clean(self): If is_electoral is true, the 'election_date' field is required.
- def clean_election_date(self): A valid date cannot be in the past. | Implement the Python class `CampaignForm` described below.
Class description:
Use this form to create and edit Campaign instances.
Method signatures and docstrings:
- def clean(self): If is_electoral is true, the 'election_date' field is required.
- def clean_election_date(self): A valid date cannot be in the past.
... | 18583f88f396b600e73f24dc16d2c24a89c8f924 | <|skeleton|>
class CampaignForm:
"""Use this form to create and edit Campaign instances."""
def clean(self):
"""If is_electoral is true, the 'election_date' field is required."""
<|body_0|>
def clean_election_date(self):
"""A valid date cannot be in the past."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CampaignForm:
"""Use this form to create and edit Campaign instances."""
def clean(self):
"""If is_electoral is true, the 'election_date' field is required."""
cleaned_data = super(CampaignForm, self).clean()
if cleaned_data.get('is_electoral') and cleaned_data.get('election_date'... | the_stack_v2_python_sparse | campaign/forms.py | kalbfled/Turnkey-Campaign-Solutions | train | 4 |
5cc9d4fce0ac1d601bd9ee6c6c92ec016ba228ff | [
"super().__init__(*args, **kwargs)\nself.dias_colegio = par.DIAS_COLEGIO\nself.probabilidad = par.PROBABILIDAD_DIA_COLEGIO",
"if self.dia in self.dias_colegio:\n if uniform(0, 1) < self.probabilidad:\n self._funcion()\n self.escribir_log()"
] | <|body_start_0|>
super().__init__(*args, **kwargs)
self.dias_colegio = par.DIAS_COLEGIO
self.probabilidad = par.PROBABILIDAD_DIA_COLEGIO
<|end_body_0|>
<|body_start_1|>
if self.dia in self.dias_colegio:
if uniform(0, 1) < self.probabilidad:
self._funcion()
... | DiaColegio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
<|body_0|>
def funcion(self):
"""si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None"""
... | stack_v2_sparse_classes_75kplus_train_000861 | 4,009 | no_license | [
{
"docstring": "dias_colegio: set(str) probabilidad: float",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None",
"name"... | 2 | stack_v2_sparse_classes_30k_train_048788 | Implement the Python class `DiaColegio` described below.
Class description:
Implement the DiaColegio class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): dias_colegio: set(str) probabilidad: float
- def funcion(self): si es que el dia está entre los habilitados para dia colegio, existe cier... | Implement the Python class `DiaColegio` described below.
Class description:
Implement the DiaColegio class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): dias_colegio: set(str) probabilidad: float
- def funcion(self): si es que el dia está entre los habilitados para dia colegio, existe cier... | 884be9365cd20a87aa0a75018a724e6ca0bc0182 | <|skeleton|>
class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
<|body_0|>
def funcion(self):
"""si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
super().__init__(*args, **kwargs)
self.dias_colegio = par.DIAS_COLEGIO
self.probabilidad = par.PROBABILIDAD_DIA_COLEGIO
def funcion(self):
"""si es que el dia está ent... | the_stack_v2_python_sparse | Tareas/T04/eventos.py | JoseAvanzada2019/IIC2233-2018-1-SantiRepo | train | 0 | |
47aa1f57f73a71b6781f4bd2c5ae01c28511d41f | [
"u, p = secrets.db.epi\nself._connection = connector_impl.connect(host=secrets.db.host, user=u, password=p, database=Database.DATABASE_NAME)\nself._cursor = self._connection.cursor()",
"self._cursor.close()\nif commit:\n self._connection.commit()\nself._connection.close()",
"sql = \"\\n SELECT\\n ... | <|body_start_0|>
u, p = secrets.db.epi
self._connection = connector_impl.connect(host=secrets.db.host, user=u, password=p, database=Database.DATABASE_NAME)
self._cursor = self._connection.cursor()
<|end_body_0|>
<|body_start_1|>
self._cursor.close()
if commit:
self._... | A collection of epicast database operations. | Database | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
"""A collection of epicast database operations."""
def connect(self, connector_impl=mysql.connector):
"""Establish a connection to the database."""
<|body_0|>
def disconnect(self, commit):
"""Close the database connection. commit: if true, commit change... | stack_v2_sparse_classes_75kplus_train_000862 | 2,444 | permissive | [
{
"docstring": "Establish a connection to the database.",
"name": "connect",
"signature": "def connect(self, connector_impl=mysql.connector)"
},
{
"docstring": "Close the database connection. commit: if true, commit changes, otherwise rollback",
"name": "disconnect",
"signature": "def di... | 3 | stack_v2_sparse_classes_30k_train_032909 | Implement the Python class `Database` described below.
Class description:
A collection of epicast database operations.
Method signatures and docstrings:
- def connect(self, connector_impl=mysql.connector): Establish a connection to the database.
- def disconnect(self, commit): Close the database connection. commit: i... | Implement the Python class `Database` described below.
Class description:
A collection of epicast database operations.
Method signatures and docstrings:
- def connect(self, connector_impl=mysql.connector): Establish a connection to the database.
- def disconnect(self, commit): Close the database connection. commit: i... | 23e1b41313f8863a7732b5861df7c70edd1ee3ad | <|skeleton|>
class Database:
"""A collection of epicast database operations."""
def connect(self, connector_impl=mysql.connector):
"""Establish a connection to the database."""
<|body_0|>
def disconnect(self, commit):
"""Close the database connection. commit: if true, commit change... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Database:
"""A collection of epicast database operations."""
def connect(self, connector_impl=mysql.connector):
"""Establish a connection to the database."""
u, p = secrets.db.epi
self._connection = connector_impl.connect(host=secrets.db.host, user=u, password=p, database=Database... | the_stack_v2_python_sparse | src/covid/database.py | cmu-delphi/flu-contest | train | 0 |
2b2e62f81970284b611809ee2570751143672a93 | [
"event_regex = {}\nregex_filepath = os.path.dirname(os.path.abspath(__file__)) + '/' + self.REGEX_FILE\nself.event_regex = self._load_regex_yaml(regex_filepath)\nEventParser.__init__(self, event_regex.keys(), self.EVENT_NAME)",
"dataframe[raw_column] = dataframe[raw_column].str.replace('\\\\\\\\', '')\nparsed_dat... | <|body_start_0|>
event_regex = {}
regex_filepath = os.path.dirname(os.path.abspath(__file__)) + '/' + self.REGEX_FILE
self.event_regex = self._load_regex_yaml(regex_filepath)
EventParser.__init__(self, event_regex.keys(), self.EVENT_NAME)
<|end_body_0|>
<|body_start_1|>
datafram... | This is class parses splunk notable logs. | SplunkNotableParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplunkNotableParser:
"""This is class parses splunk notable logs."""
def __init__(self):
"""Constructor method"""
<|body_0|>
def parse(self, dataframe, raw_column):
"""Parses the Splunk notable raw events. :param dataframe: Raw events to be parsed. :type datafram... | stack_v2_sparse_classes_75kplus_train_000863 | 3,763 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parses the Splunk notable raw events. :param dataframe: Raw events to be parsed. :type dataframe: cudf.DataFrame :param raw_column: Raw data contained column name. :type raw_column: stri... | 3 | null | Implement the Python class `SplunkNotableParser` described below.
Class description:
This is class parses splunk notable logs.
Method signatures and docstrings:
- def __init__(self): Constructor method
- def parse(self, dataframe, raw_column): Parses the Splunk notable raw events. :param dataframe: Raw events to be p... | Implement the Python class `SplunkNotableParser` described below.
Class description:
This is class parses splunk notable logs.
Method signatures and docstrings:
- def __init__(self): Constructor method
- def parse(self, dataframe, raw_column): Parses the Splunk notable raw events. :param dataframe: Raw events to be p... | 68c14f460b5d3ab41ade9b2450126db0d2536745 | <|skeleton|>
class SplunkNotableParser:
"""This is class parses splunk notable logs."""
def __init__(self):
"""Constructor method"""
<|body_0|>
def parse(self, dataframe, raw_column):
"""Parses the Splunk notable raw events. :param dataframe: Raw events to be parsed. :type datafram... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SplunkNotableParser:
"""This is class parses splunk notable logs."""
def __init__(self):
"""Constructor method"""
event_regex = {}
regex_filepath = os.path.dirname(os.path.abspath(__file__)) + '/' + self.REGEX_FILE
self.event_regex = self._load_regex_yaml(regex_filepath)
... | the_stack_v2_python_sparse | python/clx/parsers/splunk_notable_parser.py | rapidsai/clx | train | 169 |
2d7103196ee8c68588306d88f157e114e8a8c39e | [
"self.ctx = context\nself.config = config\nself.logger = logger\nself.package_path = Path(package_path) if isinstance(package_path, str) else package_path\nself.path = Path(path) if isinstance(path, str) else path",
"if self.config.get('package', {'': ''}).get('individually'):\n return {name: get_hash_of_files... | <|body_start_0|>
self.ctx = context
self.config = config
self.logger = logger
self.package_path = Path(package_path) if isinstance(package_path, str) else package_path
self.path = Path(path) if isinstance(path, str) else path
<|end_body_0|>
<|body_start_1|>
if self.confi... | Object for interacting with a Serverless artifact directory. | ServerlessArtifact | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerlessArtifact:
"""Object for interacting with a Serverless artifact directory."""
def __init__(self, context: RunwayContext, config: Dict[str, Any], *, logger: Union[PrefixAdaptor, RunwayLogger]=LOGGER, package_path: AnyPath, path: AnyPath) -> None:
"""Instantiate class. Args: c... | stack_v2_sparse_classes_75kplus_train_000864 | 19,334 | permissive | [
{
"docstring": "Instantiate class. Args: context: Runway context object. config: Rendered Serverless config file. logger: Logger this object will log to. If not provided, the logger in the local module will be used. package_path: Local path to the artifact directory. path: Root directory of the Serverless proje... | 3 | stack_v2_sparse_classes_30k_train_014252 | Implement the Python class `ServerlessArtifact` described below.
Class description:
Object for interacting with a Serverless artifact directory.
Method signatures and docstrings:
- def __init__(self, context: RunwayContext, config: Dict[str, Any], *, logger: Union[PrefixAdaptor, RunwayLogger]=LOGGER, package_path: An... | Implement the Python class `ServerlessArtifact` described below.
Class description:
Object for interacting with a Serverless artifact directory.
Method signatures and docstrings:
- def __init__(self, context: RunwayContext, config: Dict[str, Any], *, logger: Union[PrefixAdaptor, RunwayLogger]=LOGGER, package_path: An... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class ServerlessArtifact:
"""Object for interacting with a Serverless artifact directory."""
def __init__(self, context: RunwayContext, config: Dict[str, Any], *, logger: Union[PrefixAdaptor, RunwayLogger]=LOGGER, package_path: AnyPath, path: AnyPath) -> None:
"""Instantiate class. Args: c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerlessArtifact:
"""Object for interacting with a Serverless artifact directory."""
def __init__(self, context: RunwayContext, config: Dict[str, Any], *, logger: Union[PrefixAdaptor, RunwayLogger]=LOGGER, package_path: AnyPath, path: AnyPath) -> None:
"""Instantiate class. Args: context: Runwa... | the_stack_v2_python_sparse | runway/module/serverless.py | onicagroup/runway | train | 156 |
bfb4b0b420cdab0bf2790938bf1e8281a3e94938 | [
"super().__init__(fl_model, data_handler, hyperparams, **kwargs)\nself.curr_seed = 0\nself.permute_secret = 0\nif not kwargs:\n raise InvalidConfigurationException('No local_training info given at runtime')\nseed_file = get_seed_filename(kwargs)\nself.permute_secret = get_seed(seed_file)",
"allw = model_update... | <|body_start_0|>
super().__init__(fl_model, data_handler, hyperparams, **kwargs)
self.curr_seed = 0
self.permute_secret = 0
if not kwargs:
raise InvalidConfigurationException('No local_training info given at runtime')
seed_file = get_seed_filename(kwargs)
self... | ShuffleLocalTrainingHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShuffleLocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to ... | stack_v2_sparse_classes_75kplus_train_000865 | 6,140 | permissive | [
{
"docstring": "Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain data :type data_handler: `DataHandler` :param hyperparams: Hyperparameters used for training. :type hyper... | 6 | stack_v2_sparse_classes_30k_train_048851 | Implement the Python class `ShuffleLocalTrainingHandler` described below.
Class description:
Implement the ShuffleLocalTrainingHandler class.
Method signatures and docstrings:
- def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs): Initialize LocalTrainingHandler with fl_model, data_handler :param f... | Implement the Python class `ShuffleLocalTrainingHandler` described below.
Class description:
Implement the ShuffleLocalTrainingHandler class.
Method signatures and docstrings:
- def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs): Initialize LocalTrainingHandler with fl_model, data_handler :param f... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class ShuffleLocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShuffleLocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain data :t... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/party/training/shuffle_local_training_handler.py | SEED-VT/FedDebug | train | 8 | |
ee896df291119363f9783440a11e63ecfb4296c8 | [
"super().__init__()\nself.in_channels = in_channels\nself.hidden_channels = hidden_channels\nself.forget_bias = forget_bias\npadding = (kernel_size // 2, kernel_size // 2)\nkernel_size = (kernel_size, kernel_size)\nself.conv = nn.Conv2d(in_channels=in_channels, out_channels=hidden_channels * 4, kernel_size=kernel_s... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.forget_bias = forget_bias
padding = (kernel_size // 2, kernel_size // 2)
kernel_size = (kernel_size, kernel_size)
self.conv = nn.Conv2d(in_channels=in_ch... | ConvLSTM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
<|body_0|>
def forward(self, inputs: Tensor) -> T... | stack_v2_sparse_classes_75kplus_train_000866 | 3,758 | permissive | [
{
"docstring": ":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01)"
},
{
"docstring": ":param inputs: ... | 2 | stack_v2_sparse_classes_30k_train_042112 | Implement the Python class `ConvLSTM` described below.
Class description:
Implement the ConvLSTM class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01): :param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size... | Implement the Python class `ConvLSTM` described below.
Class description:
Implement the ConvLSTM class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01): :param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size... | d8079d6ceb3a41a06552bb3d88298327d0645d57 | <|skeleton|>
class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
<|body_0|>
def forward(self, inputs: Tensor) -> T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvLSTM:
def __init__(self, in_channels: int, hidden_channels: int, kernel_size: int, forget_bias: float=0.01):
""":param in_channels: 输入通道数 :param hidden_channels: 隐藏层通道数 :param kernel_size: 卷积核尺寸 :param forget_bias: 偏移量"""
super().__init__()
self.in_channels = in_channels
se... | the_stack_v2_python_sparse | study/models/CubicRNN/CubicLSTM.py | hechentao/STudy | train | 0 | |
667884fe1789f0822e5d0e5f57f7ed660fa8383a | [
"for row in matrix:\n for col in range(1, len(row)):\n row[col] += row[col - 1]\nself.matrix = matrix",
"original = self.matrix[row][col]\nif col != 0:\n original -= self.matrix[row][col - 1]\ndiff = original - val\nfor y in range(col, len(self.matrix[0])):\n self.matrix[row][y] -= diff",
"regio... | <|body_start_0|>
for row in matrix:
for col in range(1, len(row)):
row[col] += row[col - 1]
self.matrix = matrix
<|end_body_0|>
<|body_start_1|>
original = self.matrix[row][col]
if col != 0:
original -= self.matrix[row][col - 1]
diff = ori... | Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simple-sum-array-on-one-dimension-O(n)-for-both-update-and-sum beats 83.86% | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
"""Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simple-sum-array-on-one-dimension-O(n)-for-b... | stack_v2_sparse_classes_75kplus_train_000867 | 8,379 | no_license | [
{
"docstring": ":type matrix: List[List[int]] element m[i][j] in self.matrix means sum of previous elements in this row, namely sum(m[i][0] + m[i][1] + ... + m[i][j])",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "original means the single element value in ori... | 3 | stack_v2_sparse_classes_30k_test_000939 | Implement the Python class `NumMatrix` described below.
Class description:
Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simpl... | Implement the Python class `NumMatrix` described below.
Class description:
Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simpl... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class NumMatrix:
"""Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simple-sum-array-on-one-dimension-O(n)-for-b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
"""Your NumMatrix object will be instantiated and called as such: obj = NumMatrix(matrix) obj.update(row,col,val) param_2 = obj.sumRegion(row1,col1,row2,col2) https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Simple-sum-array-on-one-dimension-O(n)-for-both-update-an... | the_stack_v2_python_sparse | leetcode_python/Array/range-sum-query-2d-mutable.py | yennanliu/CS_basics | train | 64 |
0d39505d764ef2db2de46b5a1c68261771d11340 | [
"dp = [0] * len(nums)\ndp[0] = 1\nfor index in range(1, len(nums)):\n dp[index] = 1\n for i in range(index):\n if nums[index] > nums[i]:\n dp[index] = max(dp[index], dp[i] + 1)\nreturn max(dp)",
"dp = [[0, 0] for _ in range(len(nums))]\ndp[0][0] = 0\ndp[0][1] = 1\nfor index in range(1, len... | <|body_start_0|>
dp = [0] * len(nums)
dp[0] = 1
for index in range(1, len(nums)):
dp[index] = 1
for i in range(index):
if nums[index] > nums[i]:
dp[index] = max(dp[index], dp[i] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * len(nums)
dp[0] = 1
... | stack_v2_sparse_classes_75kplus_train_000868 | 974 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023030 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(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 lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOfLI... | 9d394cd2862703cfb7a7b505b35deda7450a692e | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(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 lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
dp = [0] * len(nums)
dp[0] = 1
for index in range(1, len(nums)):
dp[index] = 1
for i in range(index):
if nums[index] > nums[i]:
dp[index] =... | the_stack_v2_python_sparse | 300.最长递增子序列.py | Ezi4Zy/leetcode | train | 0 | |
ed1377943e7bd8a8963a2147987a898bf5a72908 | [
"if isinstance(crop_size, int):\n self.size = (crop_size, crop_size)\nelse:\n self.size = crop_size\nself.padding = is_padding",
"w, h = img.size\ntw, th = self.size\nif w == tw and h == th:\n return (img, label)\nif self.padding and w < tw:\n w_p = tw - w\n img = ImageOps.expand(img, border=(w_p, ... | <|body_start_0|>
if isinstance(crop_size, int):
self.size = (crop_size, crop_size)
else:
self.size = crop_size
self.padding = is_padding
<|end_body_0|>
<|body_start_1|>
w, h = img.size
tw, th = self.size
if w == tw and h == th:
return ... | Crop the given PIL.Image at a random location. | RandomCrop | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomCrop:
"""Crop the given PIL.Image at a random location."""
def __init__(self, crop_size, is_padding=True):
""":param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. :param is_padding: (int or seq... | stack_v2_sparse_classes_75kplus_train_000869 | 11,352 | permissive | [
{
"docstring": ":param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. :param is_padding: (int or sequence, optional): Optional padding on each border of the image. Default is 0, i.e no padding. If a sequence of length 4 is provi... | 2 | stack_v2_sparse_classes_30k_train_050559 | Implement the Python class `RandomCrop` described below.
Class description:
Crop the given PIL.Image at a random location.
Method signatures and docstrings:
- def __init__(self, crop_size, is_padding=True): :param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square ... | Implement the Python class `RandomCrop` described below.
Class description:
Crop the given PIL.Image at a random location.
Method signatures and docstrings:
- def __init__(self, crop_size, is_padding=True): :param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square ... | f6e6565ddfb910d1aec477b34e58d79e097b339e | <|skeleton|>
class RandomCrop:
"""Crop the given PIL.Image at a random location."""
def __init__(self, crop_size, is_padding=True):
""":param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. :param is_padding: (int or seq... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomCrop:
"""Crop the given PIL.Image at a random location."""
def __init__(self, crop_size, is_padding=True):
""":param crop_size: Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. :param is_padding: (int or sequence, option... | the_stack_v2_python_sparse | dataset/data_loader.py | jtpils/structure_knowledge_distillation | train | 1 |
b78075e72465eb318933fba9584ae4154540b444 | [
"if not b:\n need_seconds = a[0]\nelse:\n need_seconds = self.least_need_second(a, b)\nhours = need_seconds // 3600\nmins = (need_seconds - hours * 3600) // 60\nseconds = need_seconds % 60\nif hours + 8 >= 12:\n end = 'pm'\n hours = hours + 8 - 12\n hours_str = ('0' if hours < 10 else '') + str(hours... | <|body_start_0|>
if not b:
need_seconds = a[0]
else:
need_seconds = self.least_need_second(a, b)
hours = need_seconds // 3600
mins = (need_seconds - hours * 3600) // 60
seconds = need_seconds % 60
if hours + 8 >= 12:
end = 'pm'
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
<|body_0|>
def least_need_second(self, a, b):
"""Args: a: list[int] b: list[int] Return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not b:
... | stack_v2_sparse_classes_75kplus_train_000870 | 2,060 | no_license | [
{
"docstring": "Args: a: list[int] b: list[int] Return: str",
"name": "earlest_off_time",
"signature": "def earlest_off_time(self, a, b)"
},
{
"docstring": "Args: a: list[int] b: list[int] Return: int",
"name": "least_need_second",
"signature": "def least_need_second(self, a, b)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018391 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str
- def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str
- def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int
<|skeleton|>
class... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
<|body_0|>
def least_need_second(self, a, b):
"""Args: a: list[int] b: list[int] Return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def earlest_off_time(self, a, b):
"""Args: a: list[int] b: list[int] Return: str"""
if not b:
need_seconds = a[0]
else:
need_seconds = self.least_need_second(a, b)
hours = need_seconds // 3600
mins = (need_seconds - hours * 3600) // 60
... | the_stack_v2_python_sparse | 秋招/网易/3.py | AiZhanghan/Leetcode | train | 0 | |
94022e56cb69a89d462462ec3373f40528487cde | [
"result = {'status': '', 'data': {}}\ntry:\n user = User.get_instance(request)\nexcept User.DoesNotExist:\n return Response(result, status=status.HTTP_404_NOT_FOUND)\nserializer = UserDetailSerializer(user)\nresult['data'] = serializer.data\nreturn Response(result, status=status.HTTP_200_OK)",
"result = {'s... | <|body_start_0|>
result = {'status': '', 'data': {}}
try:
user = User.get_instance(request)
except User.DoesNotExist:
return Response(result, status=status.HTTP_404_NOT_FOUND)
serializer = UserDetailSerializer(user)
result['data'] = serializer.data
... | Class to get one User info | Profile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Profile:
"""Class to get one User info"""
def get(request):
"""GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist"""
<|body_0|>
def post(request):
"""... | stack_v2_sparse_classes_75kplus_train_000871 | 7,499 | no_license | [
{
"docstring": "GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": ":param request: :return:",
"name": "post",
... | 3 | stack_v2_sparse_classes_30k_train_040633 | Implement the Python class `Profile` described below.
Class description:
Class to get one User info
Method signatures and docstrings:
- def get(request): GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist
... | Implement the Python class `Profile` described below.
Class description:
Class to get one User info
Method signatures and docstrings:
- def get(request): GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist
... | c5dc31147b3037864aaf57b6d4f575fe0d232255 | <|skeleton|>
class Profile:
"""Class to get one User info"""
def get(request):
"""GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist"""
<|body_0|>
def post(request):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Profile:
"""Class to get one User info"""
def get(request):
"""GET request to get one particular user :param request: :param user_id: :return: HTTP_200_OK and JSON-Documents: if all good HTTP_404_NOT_FOUND: if user don`t exist"""
result = {'status': '', 'data': {}}
try:
... | the_stack_v2_python_sparse | server/lmsinno/users/users_views.py | slavagoreev/librarian | train | 1 |
ff280ca47a570d71f3d240773b4776ff55a925c4 | [
"bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bundle.obj.minus.filesize, 'file': bundle.obj.minus.file.url}\nbd['author_name'] = bundle.obj.minus.author.name\nbd['filetype'] = str(bun... | <|body_start_0|>
bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bundle.obj.minus.filesize, 'file': bundle.obj.minus.file.url}
bd['author_name'] = bundle.obj.minus.author.nam... | MinusWeekStatsResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinusWeekStatsResource:
def _dehydrate_short(self, bundle):
"""put foreignkey data into the serialized bundle"""
<|body_0|>
def _dehydrate_full(self, bundle):
"""put foreignkey data into the serialized bundle"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_000872 | 5,016 | no_license | [
{
"docstring": "put foreignkey data into the serialized bundle",
"name": "_dehydrate_short",
"signature": "def _dehydrate_short(self, bundle)"
},
{
"docstring": "put foreignkey data into the serialized bundle",
"name": "_dehydrate_full",
"signature": "def _dehydrate_full(self, bundle)"
... | 2 | stack_v2_sparse_classes_30k_train_015912 | Implement the Python class `MinusWeekStatsResource` described below.
Class description:
Implement the MinusWeekStatsResource class.
Method signatures and docstrings:
- def _dehydrate_short(self, bundle): put foreignkey data into the serialized bundle
- def _dehydrate_full(self, bundle): put foreignkey data into the s... | Implement the Python class `MinusWeekStatsResource` described below.
Class description:
Implement the MinusWeekStatsResource class.
Method signatures and docstrings:
- def _dehydrate_short(self, bundle): put foreignkey data into the serialized bundle
- def _dehydrate_full(self, bundle): put foreignkey data into the s... | c61267e5a19142c2b7030534b24a2b7f97d0deb2 | <|skeleton|>
class MinusWeekStatsResource:
def _dehydrate_short(self, bundle):
"""put foreignkey data into the serialized bundle"""
<|body_0|>
def _dehydrate_full(self, bundle):
"""put foreignkey data into the serialized bundle"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinusWeekStatsResource:
def _dehydrate_short(self, bundle):
"""put foreignkey data into the serialized bundle"""
bd = {'title': bundle.obj.minus.title, 'id': bundle.obj.minus.id, 'resource_uri': '/api/v1/minusrecord/%s/' % bundle.obj.minus.id, 'length': bundle.obj.minus.length, 'filesize': bun... | the_stack_v2_python_sparse | modules/minusstore/api.py | ibitprogress/minus-master | train | 0 | |
2ee774699548099d520a436fbd62c4d5632dbc17 | [
"self.is_group_site = is_group_site\nself.is_private_channel_site = is_private_channel_site\nself.is_team_site = is_team_site",
"if dictionary is None:\n return None\nis_group_site = dictionary.get('isGroupSite')\nis_private_channel_site = dictionary.get('isPrivateChannelSite')\nis_team_site = dictionary.get('... | <|body_start_0|>
self.is_group_site = is_group_site
self.is_private_channel_site = is_private_channel_site
self.is_team_site = is_team_site
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_group_site = dictionary.get('isGroupSite')
is_pri... | Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is associated with a private channel of some team. is... | Office365SiteInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is assoc... | stack_v2_sparse_classes_75kplus_train_000873 | 2,121 | permissive | [
{
"docstring": "Constructor for the Office365SiteInfo class",
"name": "__init__",
"signature": "def __init__(self, is_group_site=None, is_private_channel_site=None, is_team_site=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A diction... | 2 | stack_v2_sparse_classes_30k_train_032090 | Implement the Python class `Office365SiteInfo` described below.
Class description:
Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Sp... | Implement the Python class `Office365SiteInfo` described below.
Class description:
Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Sp... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is assoc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is associated with a ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/office_365_site_info.py | cohesity/management-sdk-python | train | 24 |
630912a7aa09d063ac17e7baa36843011c793fcf | [
"for i in range(len(numbers)):\n current_value = numbers[i]\n for j in range(i + 1, len(numbers)):\n if current_value + numbers[j] == target:\n return [i + 1, j + 1]\n if current_value + numbers[j] > target:\n break",
"numbers_set = set(numbers)\nfor i in range(len(number... | <|body_start_0|>
for i in range(len(numbers)):
current_value = numbers[i]
for j in range(i + 1, len(numbers)):
if current_value + numbers[j] == target:
return [i + 1, j + 1]
if current_value + numbers[j] > target:
br... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_000874 | 1,092 | no_license | [
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, ta... | 2 | stack_v2_sparse_classes_30k_test_001918 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :r... | 6de551327f96ec4d4b63d0045281b65bbb4f5d0f | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
for i in range(len(numbers)):
current_value = numbers[i]
for j in range(i + 1, len(numbers)):
if current_value + numbers[j] == target:
... | the_stack_v2_python_sparse | twoSum.py | JingweiTu/leetcode | train | 0 | |
7c81e7007a38dc01afa31f3057f88bd1920f4b3c | [
"self._publisher = ZmqPub(host='*', port=port, serializer=U.serialize)\nif not isinstance(module_dict, ModuleDict):\n module_dict = ModuleDict(module_dict)\nself._module_dict = module_dict",
"binary = self._module_dict.dumps()\ninfo = {'time': time.time(), 'iteration': iteration, 'message': message, 'hash': U.... | <|body_start_0|>
self._publisher = ZmqPub(host='*', port=port, serializer=U.serialize)
if not isinstance(module_dict, ModuleDict):
module_dict = ModuleDict(module_dict)
self._module_dict = module_dict
<|end_body_0|>
<|body_start_1|>
binary = self._module_dict.dumps()
... | Publishes parameters from the learner side Using ZmqPub socket | ParameterPublisher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterPublisher:
"""Publishes parameters from the learner side Using ZmqPub socket"""
def __init__(self, port, module_dict):
"""Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes model parameters"""
<|body_0|>
def publish(self... | stack_v2_sparse_classes_75kplus_train_000875 | 9,955 | permissive | [
{
"docstring": "Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes model parameters",
"name": "__init__",
"signature": "def __init__(self, port, module_dict)"
},
{
"docstring": "Called by learner. Publishes model parameters with additional info Args: ite... | 2 | stack_v2_sparse_classes_30k_train_013010 | Implement the Python class `ParameterPublisher` described below.
Class description:
Publishes parameters from the learner side Using ZmqPub socket
Method signatures and docstrings:
- def __init__(self, port, module_dict): Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes mod... | Implement the Python class `ParameterPublisher` described below.
Class description:
Publishes parameters from the learner side Using ZmqPub socket
Method signatures and docstrings:
- def __init__(self, port, module_dict): Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes mod... | 2556bd9c362a53e0a94da914ba59b5d4621c4081 | <|skeleton|>
class ParameterPublisher:
"""Publishes parameters from the learner side Using ZmqPub socket"""
def __init__(self, port, module_dict):
"""Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes model parameters"""
<|body_0|>
def publish(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParameterPublisher:
"""Publishes parameters from the learner side Using ZmqPub socket"""
def __init__(self, port, module_dict):
"""Args: port: the port connected to the pub socket module_dict: ModuleDict object that exposes model parameters"""
self._publisher = ZmqPub(host='*', port=port,... | the_stack_v2_python_sparse | surreal/distributed/parameter_server.py | PeihongYu/surreal | train | 0 |
9772e464ac7e0ab4efac4a3e9331c46603657c97 | [
"name = self._hmdevice.__class__.__name__\nif name in HM_STATE_HA_CAST:\n return HM_STATE_HA_CAST[name].get(self._hm_get_state())\nreturn self._hm_get_state()",
"if self._state:\n self._data.update({self._state: None})\nelse:\n _LOGGER.critical('Unable to initialize sensor: %s', self._name)"
] | <|body_start_0|>
name = self._hmdevice.__class__.__name__
if name in HM_STATE_HA_CAST:
return HM_STATE_HA_CAST[name].get(self._hm_get_state())
return self._hm_get_state()
<|end_body_0|>
<|body_start_1|>
if self._state:
self._data.update({self._state: None})
... | Representation of a HomeMatic sensor. | HMSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HMSensor:
"""Representation of a HomeMatic sensor."""
def native_value(self):
"""Return the state of the sensor."""
<|body_0|>
def _init_data_struct(self):
"""Generate a data dictionary (self._data) from metadata."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_000876 | 12,081 | permissive | [
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def native_value(self)"
},
{
"docstring": "Generate a data dictionary (self._data) from metadata.",
"name": "_init_data_struct",
"signature": "def _init_data_struct(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053719 | Implement the Python class `HMSensor` described below.
Class description:
Representation of a HomeMatic sensor.
Method signatures and docstrings:
- def native_value(self): Return the state of the sensor.
- def _init_data_struct(self): Generate a data dictionary (self._data) from metadata. | Implement the Python class `HMSensor` described below.
Class description:
Representation of a HomeMatic sensor.
Method signatures and docstrings:
- def native_value(self): Return the state of the sensor.
- def _init_data_struct(self): Generate a data dictionary (self._data) from metadata.
<|skeleton|>
class HMSensor... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HMSensor:
"""Representation of a HomeMatic sensor."""
def native_value(self):
"""Return the state of the sensor."""
<|body_0|>
def _init_data_struct(self):
"""Generate a data dictionary (self._data) from metadata."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HMSensor:
"""Representation of a HomeMatic sensor."""
def native_value(self):
"""Return the state of the sensor."""
name = self._hmdevice.__class__.__name__
if name in HM_STATE_HA_CAST:
return HM_STATE_HA_CAST[name].get(self._hm_get_state())
return self._hm_get... | the_stack_v2_python_sparse | homeassistant/components/homematic/sensor.py | home-assistant/core | train | 35,501 |
85998a2183b73632936b24c5028c6576b8ccc6ec | [
"super(ConcatBatcher, self).__init__()\nself.device = device\nself.model = model",
"if self.model == 'KPConv' or self.model == 'KPFCNN':\n batching_result = KPConvBatch(batches)\n batching_result.to(self.device)\n return {'data': batching_result, 'attr': []}\nelif self.model == 'SparseConvUnet':\n ret... | <|body_start_0|>
super(ConcatBatcher, self).__init__()
self.device = device
self.model = model
<|end_body_0|>
<|body_start_1|>
if self.model == 'KPConv' or self.model == 'KPFCNN':
batching_result = KPConvBatch(batches)
batching_result.to(self.device)
... | ConcatBatcher for KPConv. | ConcatBatcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcatBatcher:
"""ConcatBatcher for KPConv."""
def __init__(self, device, model='KPConv'):
"""Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class."""
<|body_0|>
def collate_fn(self, batches):
"""Collate function called by... | stack_v2_sparse_classes_75kplus_train_000877 | 19,262 | permissive | [
{
"docstring": "Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class.",
"name": "__init__",
"signature": "def __init__(self, device, model='KPConv')"
},
{
"docstring": "Collate function called by original PyTorch dataloader. Args: batches: a batch of data... | 2 | null | Implement the Python class `ConcatBatcher` described below.
Class description:
ConcatBatcher for KPConv.
Method signatures and docstrings:
- def __init__(self, device, model='KPConv'): Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class.
- def collate_fn(self, batches): Colla... | Implement the Python class `ConcatBatcher` described below.
Class description:
ConcatBatcher for KPConv.
Method signatures and docstrings:
- def __init__(self, device, model='KPConv'): Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class.
- def collate_fn(self, batches): Colla... | 51482281dc180786e7563c73c12ac5df89289748 | <|skeleton|>
class ConcatBatcher:
"""ConcatBatcher for KPConv."""
def __init__(self, device, model='KPConv'):
"""Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class."""
<|body_0|>
def collate_fn(self, batches):
"""Collate function called by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConcatBatcher:
"""ConcatBatcher for KPConv."""
def __init__(self, device, model='KPConv'):
"""Initialize. Args: device: torch device 'gpu' or 'cpu' Returns: class: The corresponding class."""
super(ConcatBatcher, self).__init__()
self.device = device
self.model = model
... | the_stack_v2_python_sparse | ml3d/torch/dataloaders/concat_batcher.py | CosmosHua/Open3D-ML | train | 0 |
03d7fd089563a8c43c11c143ae8cab405d61a3ed | [
"self.input_dim = input_dim\nself.hidden_dim = hidden_dim\nself.with_batch = with_batch\nself.name = name\nself.w_x = shared((input_dim, hidden_dim), name + '__w_x')\nself.w_xr = shared((input_dim, hidden_dim), name + '__w_xr')\nself.w_hr = shared((hidden_dim, hidden_dim), name + '__w_hr')\nself.w_xz = shared((inpu... | <|body_start_0|>
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.with_batch = with_batch
self.name = name
self.w_x = shared((input_dim, hidden_dim), name + '__w_x')
self.w_xr = shared((input_dim, hidden_dim), name + '__w_xr')
self.w_hr = shared((hidde... | Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length, input_dim) Output: matrix of dimension (batch_size, output_dim) | GRU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
"""Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length, input_dim) Output: matrix of dimension... | stack_v2_sparse_classes_75kplus_train_000878 | 17,166 | no_license | [
{
"docstring": "Initialize neural network.",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, with_batch=True, name='GRU')"
},
{
"docstring": "Propagate the input through the network and return the last hidden vector. The whole sequence is also accessible via self.h, b... | 2 | stack_v2_sparse_classes_30k_train_025999 | Implement the Python class `GRU` described below.
Class description:
Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length,... | Implement the Python class `GRU` described below.
Class description:
Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length,... | 094cbfd803320b6765225c63143ec162ac42cd97 | <|skeleton|>
class GRU:
"""Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length, input_dim) Output: matrix of dimension... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRU:
"""Gated recurrent unit (GRU). Can be used with or without batches. Without batches: Input: matrix of dimension (sequence_length, input_dim) Output: vector of dimension (output_dim) With batches: Input: tensor3 of dimension (batch_size, sequence_length, input_dim) Output: matrix of dimension (batch_size,... | the_stack_v2_python_sparse | Bi-LSTM-CRF-pos/Bi-LSTM-CRF-pos/nn.py | zwqll/entity | train | 0 |
481e04e30e4ad1c375a1d9e98e6a9b55bc2cbc93 | [
"if not isinstance(hour, (list, tuple)):\n hour = [hour]\nif not isinstance(min, (list, tuple)):\n min = [min]\nif not isinstance(sec, (list, tuple)):\n sec = [sec]\nself._timings = (hour, min, sec)\nself._last_time = datetime.datetime.now()\nself._schedule_next()",
"hour, min, sec = self._timings\nnow =... | <|body_start_0|>
if not isinstance(hour, (list, tuple)):
hour = [hour]
if not isinstance(min, (list, tuple)):
min = [min]
if not isinstance(sec, (list, tuple)):
sec = [sec]
self._timings = (hour, min, sec)
self._last_time = datetime.datetime.no... | A timer that is triggered at a specific time of day. Once the timer fires it is stopped. | OneShotAtTimer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 s... | stack_v2_sparse_classes_75kplus_train_000879 | 11,203 | no_license | [
{
"docstring": "Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 seconds. The timer has second precision. :param hour: the hour number (0-23) or list of hours :type hour: int or list of ints :param min: the minute number (0-59) or list of minutes ... | 2 | stack_v2_sparse_classes_30k_train_030075 | Implement the Python class `OneShotAtTimer` described below.
Class description:
A timer that is triggered at a specific time of day. Once the timer fires it is stopped.
Method signatures and docstrings:
- def start(self, hour=range(24), min=range(60), sec=0): Starts the timer, causing it to be fired at the specified ... | Implement the Python class `OneShotAtTimer` described below.
Class description:
A timer that is triggered at a specific time of day. Once the timer fires it is stopped.
Method signatures and docstrings:
- def start(self, hour=range(24), min=range(60), sec=0): Starts the timer, causing it to be fired at the specified ... | 1a75e48dae55876f04718cfd594cfc6e43e5c966 | <|skeleton|>
class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 seconds. The t... | the_stack_v2_python_sparse | env/lib/python2.7/site-packages/kaa/timer.py | jpmunz/smartplayer | train | 0 |
a18c00971bdea624a2d96c908c0235c2f5b4c710 | [
"result = {}\nfor rec in self.browse(cr, uid, ids, context):\n result[rec.id] = rec.partner_vat\nreturn result",
"if context is None:\n context = {}\nres = {}\nfor item in self.browse(cr, uid, ids):\n if item.partner_vat and item.country_id and item.total_operation_amount:\n res[item.id] = True\n ... | <|body_start_0|>
result = {}
for rec in self.browse(cr, uid, ids, context):
result[rec.id] = rec.partner_vat
return result
<|end_body_0|>
<|body_start_1|>
if context is None:
context = {}
res = {}
for item in self.browse(cr, uid, ids):
... | AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner | l10n_es_aeat_mod349_partner_record | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class l10n_es_aeat_mod349_partner_record:
"""AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner"""
def get_record_name(self, cr, uid, ids, field_name, args, context={}):
"""Returns the record name"""
<|body_0|>
def _check_partner_re... | stack_v2_sparse_classes_75kplus_train_000880 | 20,364 | no_license | [
{
"docstring": "Returns the record name",
"name": "get_record_name",
"signature": "def get_record_name(self, cr, uid, ids, field_name, args, context={})"
},
{
"docstring": "Checks if all line fields are filled",
"name": "_check_partner_record_line",
"signature": "def _check_partner_recor... | 3 | stack_v2_sparse_classes_30k_train_015980 | Implement the Python class `l10n_es_aeat_mod349_partner_record` described below.
Class description:
AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner
Method signatures and docstrings:
- def get_record_name(self, cr, uid, ids, field_name, args, context={}): Returns the rec... | Implement the Python class `l10n_es_aeat_mod349_partner_record` described below.
Class description:
AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner
Method signatures and docstrings:
- def get_record_name(self, cr, uid, ids, field_name, args, context={}): Returns the rec... | 1303d175d74e41d03a167d0e15d84be419d32121 | <|skeleton|>
class l10n_es_aeat_mod349_partner_record:
"""AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner"""
def get_record_name(self, cr, uid, ids, field_name, args, context={}):
"""Returns the record name"""
<|body_0|>
def _check_partner_re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class l10n_es_aeat_mod349_partner_record:
"""AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner"""
def get_record_name(self, cr, uid, ids, field_name, args, context={}):
"""Returns the record name"""
result = {}
for rec in self.browse(cr, uid... | the_stack_v2_python_sparse | l10n_es_aeat_mod349/mod349.py | kailIII/openerp-spain | train | 0 |
120a6de172fefe594e6a580d6cd4538fa5ba97db | [
"self.c = c\nself.at = c.atFileCommands\nself.at.outputList = []",
"at = self.at\nat.os(s[:-1] if s.endswith('\\n') else s)\nat.onl()",
"at = self.at\ngnx = p.v.fileIndex\nlevel = p.level()\nif level > 2:\n s = '%s: *%s* %s' % (gnx, level, p.h)\nelse:\n s = '%s: %s %s' % (gnx, '*' * level, p.h)\nat.os('%s... | <|body_start_0|>
self.c = c
self.at = c.atFileCommands
self.at.outputList = []
<|end_body_0|>
<|body_start_1|>
at = self.at
at.os(s[:-1] if s.endswith('\n') else s)
at.onl()
<|end_body_1|>
<|body_start_2|>
at = self.at
gnx = p.v.fileIndex
level =... | The base writer class for all writers in leo.plugins.writers. | BaseWriter | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseWriter:
"""The base writer class for all writers in leo.plugins.writers."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for leo.plugins.writers.BaseWriter."""
<|body_0|>
def put(self, s: str) -> None:
"""Write line s using at.os, taking special care of newli... | stack_v2_sparse_classes_75kplus_train_000881 | 1,404 | permissive | [
{
"docstring": "Ctor for leo.plugins.writers.BaseWriter.",
"name": "__init__",
"signature": "def __init__(self, c: Cmdr) -> None"
},
{
"docstring": "Write line s using at.os, taking special care of newlines.",
"name": "put",
"signature": "def put(self, s: str) -> None"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_049739 | Implement the Python class `BaseWriter` described below.
Class description:
The base writer class for all writers in leo.plugins.writers.
Method signatures and docstrings:
- def __init__(self, c: Cmdr) -> None: Ctor for leo.plugins.writers.BaseWriter.
- def put(self, s: str) -> None: Write line s using at.os, taking ... | Implement the Python class `BaseWriter` described below.
Class description:
The base writer class for all writers in leo.plugins.writers.
Method signatures and docstrings:
- def __init__(self, c: Cmdr) -> None: Ctor for leo.plugins.writers.BaseWriter.
- def put(self, s: str) -> None: Write line s using at.os, taking ... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class BaseWriter:
"""The base writer class for all writers in leo.plugins.writers."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for leo.plugins.writers.BaseWriter."""
<|body_0|>
def put(self, s: str) -> None:
"""Write line s using at.os, taking special care of newli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseWriter:
"""The base writer class for all writers in leo.plugins.writers."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for leo.plugins.writers.BaseWriter."""
self.c = c
self.at = c.atFileCommands
self.at.outputList = []
def put(self, s: str) -> None:
"""... | the_stack_v2_python_sparse | leo/plugins/writers/basewriter.py | leo-editor/leo-editor | train | 1,671 |
1ab9e1704ba27d6d4d61b2718f9d1c53d61571ba | [
"if not os.path.exists(base_path):\n os.makedirs(base_path)\nfor fn in NAIPTileIndex.INDEX_FNS:\n if not os.path.exists(os.path.join(base_path, fn)):\n download_url(NAIPTileIndex.NAIP_INDEX_BLOB_ROOT + fn, os.path.join(base_path, fn), verbose)\nself.base_path = base_path\nself.tile_rtree = rtree.index.... | <|body_start_0|>
if not os.path.exists(base_path):
os.makedirs(base_path)
for fn in NAIPTileIndex.INDEX_FNS:
if not os.path.exists(os.path.join(base_path, fn)):
download_url(NAIPTileIndex.NAIP_INDEX_BLOB_ROOT + fn, os.path.join(base_path, fn), verbose)
sel... | Utility class for performing NAIP tile lookups by location | NAIPTileIndex | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NAIPTileIndex:
"""Utility class for performing NAIP tile lookups by location"""
def __init__(self, base_path, verbose=False):
"""Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files from the blob container if they do not exist in the `base_... | stack_v2_sparse_classes_75kplus_train_000882 | 5,605 | permissive | [
{
"docstring": "Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files from the blob container if they do not exist in the `base_path/` directory. Args: base_path (str): The path on the local system to look for/store the three files that make up the tile index. This pat... | 3 | stack_v2_sparse_classes_30k_train_041499 | Implement the Python class `NAIPTileIndex` described below.
Class description:
Utility class for performing NAIP tile lookups by location
Method signatures and docstrings:
- def __init__(self, base_path, verbose=False): Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files f... | Implement the Python class `NAIPTileIndex` described below.
Class description:
Utility class for performing NAIP tile lookups by location
Method signatures and docstrings:
- def __init__(self, base_path, verbose=False): Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files f... | ff141cd6b7a7b504c18b0987fbfd58ec6552df43 | <|skeleton|>
class NAIPTileIndex:
"""Utility class for performing NAIP tile lookups by location"""
def __init__(self, base_path, verbose=False):
"""Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files from the blob container if they do not exist in the `base_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NAIPTileIndex:
"""Utility class for performing NAIP tile lookups by location"""
def __init__(self, base_path, verbose=False):
"""Loads the tile index into memory (~400 MB) for use by `self.lookup()`. Downloads the index files from the blob container if they do not exist in the `base_path/` direct... | the_stack_v2_python_sparse | geospatial/data/NAIPTileIndex.py | microsoft/ai4eutils | train | 40 |
25a485affe12b009bdcd68445c583e2c8c66c755 | [
"self.nodes = network.nodes\nfor i in range(2 * m):\n node1 = self.chooseNode()\n node2 = random.choice(node1.nodelist)\n node3 = self.chooseNode()\n node4 = random.choice(node3.nodelist)\n node1.addLinkTo(node4)\n node3.addLinkTo(node2)\n node1.removeLinkTo(node2)\n node3.removeLinkTo(node4... | <|body_start_0|>
self.nodes = network.nodes
for i in range(2 * m):
node1 = self.chooseNode()
node2 = random.choice(node1.nodelist)
node3 = self.chooseNode()
node4 = random.choice(node3.nodelist)
node1.addLinkTo(node4)
node3.addLinkT... | function that takes a network with m edges and returns a randomised version of that network | RandomizedNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedNetwork:
"""function that takes a network with m edges and returns a randomised version of that network"""
def __createNetwork__(self, network, m):
"""for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 = (n3; n4) from the network and rewire them such that the... | stack_v2_sparse_classes_75kplus_train_000883 | 1,341 | no_license | [
{
"docstring": "for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 = (n3; n4) from the network and rewire them such that the start and end nodes are swapped :param network: network :param m: number of edges",
"name": "__createNetwork__",
"signature": "def __createNetwork__(self, network, ... | 2 | stack_v2_sparse_classes_30k_train_040348 | Implement the Python class `RandomizedNetwork` described below.
Class description:
function that takes a network with m edges and returns a randomised version of that network
Method signatures and docstrings:
- def __createNetwork__(self, network, m): for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 ... | Implement the Python class `RandomizedNetwork` described below.
Class description:
function that takes a network with m edges and returns a randomised version of that network
Method signatures and docstrings:
- def __createNetwork__(self, network, m): for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 ... | fcd4b75158af516645b64ae4d4cefde784edf9b2 | <|skeleton|>
class RandomizedNetwork:
"""function that takes a network with m edges and returns a randomised version of that network"""
def __createNetwork__(self, network, m):
"""for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 = (n3; n4) from the network and rewire them such that the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedNetwork:
"""function that takes a network with m edges and returns a randomised version of that network"""
def __createNetwork__(self, network, m):
"""for 2m iterations, randomly select two edges e1 = (n1; n2) and e2 = (n3; n4) from the network and rewire them such that the start and en... | the_stack_v2_python_sparse | Assign5/RandomizedNetwork.py | KupitzA/BI3 | train | 0 |
d45cf14f156b82aabb1c73d9f69302229ed3588a | [
"r = self.BI.login(user='test2', psw='123456')\nstatus_code = r.get('code')\nresponse = r.get('body')\nself.CA.assert_code(status_code, 200)\nself.CA.assert_result(response['code'], 0)\nself.CA.assert_result(response['msg'], 'login success!')",
"r = self.BI.login(user='test2', psw='000000')\nstatus_code = r.get('... | <|body_start_0|>
r = self.BI.login(user='test2', psw='123456')
status_code = r.get('code')
response = r.get('body')
self.CA.assert_code(status_code, 200)
self.CA.assert_result(response['code'], 0)
self.CA.assert_result(response['msg'], 'login success!')
<|end_body_0|>
<|... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_success(self):
"""正确账号密码,登陆成功"""
<|body_0|>
def test_login_fail(self, login_fixture):
"""错误密码,登陆失败"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r = self.BI.login(user='test2', psw='123456')
status_code = r.get('c... | stack_v2_sparse_classes_75kplus_train_000884 | 1,129 | no_license | [
{
"docstring": "正确账号密码,登陆成功",
"name": "test_login_success",
"signature": "def test_login_success(self)"
},
{
"docstring": "错误密码,登陆失败",
"name": "test_login_fail",
"signature": "def test_login_fail(self, login_fixture)"
}
] | 2 | null | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self): 正确账号密码,登陆成功
- def test_login_fail(self, login_fixture): 错误密码,登陆失败 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self): 正确账号密码,登陆成功
- def test_login_fail(self, login_fixture): 错误密码,登陆失败
<|skeleton|>
class TestLogin:
def test_login_success(self):
"""正确账... | 145715a5881a1179a36e5fc9c23f35ccc26906a7 | <|skeleton|>
class TestLogin:
def test_login_success(self):
"""正确账号密码,登陆成功"""
<|body_0|>
def test_login_fail(self, login_fixture):
"""错误密码,登陆失败"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLogin:
def test_login_success(self):
"""正确账号密码,登陆成功"""
r = self.BI.login(user='test2', psw='123456')
status_code = r.get('code')
response = r.get('body')
self.CA.assert_code(status_code, 200)
self.CA.assert_result(response['code'], 0)
self.CA.assert_... | the_stack_v2_python_sparse | PytestAPI/case/login_test.py | asceyan/TestFrame | train | 2 | |
88af2cd58d94aed0233589821d1727384843235b | [
"if not nums:\n return []\ns = set(nums)\nm = len(nums)\nres = []\ntemp = [ele for ele in range(1, m + 1)]\nfor ele in temp:\n if ele not in s:\n res.append(ele)\nreturn res",
"res = []\nfor i in range(len(nums)):\n index = abs(nums[i]) - 1\n nums[index] = -abs(nums[index])\nfor j in range(len(... | <|body_start_0|>
if not nums:
return []
s = set(nums)
m = len(nums)
res = []
temp = [ele for ele in range(1, m + 1)]
for ele in temp:
if ele not in s:
res.append(ele)
return res
<|end_body_0|>
<|body_start_1|>
res =... | Method 1 (requires extra space, a set) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Method 1 (requires extra space, a set)"""
def findDisappearedNumbersA(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbersB(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_000885 | 1,234 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbersA",
"signature": "def findDisappearedNumbersA(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbersB",
"signature": "def findDisappearedNumbersB(se... | 2 | stack_v2_sparse_classes_30k_train_046604 | Implement the Python class `Solution` described below.
Class description:
Method 1 (requires extra space, a set)
Method signatures and docstrings:
- def findDisappearedNumbersA(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbersB(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Method 1 (requires extra space, a set)
Method signatures and docstrings:
- def findDisappearedNumbersA(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbersB(self, nums): :type nums: List[int] :rtype: List[int]
<|sk... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
"""Method 1 (requires extra space, a set)"""
def findDisappearedNumbersA(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbersB(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Method 1 (requires extra space, a set)"""
def findDisappearedNumbersA(self, nums):
""":type nums: List[int] :rtype: List[int]"""
if not nums:
return []
s = set(nums)
m = len(nums)
res = []
temp = [ele for ele in range(1, m + 1)]
... | the_stack_v2_python_sparse | 2.SET/find_all_numbers_disappeared/solution.py | kimmyoo/python_leetcode | train | 1 |
16c78f93f93551d67d56a428039feb5d3b044c74 | [
"super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)\nself.num_n_grams = int(max_string_length / fragment_length)\nif alphabet is not None and padding_char in alphabet:\n raise RuntimeError('TreeHistClient was passed a padding character that is in the... | <|body_start_0|>
super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)
self.num_n_grams = int(max_string_length / fragment_length)
if alphabet is not None and padding_char in alphabet:
raise RuntimeError('TreeHistClient was ... | TreeHistClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeHistClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, padding_char='*'):
"""Args: epsilon (float): Privacy Budget fragment_length: the length to increase the fragment by on each iteration max_string_length: max s... | stack_v2_sparse_classes_75kplus_train_000886 | 3,074 | permissive | [
{
"docstring": "Args: epsilon (float): Privacy Budget fragment_length: the length to increase the fragment by on each iteration max_string_length: max size of the strings to find alphabet (optional list): The alphabet over which we are privatising strings index_mapper (optional func): Index map function fo_clie... | 3 | null | Implement the Python class `TreeHistClient` described below.
Class description:
Implement the TreeHistClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, padding_char='*'): Args: epsilon (float): Privacy Bu... | Implement the Python class `TreeHistClient` described below.
Class description:
Implement the TreeHistClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, padding_char='*'): Args: epsilon (float): Privacy Bu... | d0fe2a8ce29515a638d6964419b72b58046dcc44 | <|skeleton|>
class TreeHistClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, padding_char='*'):
"""Args: epsilon (float): Privacy Budget fragment_length: the length to increase the fragment by on each iteration max_string_length: max s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeHistClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, padding_char='*'):
"""Args: epsilon (float): Privacy Budget fragment_length: the length to increase the fragment by on each iteration max_string_length: max size of the str... | the_stack_v2_python_sparse | pure_ldp/heavy_hitters/treehistogram/treehist_client.py | hbcbh1999/pure-LDP | train | 0 | |
bba35207441e50dcd0e3340ed6f64662f3e8694e | [
"if key[:2] == '__':\n raise AttributeError(key)\nreturn self[key]",
"if key[:2] == '__':\n return dict.__setattr__(self, key, value)\nif isinstance(value, types.FunctionType):\n value = types.MethodType(value, self)\nelif isinstance(value, types.MethodType):\n value = types.MethodType(value.__func__,... | <|body_start_0|>
if key[:2] == '__':
raise AttributeError(key)
return self[key]
<|end_body_0|>
<|body_start_1|>
if key[:2] == '__':
return dict.__setattr__(self, key, value)
if isinstance(value, types.FunctionType):
value = types.MethodType(value, sel... | Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x pdct.mult_x(2) --> 2 To assign a static member use []: def mult(a,b): return ... | PrettyDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrettyDict:
"""Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x pdct.mult_x(2) --> 2 To assign a static... | stack_v2_sparse_classes_75kplus_train_000887 | 5,981 | permissive | [
{
"docstring": "Equyivalent to self[key]",
"name": "__getattr__",
"signature": "def __getattr__(self, key: str)"
},
{
"docstring": "Equivalent to self[key] = value",
"name": "__setattr__",
"signature": "def __setattr__(self, key: str, value)"
},
{
"docstring": "Equivalent of self... | 3 | stack_v2_sparse_classes_30k_val_001736 | Implement the Python class `PrettyDict` described below.
Class description:
Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x ... | Implement the Python class `PrettyDict` described below.
Class description:
Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x ... | bca73adeecdbf71a1f5ee466ded67d6c1ed4e94d | <|skeleton|>
class PrettyDict:
"""Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x pdct.mult_x(2) --> 2 To assign a static... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrettyDict:
"""Dictionary which allows accessing its members with member notation, e.g. pdct = PrettyDict() pdct.x = 1 x = pdct.x Functions will be made members, i.e the following works as expected def mult_x(self, a): return self.x * a pdct.mult_x = mult_x pdct.mult_x(2) --> 2 To assign a static member use [... | the_stack_v2_python_sparse | cdxbasics/prettydict.py | hansbuehler/cdxbasics | train | 2 |
1efc3d3486133799bd2ef74a978e9c9f4852262d | [
"parent_parsed_url = urllib.parse.urlparse(parent_partition_url)\nparent_path = PurePosixPath(parent_parsed_url.path)\nparent_stem = parent_path.stem\npartition_path = parent_path.parent / '{}-{}.json'.format(parent_stem, partition_name)\npartition_parsed_url = parent_parsed_url._replace(path=str(partition_path))\n... | <|body_start_0|>
parent_parsed_url = urllib.parse.urlparse(parent_partition_url)
parent_path = PurePosixPath(parent_parsed_url.path)
parent_stem = parent_path.stem
partition_path = parent_path.parent / '{}-{}.json'.format(parent_stem, partition_name)
partition_parsed_url = parent... | WriterContract | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriterContract:
def partition_url_generator(self, parent_partition_url: str, partition_name: str) -> str:
"""Given the url of the parent partition and the name of a partition to be added to the parent partition, return the url of the resulting of the resulting partition. Parameters -----... | stack_v2_sparse_classes_75kplus_train_000888 | 12,543 | permissive | [
{
"docstring": "Given the url of the parent partition and the name of a partition to be added to the parent partition, return the url of the resulting of the resulting partition. Parameters ---------- parent_partition_url : str The URL of the parent partition. partition_name : str The name of the partition we'r... | 3 | stack_v2_sparse_classes_30k_train_046858 | Implement the Python class `WriterContract` described below.
Class description:
Implement the WriterContract class.
Method signatures and docstrings:
- def partition_url_generator(self, parent_partition_url: str, partition_name: str) -> str: Given the url of the parent partition and the name of a partition to be adde... | Implement the Python class `WriterContract` described below.
Class description:
Implement the WriterContract class.
Method signatures and docstrings:
- def partition_url_generator(self, parent_partition_url: str, partition_name: str) -> str: Given the url of the parent partition and the name of a partition to be adde... | eb8e1d3899628db66cffed1370f2a7e6dd729c4f | <|skeleton|>
class WriterContract:
def partition_url_generator(self, parent_partition_url: str, partition_name: str) -> str:
"""Given the url of the parent partition and the name of a partition to be added to the parent partition, return the url of the resulting of the resulting partition. Parameters -----... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriterContract:
def partition_url_generator(self, parent_partition_url: str, partition_name: str) -> str:
"""Given the url of the parent partition and the name of a partition to be added to the parent partition, return the url of the resulting of the resulting partition. Parameters ---------- parent_p... | the_stack_v2_python_sparse | slicedimage/io/_base.py | spacetx/slicedimage | train | 7 | |
b176edb56f363151fee8af905018296bd7e5f998 | [
"url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id)\nr = requests.get(url)\nreturn BeautifulSoup(r.text, 'html.parser')",
"form = self.soup(remote_id).find('form', {'name': 'frm_daily'})\ntable = form.findChild('table')\nchildren = table.findChildren('tr')[5].findChildren('td')\ndt = arrow.get(children[0].... | <|body_start_0|>
url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id)
r = requests.get(url)
return BeautifulSoup(r.text, 'html.parser')
<|end_body_0|>
<|body_start_1|>
form = self.soup(remote_id).find('form', {'name': 'frm_daily'})
table = form.findChild('table')
ch... | Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil | Corps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Corps:
"""Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil"""
def soup(self, remote_id):
"""Return a beautiful soup object from rivergages.mvr.usace.army.mil"""
<|body_0|>
def dt_value(self, remote_id):
"""Return the most recent datetime and v... | stack_v2_sparse_classes_75kplus_train_000889 | 1,525 | no_license | [
{
"docstring": "Return a beautiful soup object from rivergages.mvr.usace.army.mil",
"name": "soup",
"signature": "def soup(self, remote_id)"
},
{
"docstring": "Return the most recent datetime and value",
"name": "dt_value",
"signature": "def dt_value(self, remote_id)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_test_000462 | Implement the Python class `Corps` described below.
Class description:
Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil
Method signatures and docstrings:
- def soup(self, remote_id): Return a beautiful soup object from rivergages.mvr.usace.army.mil
- def dt_value(self, remote_id): Return the most ... | Implement the Python class `Corps` described below.
Class description:
Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil
Method signatures and docstrings:
- def soup(self, remote_id): Return a beautiful soup object from rivergages.mvr.usace.army.mil
- def dt_value(self, remote_id): Return the most ... | 21dfc83758b689410578faef697398afab92fded | <|skeleton|>
class Corps:
"""Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil"""
def soup(self, remote_id):
"""Return a beautiful soup object from rivergages.mvr.usace.army.mil"""
<|body_0|>
def dt_value(self, remote_id):
"""Return the most recent datetime and v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Corps:
"""Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil"""
def soup(self, remote_id):
"""Return a beautiful soup object from rivergages.mvr.usace.army.mil"""
url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id)
r = requests.get(url)
return Beaut... | the_stack_v2_python_sparse | web/app/remote/corps.py | abkfenris/gage-web | train | 1 |
d3a1784a858399b9e57c0f349f6451169f6e321b | [
"super(OnlineBCTrainer, self).__init__(brain, trainer_parameters, training, load, seed, run_id)\nself.param_keys = ['brain_to_imitate', 'batch_size', 'time_horizon', 'summary_freq', 'max_steps', 'batches_per_epoch', 'use_recurrent', 'hidden_units', 'learning_rate', 'num_layers', 'sequence_length', 'memory_size', 'm... | <|body_start_0|>
super(OnlineBCTrainer, self).__init__(brain, trainer_parameters, training, load, seed, run_id)
self.param_keys = ['brain_to_imitate', 'batch_size', 'time_horizon', 'summary_freq', 'max_steps', 'batches_per_epoch', 'use_recurrent', 'hidden_units', 'learning_rate', 'num_layers', 'sequence... | The OnlineBCTrainer is an implementation of Online Behavioral Cloning. | OnlineBCTrainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnlineBCTrainer:
"""The OnlineBCTrainer is an implementation of Online Behavioral Cloning."""
def __init__(self, brain, trainer_parameters, training, load, seed, run_id):
"""Responsible for collecting experiences and training PPO model. :param trainer_parameters: The parameters for t... | stack_v2_sparse_classes_75kplus_train_000890 | 6,685 | permissive | [
{
"docstring": "Responsible for collecting experiences and training PPO model. :param trainer_parameters: The parameters for the trainer (dictionary). :param training: Whether the trainer is set for training. :param load: Whether the model should be loaded. :param seed: The seed the model will be initialized wi... | 3 | stack_v2_sparse_classes_30k_train_033262 | Implement the Python class `OnlineBCTrainer` described below.
Class description:
The OnlineBCTrainer is an implementation of Online Behavioral Cloning.
Method signatures and docstrings:
- def __init__(self, brain, trainer_parameters, training, load, seed, run_id): Responsible for collecting experiences and training P... | Implement the Python class `OnlineBCTrainer` described below.
Class description:
The OnlineBCTrainer is an implementation of Online Behavioral Cloning.
Method signatures and docstrings:
- def __init__(self, brain, trainer_parameters, training, load, seed, run_id): Responsible for collecting experiences and training P... | 334df1e8afbfff3544413ade46fb12f03556014b | <|skeleton|>
class OnlineBCTrainer:
"""The OnlineBCTrainer is an implementation of Online Behavioral Cloning."""
def __init__(self, brain, trainer_parameters, training, load, seed, run_id):
"""Responsible for collecting experiences and training PPO model. :param trainer_parameters: The parameters for t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OnlineBCTrainer:
"""The OnlineBCTrainer is an implementation of Online Behavioral Cloning."""
def __init__(self, brain, trainer_parameters, training, load, seed, run_id):
"""Responsible for collecting experiences and training PPO model. :param trainer_parameters: The parameters for the trainer (d... | the_stack_v2_python_sparse | mlagents/trainers/bc/online_trainer.py | Abluceli/HRG-SAC | train | 7 |
34eb3eabde4d8665502d141338d7b82776449095 | [
"if len(s) == 0:\n return ''\nvowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']\ntemp = []\nans = []\nvowels = []\nfor i in xrange(len(s)):\n if s[i] in vowelsTable:\n x = '~'\n vowels.append(s[i])\n else:\n x = s[i]\n temp.append(x)\nfor i in temp:\n if i == '~':\... | <|body_start_0|>
if len(s) == 0:
return ''
vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']
temp = []
ans = []
vowels = []
for i in xrange(len(s)):
if s[i] in vowelsTable:
x = '~'
vowels.append(s[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def reverseVowels_2_ptr(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_000891 | 2,402 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels2",
"signature": "def reverseVowels2(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name... | 3 | stack_v2_sparse_classes_30k_train_045990 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
- def reverseVowels_2_ptr(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
- def reverseVowels_2_ptr(self, s): :type s: str :rtype: str
<|skele... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def reverseVowels_2_ptr(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
if len(s) == 0:
return ''
vowelsTable = ['a', 'A', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U']
temp = []
ans = []
vowels = []
for i in xrange(len(s)):
if s[i] in vow... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00345.Reverse_Vowels_of_a_String.py | roger6blog/LeetCode | train | 0 | |
72d41cec9019968d506013a154394b7879a3ebb4 | [
"utils = Utility()\nself.__conf = utils.CONFIG\nconns = utils.get_all_plugins(self.__conf.PATH_CONNECTION_MANAGERS)\nself.__conn_wh = conns[0].plugin_object\nself.__conn_wh.connect(self.__conf.URL_TEST_DB)\nbrowsers = utils.get_all_plugins(self.__conf.PATH_BROWSER)\nself.__browser = browsers[0].plugin_object\nself.... | <|body_start_0|>
utils = Utility()
self.__conf = utils.CONFIG
conns = utils.get_all_plugins(self.__conf.PATH_CONNECTION_MANAGERS)
self.__conn_wh = conns[0].plugin_object
self.__conn_wh.connect(self.__conf.URL_TEST_DB)
browsers = utils.get_all_plugins(self.__conf.PATH_BROW... | Testcase for Repository Maager | RepositoryManagerTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryManagerTestCase:
"""Testcase for Repository Maager"""
def setUp(self):
"""Setups the test case for testing the repo mgr class"""
<|body_0|>
def test_save_and_get_db(self):
"""Test the repository managers functionality for saving and reading back the dat... | stack_v2_sparse_classes_75kplus_train_000892 | 7,338 | no_license | [
{
"docstring": "Setups the test case for testing the repo mgr class",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the repository managers functionality for saving and reading back the database meta properties",
"name": "test_save_and_get_db",
"signature": "def... | 6 | null | Implement the Python class `RepositoryManagerTestCase` described below.
Class description:
Testcase for Repository Maager
Method signatures and docstrings:
- def setUp(self): Setups the test case for testing the repo mgr class
- def test_save_and_get_db(self): Test the repository managers functionality for saving and... | Implement the Python class `RepositoryManagerTestCase` described below.
Class description:
Testcase for Repository Maager
Method signatures and docstrings:
- def setUp(self): Setups the test case for testing the repo mgr class
- def test_save_and_get_db(self): Test the repository managers functionality for saving and... | bffef6f120ac33b0257b7530616a9bffb323b0a8 | <|skeleton|>
class RepositoryManagerTestCase:
"""Testcase for Repository Maager"""
def setUp(self):
"""Setups the test case for testing the repo mgr class"""
<|body_0|>
def test_save_and_get_db(self):
"""Test the repository managers functionality for saving and reading back the dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepositoryManagerTestCase:
"""Testcase for Repository Maager"""
def setUp(self):
"""Setups the test case for testing the repo mgr class"""
utils = Utility()
self.__conf = utils.CONFIG
conns = utils.get_all_plugins(self.__conf.PATH_CONNECTION_MANAGERS)
self.__conn_w... | the_stack_v2_python_sparse | bipy/services/db/repository/objects/testmanager.py | singajeet/bipy | train | 0 |
cf5a9c2ae802eab03e95c07333c1929a45337ad9 | [
"super().__init__()\nself.signal_gate_pad = nn.ConstantPad1d(padding=(kernels - 1, 0), value=0.0)\nself.signal_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size=kernels, stride=1)\nself.gate_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size... | <|body_start_0|>
super().__init__()
self.signal_gate_pad = nn.ConstantPad1d(padding=(kernels - 1, 0), value=0.0)
self.signal_conv = nn.Conv1d(in_channels=residual_channels, out_channels=gate_channels, kernel_size=kernels, stride=1)
self.gate_conv = nn.Conv1d(in_channels=residual_channels... | Блок с гейтом и остаточным соединением. | SubBlock | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях.... | stack_v2_sparse_classes_75kplus_train_000893 | 13,064 | permissive | [
{
"docstring": ":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях. :param residual_channels: Количество каналов на входе и по обходному пути.",
"name": "__init__",
"signature": "def __init__(self, kernels: int, gate... | 2 | stack_v2_sparse_classes_30k_test_001634 | Implement the Python class `SubBlock` described below.
Class description:
Блок с гейтом и остаточным соединением.
Method signatures and docstrings:
- def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None: :param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_chann... | Implement the Python class `SubBlock` described below.
Class description:
Блок с гейтом и остаточным соединением.
Method signatures and docstrings:
- def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None: :param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_chann... | 3a67544fd4c1bce39d67523799b76c9adfd03969 | <|skeleton|>
class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubBlock:
"""Блок с гейтом и остаточным соединением."""
def __init__(self, kernels: int, gate_channels: int, residual_channels: int) -> None:
""":param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях. :param resid... | the_stack_v2_python_sparse | poptimizer/dl/models/wave_net.py | tjlee/poptimizer | train | 0 |
e3b44299dae933bcbd74390072cc3051df2c3d6d | [
"logger.info('user %s successfully changed password', self.request.user.username)\nmessages.success(self.request, _('Your password was changed successfully.'))\nreturn super().form_valid(form)",
"if self.request.user.is_authenticated():\n return self.request.user.profile.email_confirmed\nreturn False"
] | <|body_start_0|>
logger.info('user %s successfully changed password', self.request.user.username)
messages.success(self.request, _('Your password was changed successfully.'))
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
if self.request.user.is_authenticated():
... | PasswordChangeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordChangeView:
def form_valid(self, form):
"""Before redirecting add password changed successfully message."""
<|body_0|>
def test_func(self):
"""Access test: a user can only change their password after their email has been confirmed."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_000894 | 6,106 | no_license | [
{
"docstring": "Before redirecting add password changed successfully message.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Access test: a user can only change their password after their email has been confirmed.",
"name": "test_func",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_041417 | Implement the Python class `PasswordChangeView` described below.
Class description:
Implement the PasswordChangeView class.
Method signatures and docstrings:
- def form_valid(self, form): Before redirecting add password changed successfully message.
- def test_func(self): Access test: a user can only change their pas... | Implement the Python class `PasswordChangeView` described below.
Class description:
Implement the PasswordChangeView class.
Method signatures and docstrings:
- def form_valid(self, form): Before redirecting add password changed successfully message.
- def test_func(self): Access test: a user can only change their pas... | 07d1387e83775bf8bd3d6f97f2a9c5d909e5119f | <|skeleton|>
class PasswordChangeView:
def form_valid(self, form):
"""Before redirecting add password changed successfully message."""
<|body_0|>
def test_func(self):
"""Access test: a user can only change their password after their email has been confirmed."""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordChangeView:
def form_valid(self, form):
"""Before redirecting add password changed successfully message."""
logger.info('user %s successfully changed password', self.request.user.username)
messages.success(self.request, _('Your password was changed successfully.'))
retu... | the_stack_v2_python_sparse | users/views.py | aspigirlcodes/uniqid | train | 2 | |
aa2829f94c5c0c04cf415559a387e4a44fdc2800 | [
"self.create_pre_authenticated_session('abc@163.com')\nself.browser.get(self.live_server_url)\nself.add_list_item('New item 1')\nremove_1 = self.browser.find_element_by_css_selector('button#id_remove_list_item_1')\nself.assertEqual(remove_1.text, '×')\nself.assertTrue(remove_1.get_attribute('disabled'))\nself.add_l... | <|body_start_0|>
self.create_pre_authenticated_session('abc@163.com')
self.browser.get(self.live_server_url)
self.add_list_item('New item 1')
remove_1 = self.browser.find_element_by_css_selector('button#id_remove_list_item_1')
self.assertEqual(remove_1.text, '×')
self.ass... | 删除待办事项测试 | RemoveListItemTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveListItemTest:
"""删除待办事项测试"""
def test_001(self):
"""待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性"""
<|body_0|>
def test_002(self):
"""删除待办事项,并跳转到本页面"""
<|body_1|>
def test_003(self):
"""匿名用户看不到删除按钮"""
<|body_2|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_000895 | 3,418 | no_license | [
{
"docstring": "待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性",
"name": "test_001",
"signature": "def test_001(self)"
},
{
"docstring": "删除待办事项,并跳转到本页面",
"name": "test_002",
"signature": "def test_002(self)"
},
{
"docstring": "匿名用户看不到删除按钮",
"name": "test_003",
"signature": "def... | 3 | null | Implement the Python class `RemoveListItemTest` described below.
Class description:
删除待办事项测试
Method signatures and docstrings:
- def test_001(self): 待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性
- def test_002(self): 删除待办事项,并跳转到本页面
- def test_003(self): 匿名用户看不到删除按钮 | Implement the Python class `RemoveListItemTest` described below.
Class description:
删除待办事项测试
Method signatures and docstrings:
- def test_001(self): 待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性
- def test_002(self): 删除待办事项,并跳转到本页面
- def test_003(self): 匿名用户看不到删除按钮
<|skeleton|>
class RemoveListItemTest:
"""删除待办事项测试"""... | 973b3afb239db5f55cb52897e7a8a241a459349f | <|skeleton|>
class RemoveListItemTest:
"""删除待办事项测试"""
def test_001(self):
"""待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性"""
<|body_0|>
def test_002(self):
"""删除待办事项,并跳转到本页面"""
<|body_1|>
def test_003(self):
"""匿名用户看不到删除按钮"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoveListItemTest:
"""删除待办事项测试"""
def test_001(self):
"""待办事项删除按钮的活性与非活性 第一条待办事项的删除按钮是非活性,其余均是活性"""
self.create_pre_authenticated_session('abc@163.com')
self.browser.get(self.live_server_url)
self.add_list_item('New item 1')
remove_1 = self.browser.find_element_by... | the_stack_v2_python_sparse | functional_tests/test_lists/test_remove_list_item.py | aaluo001/superlists | train | 0 |
f38e29da30463a78190a9a5c456908f1fcb0250a | [
"self.slot = slot\nself.comm = I2C\nself.host = host\nself.i2c_addr = 24\nself.tp00 = Tp00(self.slot, self.comm, self.host)\nself.tp00.start()",
"send_data = []\nsend_data.append({'act': 'r', 'add': self.i2c_addr, 'cmd': 5, 'len': 2})\n_result = self.tp00.send(json.dumps(send_data))\nresult_data = json.loads(_res... | <|body_start_0|>
self.slot = slot
self.comm = I2C
self.host = host
self.i2c_addr = 24
self.tp00 = Tp00(self.slot, self.comm, self.host)
self.tp00.start()
<|end_body_0|>
<|body_start_1|>
send_data = []
send_data.append({'act': 'r', 'add': self.i2c_addr, 'c... | #29 Ambient temperature meter | Tp29 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tp29:
"""#29 Ambient temperature meter"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
<|body_0|>
def get_data(self):
"""値を取得します。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.slot = slot
self.comm = I2C
self.host = ... | stack_v2_sparse_classes_75kplus_train_000896 | 1,782 | permissive | [
{
"docstring": "コンストラクタ",
"name": "__init__",
"signature": "def __init__(self, slot, host=None)"
},
{
"docstring": "値を取得します。",
"name": "get_data",
"signature": "def get_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026455 | Implement the Python class `Tp29` described below.
Class description:
#29 Ambient temperature meter
Method signatures and docstrings:
- def __init__(self, slot, host=None): コンストラクタ
- def get_data(self): 値を取得します。 | Implement the Python class `Tp29` described below.
Class description:
#29 Ambient temperature meter
Method signatures and docstrings:
- def __init__(self, slot, host=None): コンストラクタ
- def get_data(self): 値を取得します。
<|skeleton|>
class Tp29:
"""#29 Ambient temperature meter"""
def __init__(self, slot, host=None)... | 701430da89c45397a63fd522a4f5cf80516f57d0 | <|skeleton|>
class Tp29:
"""#29 Ambient temperature meter"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
<|body_0|>
def get_data(self):
"""値を取得します。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tp29:
"""#29 Ambient temperature meter"""
def __init__(self, slot, host=None):
"""コンストラクタ"""
self.slot = slot
self.comm = I2C
self.host = host
self.i2c_addr = 24
self.tp00 = Tp00(self.slot, self.comm, self.host)
self.tp00.start()
def get_data(s... | the_stack_v2_python_sparse | py/tp29.py | cw-tpdev/node-red-contrib-tibbo-pi-p4 | train | 2 |
ba976825bb37fc7f13bbfbbd3ab46c39317d03ad | [
"super().__init__()\nself.cache_time = {}\nself.access_history = 0",
"if key is not None and item is not None:\n self.cache_time[key] = self.access_history\n self.cache_data[key] = item\n self.access_history += 1\n if len(self.cache_data) > BaseCaching.MAX_ITEMS:\n old_key = min(self.cache_time... | <|body_start_0|>
super().__init__()
self.cache_time = {}
self.access_history = 0
<|end_body_0|>
<|body_start_1|>
if key is not None and item is not None:
self.cache_time[key] = self.access_history
self.cache_data[key] = item
self.access_history += 1
... | Least recently used | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Least recently used"""
def __init__(self):
"""Initialize"""
<|body_0|>
def put(self, key: str, item: str):
"""Add an item in the cache"""
<|body_1|>
def get(self, key: str):
"""Get an item by key"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_000897 | 1,189 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add an item in the cache",
"name": "put",
"signature": "def put(self, key: str, item: str)"
},
{
"docstring": "Get an item by key",
"name": "get",
"signature": "def get(s... | 3 | stack_v2_sparse_classes_30k_train_037091 | Implement the Python class `LRUCache` described below.
Class description:
Least recently used
Method signatures and docstrings:
- def __init__(self): Initialize
- def put(self, key: str, item: str): Add an item in the cache
- def get(self, key: str): Get an item by key | Implement the Python class `LRUCache` described below.
Class description:
Least recently used
Method signatures and docstrings:
- def __init__(self): Initialize
- def put(self, key: str, item: str): Add an item in the cache
- def get(self, key: str): Get an item by key
<|skeleton|>
class LRUCache:
"""Least recen... | 744e6cb3bb67b2caa30f967708243b5474046961 | <|skeleton|>
class LRUCache:
"""Least recently used"""
def __init__(self):
"""Initialize"""
<|body_0|>
def put(self, key: str, item: str):
"""Add an item in the cache"""
<|body_1|>
def get(self, key: str):
"""Get an item by key"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
"""Least recently used"""
def __init__(self):
"""Initialize"""
super().__init__()
self.cache_time = {}
self.access_history = 0
def put(self, key: str, item: str):
"""Add an item in the cache"""
if key is not None and item is not None:
... | the_stack_v2_python_sparse | 0x03-caching/3-lru_cache.py | emna7/holbertonschool-web_back_end | train | 1 |
4fae784bbf591f2bb30e5a95df40d3f8b4c51ec7 | [
"self.points, self.labels = (None, None)\nif points_path:\n self.load_points(points_path)\nif labels_path:\n self.load_labels(labels_path)",
"self.points = LidarPointCloud.from_file(path).points.T\nif self.labels is not None:\n assert len(self.points) == len(self.labels), 'Error: There are {} points in t... | <|body_start_0|>
self.points, self.labels = (None, None)
if points_path:
self.load_points(points_path)
if labels_path:
self.load_labels(labels_path)
<|end_body_0|>
<|body_start_1|>
self.points = LidarPointCloud.from_file(path).points.T
if self.labels is n... | Class for a point cloud. | LidarSegPointCloud | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LidarSegPointCloud:
"""Class for a point cloud."""
def __init__(self, points_path: str=None, labels_path: str=None):
"""Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and intensity of the points in the point cloud. :param label... | stack_v2_sparse_classes_75kplus_train_000898 | 13,683 | permissive | [
{
"docstring": "Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and intensity of the points in the point cloud. :param labels_path: Path to the bin file containing the labels of the points in the point cloud.",
"name": "__init__",
"signature": "def... | 3 | null | Implement the Python class `LidarSegPointCloud` described below.
Class description:
Class for a point cloud.
Method signatures and docstrings:
- def __init__(self, points_path: str=None, labels_path: str=None): Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and... | Implement the Python class `LidarSegPointCloud` described below.
Class description:
Class for a point cloud.
Method signatures and docstrings:
- def __init__(self, points_path: str=None, labels_path: str=None): Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and... | f308a7e2c90da6d061bed92489c0cd3f0b57a1e1 | <|skeleton|>
class LidarSegPointCloud:
"""Class for a point cloud."""
def __init__(self, points_path: str=None, labels_path: str=None):
"""Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and intensity of the points in the point cloud. :param label... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LidarSegPointCloud:
"""Class for a point cloud."""
def __init__(self, points_path: str=None, labels_path: str=None):
"""Initialize a LidarSegPointCloud object. :param points_path: Path to the bin file containing the x, y, z and intensity of the points in the point cloud. :param labels_path: Path ... | the_stack_v2_python_sparse | dataset_convert/laserscan_nuscenes.py | ika-rwth-aachen/PCLSegmentation | train | 18 |
bc08ddc1b4c39cbb9b397273b41c3c855297cab3 | [
"silhouette_avgs = []\nfor n_clusters in tqdm(range_n_clusters):\n model = KMeans(n_clusters=n_clusters, n_init=20)\n cluster_labels = model.fit_predict(X)\n silhouette_avg = silhouette_score(X, cluster_labels)\n silhouette_avgs.append(silhouette_avg)\nplt.figure(figsize=(8, 6))\nplt.plot(range_n_cluste... | <|body_start_0|>
silhouette_avgs = []
for n_clusters in tqdm(range_n_clusters):
model = KMeans(n_clusters=n_clusters, n_init=20)
cluster_labels = model.fit_predict(X)
silhouette_avg = silhouette_score(X, cluster_labels)
silhouette_avgs.append(silhouette_av... | ClusteringUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusteringUtil:
def plot_avg_silhouette_score(X, range_n_clusters):
"""plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature matrix range_n_clusters : np.ndarray a range of values for n_clusters Returns -------"""
<|bod... | stack_v2_sparse_classes_75kplus_train_000899 | 2,029 | no_license | [
{
"docstring": "plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature matrix range_n_clusters : np.ndarray a range of values for n_clusters Returns -------",
"name": "plot_avg_silhouette_score",
"signature": "def plot_avg_silhouette_score(X, r... | 2 | stack_v2_sparse_classes_30k_train_054250 | Implement the Python class `ClusteringUtil` described below.
Class description:
Implement the ClusteringUtil class.
Method signatures and docstrings:
- def plot_avg_silhouette_score(X, range_n_clusters): plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature... | Implement the Python class `ClusteringUtil` described below.
Class description:
Implement the ClusteringUtil class.
Method signatures and docstrings:
- def plot_avg_silhouette_score(X, range_n_clusters): plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature... | 73eccca76614f2e7fbf8738f1142fe2eb05cb4c7 | <|skeleton|>
class ClusteringUtil:
def plot_avg_silhouette_score(X, range_n_clusters):
"""plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature matrix range_n_clusters : np.ndarray a range of values for n_clusters Returns -------"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusteringUtil:
def plot_avg_silhouette_score(X, range_n_clusters):
"""plot average silhouette score against a range of values of n_clusters Parameters ---------- X : np.ndarray feature matrix range_n_clusters : np.ndarray a range of values for n_clusters Returns -------"""
silhouette_avgs = [... | the_stack_v2_python_sparse | utility/clustering_util.py | heming611/DataScienceLibrary | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.