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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c8967e7f516cff8ebbaa2d30a4445103cdadc49e | [
"url = 'http://docs.python.org/%.1f/objects.inv'\nfor v in [2.6, 3.0, 3.1]:\n request = scrapy.Request(url % v, callback=self._parse_old_sphinx)\n request.meta['version'] = str(v)\n yield request\nfor v in [2.7, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8]:\n request = scrapy.Request(url % v, callback=self._parse... | <|body_start_0|>
url = 'http://docs.python.org/%.1f/objects.inv'
for v in [2.6, 3.0, 3.1]:
request = scrapy.Request(url % v, callback=self._parse_old_sphinx)
request.meta['version'] = str(v)
yield request
for v in [2.7, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8]:
... | Spider for scraping the Python standard libraries. | PythonStdlibSpider | [
"LicenseRef-scancode-dco-1.1",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonStdlibSpider:
"""Spider for scraping the Python standard libraries."""
def start_requests(self):
"""Start making requests."""
<|body_0|>
def _parse_old_sphinx(self, response):
"""Parse the response for old sphinx docs."""
<|body_1|>
def _parse_... | stack_v2_sparse_classes_75kplus_train_002000 | 1,874 | permissive | [
{
"docstring": "Start making requests.",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "Parse the response for old sphinx docs.",
"name": "_parse_old_sphinx",
"signature": "def _parse_old_sphinx(self, response)"
},
{
"docstring": "Parse the r... | 3 | null | Implement the Python class `PythonStdlibSpider` described below.
Class description:
Spider for scraping the Python standard libraries.
Method signatures and docstrings:
- def start_requests(self): Start making requests.
- def _parse_old_sphinx(self, response): Parse the response for old sphinx docs.
- def _parse_new_... | Implement the Python class `PythonStdlibSpider` described below.
Class description:
Spider for scraping the Python standard libraries.
Method signatures and docstrings:
- def start_requests(self): Start making requests.
- def _parse_old_sphinx(self, response): Parse the response for old sphinx docs.
- def _parse_new_... | c9b123ddae7095ba83a5429cc741ce6740dc6b14 | <|skeleton|>
class PythonStdlibSpider:
"""Spider for scraping the Python standard libraries."""
def start_requests(self):
"""Start making requests."""
<|body_0|>
def _parse_old_sphinx(self, response):
"""Parse the response for old sphinx docs."""
<|body_1|>
def _parse_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PythonStdlibSpider:
"""Spider for scraping the Python standard libraries."""
def start_requests(self):
"""Start making requests."""
url = 'http://docs.python.org/%.1f/objects.inv'
for v in [2.6, 3.0, 3.1]:
request = scrapy.Request(url % v, callback=self._parse_old_sphi... | the_stack_v2_python_sparse | sourced/ml/mining/spiders/python_stdlib.py | neomatrix369/ml-mining | train | 0 |
4fdabc9f36e23d2f079c356b0ac7fd8af257383e | [
"data = self.get_json()\ntry:\n data['next_call'] = str(arrow.get(data.get('next_call')).datetime.replace(tzinfo=None))\nexcept arrow.ParserError:\n return self.error(f\"Invalid input for parameter next_call:{data.get('next_call')}\")\nif 'method' in data:\n data['method'] = data['method'].upper()\n if ... | <|body_start_0|>
data = self.get_json()
try:
data['next_call'] = str(arrow.get(data.get('next_call')).datetime.replace(tzinfo=None))
except arrow.ParserError:
return self.error(f"Invalid input for parameter next_call:{data.get('next_call')}")
if 'method' in data:
... | Handler for recurring APIs. | RecurringAPIHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: ... | stack_v2_sparse_classes_75kplus_train_002001 | 7,029 | permissive | [
{
"docstring": "--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: type: string description: HTTP method of the API call. next_call: type: datetime descr... | 3 | stack_v2_sparse_classes_30k_train_008784 | Implement the Python class `RecurringAPIHandler` described below.
Class description:
Handler for recurring APIs.
Method signatures and docstrings:
- def post(self): --- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: typ... | Implement the Python class `RecurringAPIHandler` described below.
Class description:
Handler for recurring APIs.
Method signatures and docstrings:
- def post(self): --- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: typ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: type: string ... | the_stack_v2_python_sparse | skyportal/handlers/api/recurring_api.py | skyportal/skyportal | train | 80 |
1873e840c22c5678876bad7ad8f4cce71d8de4fd | [
"try:\n result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body))\n return_data = {'status': '200', 'result': str(result)}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(retur... | <|body_start_0|>
try:
result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body))
return_data = {'status': '200', 'result': str(result)}
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '400', ... | 1. POST : 2. GET : 3. PUT : 4. DELETE : | CommonJobInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonJobInfo:
"""1. POST : 2. GET : 3. PUT : 4. DELETE :"""
def post(self, request, nnid):
"""set the time on the job :param request: :return:"""
<|body_0|>
def get(self, request):
"""get all job list :param request: :return:"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_75kplus_train_002002 | 2,335 | no_license | [
{
"docstring": "set the time on the job :param request: :return:",
"name": "post",
"signature": "def post(self, request, nnid)"
},
{
"docstring": "get all job list :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "set the time on t... | 4 | stack_v2_sparse_classes_30k_train_041302 | Implement the Python class `CommonJobInfo` described below.
Class description:
1. POST : 2. GET : 3. PUT : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, nnid): set the time on the job :param request: :return:
- def get(self, request): get all job list :param request: :return:
- def put(self,... | Implement the Python class `CommonJobInfo` described below.
Class description:
1. POST : 2. GET : 3. PUT : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, nnid): set the time on the job :param request: :return:
- def get(self, request): get all job list :param request: :return:
- def put(self,... | 17216fd58619b56b6a397178d327687c274c238c | <|skeleton|>
class CommonJobInfo:
"""1. POST : 2. GET : 3. PUT : 4. DELETE :"""
def post(self, request, nnid):
"""set the time on the job :param request: :return:"""
<|body_0|>
def get(self, request):
"""get all job list :param request: :return:"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonJobInfo:
"""1. POST : 2. GET : 3. PUT : 4. DELETE :"""
def post(self, request, nnid):
"""set the time on the job :param request: :return:"""
try:
result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body))
return_data = {'status': '200'... | the_stack_v2_python_sparse | tfmsarest/views/common_job.py | TensorMSA/tensormsa_server_old | train | 0 |
064f89af3b43e1594d1d91caae4a0c522b2623d7 | [
"responses = await super()._get_source_responses(*urls)\nif urls[0].endswith('.zip'):\n unzipped_responses = await asyncio.gather(*[self.__unzip(response) for response in responses])\n responses[:] = list(itertools.chain(*unzipped_responses))\nreturn responses",
"headers = super()._headers()\nif (token := c... | <|body_start_0|>
responses = await super()._get_source_responses(*urls)
if urls[0].endswith('.zip'):
unzipped_responses = await asyncio.gather(*[self.__unzip(response) for response in responses])
responses[:] = list(itertools.chain(*unzipped_responses))
return responses
<... | Base class for source collectors that retrieve files. | FileSourceCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSourceCollector:
"""Base class for source collectors that retrieve files."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to unzip any zipped responses."""
<|body_0|>
def _headers(self) -> dict[str, str]:
"""Extend to add a ... | stack_v2_sparse_classes_75kplus_train_002003 | 3,532 | permissive | [
{
"docstring": "Extend to unzip any zipped responses.",
"name": "_get_source_responses",
"signature": "async def _get_source_responses(self, *urls: URL) -> SourceResponses"
},
{
"docstring": "Extend to add a private token to the headers, if present in the parameters.",
"name": "_headers",
... | 3 | stack_v2_sparse_classes_30k_train_015546 | Implement the Python class `FileSourceCollector` described below.
Class description:
Base class for source collectors that retrieve files.
Method signatures and docstrings:
- async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to unzip any zipped responses.
- def _headers(self) -> dict[str, s... | Implement the Python class `FileSourceCollector` described below.
Class description:
Base class for source collectors that retrieve files.
Method signatures and docstrings:
- async def _get_source_responses(self, *urls: URL) -> SourceResponses: Extend to unzip any zipped responses.
- def _headers(self) -> dict[str, s... | 602b6970e5d9088cb89cc6d488337349e54e1c9a | <|skeleton|>
class FileSourceCollector:
"""Base class for source collectors that retrieve files."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to unzip any zipped responses."""
<|body_0|>
def _headers(self) -> dict[str, str]:
"""Extend to add a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSourceCollector:
"""Base class for source collectors that retrieve files."""
async def _get_source_responses(self, *urls: URL) -> SourceResponses:
"""Extend to unzip any zipped responses."""
responses = await super()._get_source_responses(*urls)
if urls[0].endswith('.zip'):
... | the_stack_v2_python_sparse | components/collector/src/base_collectors/file_source_collector.py | Erik-Stel/quality-time | train | 0 |
69e0809db10d716ca3c684a81a0be43bb28d5e11 | [
"if id:\n self.id = id\nelse:\n self.id = str(uuid4())\nself.exemplar = exemplar\nself.members = set(members)\nself.members.add(exemplar)\nself.longest_id = None\nself.longest_len = None\nself.shortest_id = None\nself.shortest_len = None\nself.average_size = None\nself.number_of_members = len(self.members)\ns... | <|body_start_0|>
if id:
self.id = id
else:
self.id = str(uuid4())
self.exemplar = exemplar
self.members = set(members)
self.members.add(exemplar)
self.longest_id = None
self.longest_len = None
self.shortest_id = None
self.sh... | A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the examplar. The ID can also be the exemplar name too! :ivar id: A unique ID. If no... | Cluster | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
"""A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the examplar. The ID can also be the exemplar nam... | stack_v2_sparse_classes_75kplus_train_002004 | 2,699 | permissive | [
{
"docstring": "Initiate a cluster of sequences :param id: the unique ID. Can be None to autogenerate one :param exemplar: the exemplar sequence :param members: a list or set of the members of the sequence",
"name": "__init__",
"signature": "def __init__(self, id, exemplar, members)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_042165 | Implement the Python class `Cluster` described below.
Class description:
A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the exampl... | Implement the Python class `Cluster` described below.
Class description:
A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the exampl... | 42575fa93e8a1c53012bbfe292514d95b48fbd9d | <|skeleton|>
class Cluster:
"""A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the examplar. The ID can also be the exemplar nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cluster:
"""A cluster of sequences has an ID that should be unique, an exemplar sequence, and a set of members. For convenience, the exemplar is also guaranteed to be one of the members so that you don't need to search through both the members and the examplar. The ID can also be the exemplar name too! :ivar ... | the_stack_v2_python_sparse | pppf_clusters/cluster.py | linsalrob/PPPF | train | 2 |
0ac317a273dc2bb25504bcec41eff8011345f41e | [
"self.length = [0]\nfor i in range(len(strs)):\n self.length.append(self.length[-1] + len(strs[i]))\nreturn ''.join(strs)",
"result = []\nfor i in range(len(self.length) - 1):\n result.append(s[self.length[i]:self.length[i + 1]])\nreturn result"
] | <|body_start_0|>
self.length = [0]
for i in range(len(strs)):
self.length.append(self.length[-1] + len(strs[i]))
return ''.join(strs)
<|end_body_0|>
<|body_start_1|>
result = []
for i in range(len(self.length) - 1):
result.append(s[self.length[i]:self.len... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_002005 | 747 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_008231 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 08500c39e14f3bf140db82a3dd2df4ca18705845 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
self.length = [0]
for i in range(len(strs)):
self.length.append(self.length[-1] + len(strs[i]))
return ''.join(strs)
def decode(self, s):
... | the_stack_v2_python_sparse | python/271_encode-and-decode-strings/encodeAndDecodeStrings.py | kfrancischen/leetcode | train | 2 | |
9b2b11a0bf6ae3faf6bbc3c36d1114a4ebd0bb08 | [
"self.owner = kargs['owner']\ndel kargs['owner']\nwindow_title = kargs.get('window_title')\ndel kargs['window_title']\nsuper().__init__(*args, **kargs)\nif window_title:\n self.setWindowTitle(window_title)",
"widget = self.findChild(NestedSplitter)\nother_top = self.owner.top()\ncount = widget.count()\nall_ok ... | <|body_start_0|>
self.owner = kargs['owner']
del kargs['owner']
window_title = kargs.get('window_title')
del kargs['window_title']
super().__init__(*args, **kargs)
if window_title:
self.setWindowTitle(window_title)
<|end_body_0|>
<|body_start_1|>
widg... | A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the top-level widget/window, because it assumes it can wrap itself in another NestedSplitter ... | NestedSplitterTopLevel | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedSplitterTopLevel:
"""A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the top-level widget/window, because it ass... | stack_v2_sparse_classes_75kplus_train_002006 | 49,175 | permissive | [
{
"docstring": "Init. taking note of the FreeLayoutController which owns this",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "A top-level NestedSplitter window has been closed, check all the panes for widgets which must be preserved, and move any found ... | 2 | stack_v2_sparse_classes_30k_train_009030 | Implement the Python class `NestedSplitterTopLevel` described below.
Class description:
A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the ... | Implement the Python class `NestedSplitterTopLevel` described below.
Class description:
A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the ... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class NestedSplitterTopLevel:
"""A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the top-level widget/window, because it ass... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NestedSplitterTopLevel:
"""A QWidget to wrap a NestedSplitter to allow it to live in a top level window and handle close events properly. These windows are opened by the splitter handle context-menu item 'Open Window'. The NestedSplitter itself can't be the top-level widget/window, because it assumes it can w... | the_stack_v2_python_sparse | leo/plugins/nested_splitter.py | leo-editor/leo-editor | train | 1,671 |
826e188de2f31c76a0e42ff17987f11a8416fd5f | [
"super(ThreadedXMLRPCServer, self).__init__(callback)\nself._rpc_thread = None\nself._xmlrpc_server = None",
"if self._xmlrpc_server:\n self._xmlrpc_server.shutdown()\n self._xmlrpc_server.server_close()\n self._xmlrpc_server = None",
"try:\n self._xmlrpc_server = SimpleXMLRPCServer.SimpleXMLRPCServ... | <|body_start_0|>
super(ThreadedXMLRPCServer, self).__init__(callback)
self._rpc_thread = None
self._xmlrpc_server = None
<|end_body_0|>
<|body_start_1|>
if self._xmlrpc_server:
self._xmlrpc_server.shutdown()
self._xmlrpc_server.server_close()
self._xm... | Threaded XML RPC server. | ThreadedXMLRPCServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadedXMLRPCServer:
"""Threaded XML RPC server."""
def __init__(self, callback):
"""Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request."""
<|body_0|>
def _Close(self):
"""Closes the RPC communicati... | stack_v2_sparse_classes_75kplus_train_002007 | 4,293 | permissive | [
{
"docstring": "Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.",
"name": "__init__",
"signature": "def __init__(self, callback)"
},
{
"docstring": "Closes the RPC communication channel for clients.",
"name": "_Close",
"... | 5 | null | Implement the Python class `ThreadedXMLRPCServer` described below.
Class description:
Threaded XML RPC server.
Method signatures and docstrings:
- def __init__(self, callback): Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.
- def _Close(self): Close... | Implement the Python class `ThreadedXMLRPCServer` described below.
Class description:
Threaded XML RPC server.
Method signatures and docstrings:
- def __init__(self, callback): Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.
- def _Close(self): Close... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ThreadedXMLRPCServer:
"""Threaded XML RPC server."""
def __init__(self, callback):
"""Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request."""
<|body_0|>
def _Close(self):
"""Closes the RPC communicati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadedXMLRPCServer:
"""Threaded XML RPC server."""
def __init__(self, callback):
"""Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request."""
super(ThreadedXMLRPCServer, self).__init__(callback)
self._rpc_thread = None... | the_stack_v2_python_sparse | plaso/multi_process/plaso_xmlrpc.py | log2timeline/plaso | train | 1,506 |
970ae9314d53218234dcd43083e38c2b3edd2237 | [
"add_furniture('rented_items_test.csv', 'Test Miles', 'LR04', 'Leather Sofa', 25)\nadd_furniture('rented_items_test.csv', 'Test Data', 'KT78', 'Kitchen Table', 10)\nadd_furniture('rented_items_test.csv', 'Test Gonzales', 'BR02', 'Queen Mattress', 17)\nwith open('rented_items_test.csv', 'r') as inv_file:\n csv_da... | <|body_start_0|>
add_furniture('rented_items_test.csv', 'Test Miles', 'LR04', 'Leather Sofa', 25)
add_furniture('rented_items_test.csv', 'Test Data', 'KT78', 'Kitchen Table', 10)
add_furniture('rented_items_test.csv', 'Test Gonzales', 'BR02', 'Queen Mattress', 17)
with open('rented_items... | Class to test inventory module. | TestIventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""test add furniture"""
<|body_0|>
def test_single_customer(self):
"""test coverage in single_customer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
add_furnitu... | stack_v2_sparse_classes_75kplus_train_002008 | 1,361 | no_license | [
{
"docstring": "test add furniture",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "test coverage in single_customer",
"name": "test_single_customer",
"signature": "def test_single_customer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022883 | Implement the Python class `TestIventory` described below.
Class description:
Class to test inventory module.
Method signatures and docstrings:
- def test_add_furniture(self): test add furniture
- def test_single_customer(self): test coverage in single_customer | Implement the Python class `TestIventory` described below.
Class description:
Class to test inventory module.
Method signatures and docstrings:
- def test_add_furniture(self): test add furniture
- def test_single_customer(self): test coverage in single_customer
<|skeleton|>
class TestIventory:
"""Class to test i... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""test add furniture"""
<|body_0|>
def test_single_customer(self):
"""test coverage in single_customer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""test add furniture"""
add_furniture('rented_items_test.csv', 'Test Miles', 'LR04', 'Leather Sofa', 25)
add_furniture('rented_items_test.csv', 'Test Data', 'KT78', 'Kitchen Table', 10)
add_... | the_stack_v2_python_sparse | students/ganyoa/lessons/lesson08/assignment/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
8864d787ac7f07affc5a8a3c4d1380681d1c182f | [
"self.date = None\nself.start_serial_time = None\nself.end_serial_time = None\nself.transect_duration_sec = None\nself.ens_duration_sec = None",
"self.date = date_in\nself.start_serial_time = start_in\nself.end_serial_time = end_in\nself.transect_duration_sec = float(end_in - start_in)\nself.ens_duration_sec = en... | <|body_start_0|>
self.date = None
self.start_serial_time = None
self.end_serial_time = None
self.transect_duration_sec = None
self.ens_duration_sec = None
<|end_body_0|>
<|body_start_1|>
self.date = date_in
self.start_serial_time = start_in
self.end_seria... | This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time: float Python serial time for end of transect (seconds since 1/1/1970), tim... | DateTime | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateTime:
"""This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time: float Python serial time for end of tr... | stack_v2_sparse_classes_75kplus_train_002009 | 3,086 | permissive | [
{
"docstring": "Initialize class and instance variables.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Populate data in object. Parameters ---------- date_in: str Measurement date as mm/dd/yyyy start_in: float Python serial time for start of transect. end_in: float P... | 3 | stack_v2_sparse_classes_30k_train_002945 | Implement the Python class `DateTime` described below.
Class description:
This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time:... | Implement the Python class `DateTime` described below.
Class description:
This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time:... | d82e18bcd8183c16ed2a9f57639933fac133624b | <|skeleton|>
class DateTime:
"""This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time: float Python serial time for end of tr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DateTime:
"""This stores the date and time data in Python compatible format. Attributes ---------- date: str Measurement date as mm/dd/yyyy start_serial_time: float Python serial time for start of transect (seconds since 1/1/1970), timestamp end_serial_time: float Python serial time for end of transect (secon... | the_stack_v2_python_sparse | Classes/DateTime.py | ricorx7/QRevPy | train | 0 |
1cb762b8ed46c2768e80a8d82a8129a7d17cebe5 | [
"instance.declined_motive = validated_data['declined_motive']\ninstance.status = 3\ninstance.save()\nreturn instance",
"display_name = obj.specialist.first_name + ' ' + obj.specialist.last_name\nif obj.specialist.nick is not None:\n if len(obj.specialist.nick) > 0:\n display_name = obj.specialist.nick\n... | <|body_start_0|>
instance.declined_motive = validated_data['declined_motive']
instance.status = 3
instance.save()
return instance
<|end_body_0|>
<|body_start_1|>
display_name = obj.specialist.first_name + ' ' + obj.specialist.last_name
if obj.specialist.nick is not None:... | Aceptar match . | MatchDeclineSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchDeclineSerializer:
"""Aceptar match ."""
def update(self, instance, validated_data):
"""Redefinir update."""
<|body_0|>
def to_representation(self, obj):
"""to Representacion."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
instance.decline... | stack_v2_sparse_classes_75kplus_train_002010 | 10,249 | no_license | [
{
"docstring": "Redefinir update.",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "to Representacion.",
"name": "to_representation",
"signature": "def to_representation(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027550 | Implement the Python class `MatchDeclineSerializer` described below.
Class description:
Aceptar match .
Method signatures and docstrings:
- def update(self, instance, validated_data): Redefinir update.
- def to_representation(self, obj): to Representacion. | Implement the Python class `MatchDeclineSerializer` described below.
Class description:
Aceptar match .
Method signatures and docstrings:
- def update(self, instance, validated_data): Redefinir update.
- def to_representation(self, obj): to Representacion.
<|skeleton|>
class MatchDeclineSerializer:
"""Aceptar ma... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class MatchDeclineSerializer:
"""Aceptar match ."""
def update(self, instance, validated_data):
"""Redefinir update."""
<|body_0|>
def to_representation(self, obj):
"""to Representacion."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchDeclineSerializer:
"""Aceptar match ."""
def update(self, instance, validated_data):
"""Redefinir update."""
instance.declined_motive = validated_data['declined_motive']
instance.status = 3
instance.save()
return instance
def to_representation(self, obj):... | the_stack_v2_python_sparse | api/serializers/match.py | darwinv/api-chat-lnk | train | 0 |
bc2e459c87ebeb9c5af2917fbdef87d866298164 | [
"tasks = []\nsearch_tasks = self.filter(user=user)\nfor search_task in search_tasks:\n try:\n full_task = TaskState.objects.get(task_id=search_task.task)\n tasks.append(full_task)\n except TaskState.DoesNotExist:\n pass\ntasks.sort(key=lambda x: x.tstamp, reverse=True)\nreturn tasks",
"... | <|body_start_0|>
tasks = []
search_tasks = self.filter(user=user)
for search_task in search_tasks:
try:
full_task = TaskState.objects.get(task_id=search_task.task)
tasks.append(full_task)
except TaskState.DoesNotExist:
pass
... | Helper class for different formats of the tasks of the user | TaskManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskManager:
"""Helper class for different formats of the tasks of the user"""
def get_tasks_of_user(self, user):
"""method returns all SearchTasks of the user in the database"""
<|body_0|>
def get_task_of_user_in_string_format(self, user):
"""method returns all ... | stack_v2_sparse_classes_75kplus_train_002011 | 7,514 | no_license | [
{
"docstring": "method returns all SearchTasks of the user in the database",
"name": "get_tasks_of_user",
"signature": "def get_tasks_of_user(self, user)"
},
{
"docstring": "method returns all SearchTasks of the user in string format",
"name": "get_task_of_user_in_string_format",
"signat... | 4 | null | Implement the Python class `TaskManager` described below.
Class description:
Helper class for different formats of the tasks of the user
Method signatures and docstrings:
- def get_tasks_of_user(self, user): method returns all SearchTasks of the user in the database
- def get_task_of_user_in_string_format(self, user)... | Implement the Python class `TaskManager` described below.
Class description:
Helper class for different formats of the tasks of the user
Method signatures and docstrings:
- def get_tasks_of_user(self, user): method returns all SearchTasks of the user in the database
- def get_task_of_user_in_string_format(self, user)... | 35eda5c0a871afdb63799677b2faf1cdcbf93249 | <|skeleton|>
class TaskManager:
"""Helper class for different formats of the tasks of the user"""
def get_tasks_of_user(self, user):
"""method returns all SearchTasks of the user in the database"""
<|body_0|>
def get_task_of_user_in_string_format(self, user):
"""method returns all ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskManager:
"""Helper class for different formats of the tasks of the user"""
def get_tasks_of_user(self, user):
"""method returns all SearchTasks of the user in the database"""
tasks = []
search_tasks = self.filter(user=user)
for search_task in search_tasks:
... | the_stack_v2_python_sparse | twitter/models.py | svensmets/datacollection | train | 0 |
ad72a0f5c3f8572ec0cc18439971861f7b5daeb8 | [
"VapiInterface.__init__(self, config, _ConsumerPrincipalsStub)\nself._VAPI_OPERATION_IDS = {}\nself._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})\nself._VAPI_OPERATION_IDS.update({'delete_task': 'delete$task'})\nself._VAPI_OPERATION_IDS.update({'get_task': 'get$task'})\nself._VAPI_OPERATION_IDS.update(... | <|body_start_0|>
VapiInterface.__init__(self, config, _ConsumerPrincipalsStub)
self._VAPI_OPERATION_IDS = {}
self._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})
self._VAPI_OPERATION_IDS.update({'delete_task': 'delete$task'})
self._VAPI_OPERATION_IDS.update({'get_task'... | The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0. | ConsumerPrincipals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerPrincipals:
"""The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vm... | stack_v2_sparse_classes_75kplus_train_002012 | 32,011 | permissive | [
{
"docstring": ":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Creates a profile with the specified connection information on all ... | 5 | stack_v2_sparse_classes_30k_train_007258 | Implement the Python class `ConsumerPrincipals` described below.
Class description:
The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0.
Method signatures and docstring... | Implement the Python class `ConsumerPrincipals` described below.
Class description:
The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0.
Method signatures and docstring... | c07e1be98615201139b26c28db3aa584c4254b66 | <|skeleton|>
class ConsumerPrincipals:
"""The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsumerPrincipals:
"""The ``ConsumerPrincipals`` class configures the token policies and STS trust necessary for the workload vCenter to query the trusted services for their status. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.bin... | the_stack_v2_python_sparse | com/vmware/vcenter/trusted_infrastructure/trust_authority_clusters_client.py | adammillerio/vsphere-automation-sdk-python | train | 0 |
51eaeef4bdb0a20dcfd86225378376efe7a2a3fe | [
"self.logging = logging\nself.keywords = keywords\nself.name = name\nself.id = task_id\nif operator in ['or', 'and']:\n self.operator = operator\nelif operator == []:\n self.operator = 'or'\nelse:\n self.logging.print('Operator: ' + operator + ' unknown')\n self.logging.print('Using operator:or')\n s... | <|body_start_0|>
self.logging = logging
self.keywords = keywords
self.name = name
self.id = task_id
if operator in ['or', 'and']:
self.operator = operator
elif operator == []:
self.operator = 'or'
else:
self.logging.print('Opera... | LoggingTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingTask:
def __init__(self, logging, task_id, keywords, operator, name=None):
"""Mangages one logging task :param logging: reference to the logging module :param task_id: id :param keywords: keywords, the logs are scanned for :param operator: how multilple keywords combined to evalua... | stack_v2_sparse_classes_75kplus_train_002013 | 2,376 | permissive | [
{
"docstring": "Mangages one logging task :param logging: reference to the logging module :param task_id: id :param keywords: keywords, the logs are scanned for :param operator: how multilple keywords combined to evaluate the logs. Possible operators:\"or\",\"and\" :param name: name of the file the logs are pri... | 4 | null | Implement the Python class `LoggingTask` described below.
Class description:
Implement the LoggingTask class.
Method signatures and docstrings:
- def __init__(self, logging, task_id, keywords, operator, name=None): Mangages one logging task :param logging: reference to the logging module :param task_id: id :param key... | Implement the Python class `LoggingTask` described below.
Class description:
Implement the LoggingTask class.
Method signatures and docstrings:
- def __init__(self, logging, task_id, keywords, operator, name=None): Mangages one logging task :param logging: reference to the logging module :param task_id: id :param key... | 9ff7bd1ab9609276fa4008d0180fdeb500fb9484 | <|skeleton|>
class LoggingTask:
def __init__(self, logging, task_id, keywords, operator, name=None):
"""Mangages one logging task :param logging: reference to the logging module :param task_id: id :param keywords: keywords, the logs are scanned for :param operator: how multilple keywords combined to evalua... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoggingTask:
def __init__(self, logging, task_id, keywords, operator, name=None):
"""Mangages one logging task :param logging: reference to the logging module :param task_id: id :param keywords: keywords, the logs are scanned for :param operator: how multilple keywords combined to evaluate the logs. P... | the_stack_v2_python_sparse | logging/loggingTask.py | UHH-ISS/honeygrove-console | train | 1 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nproposal = Semester.from_dict(api.payload)\nif proposal is not None:\n 'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objektes.'\n sem = adm.create_semester(proposal.get_id(), proposal.get_name())\n return (sem, 200)\nelse:\n return ('... | <|body_start_0|>
adm = ProjectAdministration()
proposal = Semester.from_dict(api.payload)
if proposal is not None:
'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objektes.'
sem = adm.create_semester(proposal.get_id(), proposal.get_name... | SemesterOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
<|body_0|>
def put(self):
"""Update eines bestimmten Semester-Objektes."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = ProjectAdministration()
proposal = S... | stack_v2_sparse_classes_75kplus_train_002014 | 44,493 | no_license | [
{
"docstring": "Anlegen eines neuen Semester-Objekts",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update eines bestimmten Semester-Objektes.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054291 | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Semester-Objekts
- def put(self): Update eines bestimmten Semester-Objektes. | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Semester-Objekts
- def put(self): Update eines bestimmten Semester-Objektes.
<|skeleton|>
class SemesterOperations:
... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
<|body_0|>
def put(self):
"""Update eines bestimmten Semester-Objektes."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
adm = ProjectAdministration()
proposal = Semester.from_dict(api.payload)
if proposal is not None:
'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objek... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
17f1dd6fd749352f10d5e6c2fd02a1bdceefdb19 | [
"_url_path = '/geocode-reverse'\n_query_builder = Configuration.get_base_uri()\n_query_builder += _url_path\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json'}\n_form_parameters = {'output-case': 'camel', 'latitude': latitude, 'longitude': longitude, 'language-code': languag... | <|body_start_0|>
_url_path = '/geocode-reverse'
_query_builder = Configuration.get_base_uri()
_query_builder += _url_path
_query_url = APIHelper.clean_url(_query_builder)
_headers = {'accept': 'application/json'}
_form_parameters = {'output-case': 'camel', 'latitude': lat... | A Controller to access Endpoints in the neutrino_api API. | Geolocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geolocation:
"""A Controller to access Endpoints in the neutrino_api API."""
def geocode_reverse(self, latitude, longitude, language_code='en', zoom='address'):
"""Does a POST request to /geocode-reverse. Convert a geographic coordinate (latitude and longitude) into a real world addr... | stack_v2_sparse_classes_75kplus_train_002015 | 7,781 | permissive | [
{
"docstring": "Does a POST request to /geocode-reverse. Convert a geographic coordinate (latitude and longitude) into a real world address. See: https://www.neutrinoapi.com/api/geocode-reverse/ Args: latitude (string): The location latitude in decimal degrees format longitude (string): The location longitude i... | 3 | stack_v2_sparse_classes_30k_train_042635 | Implement the Python class `Geolocation` described below.
Class description:
A Controller to access Endpoints in the neutrino_api API.
Method signatures and docstrings:
- def geocode_reverse(self, latitude, longitude, language_code='en', zoom='address'): Does a POST request to /geocode-reverse. Convert a geographic c... | Implement the Python class `Geolocation` described below.
Class description:
A Controller to access Endpoints in the neutrino_api API.
Method signatures and docstrings:
- def geocode_reverse(self, latitude, longitude, language_code='en', zoom='address'): Does a POST request to /geocode-reverse. Convert a geographic c... | cc00933eefef0f40710f606e9fbf2dfb97a4f063 | <|skeleton|>
class Geolocation:
"""A Controller to access Endpoints in the neutrino_api API."""
def geocode_reverse(self, latitude, longitude, language_code='en', zoom='address'):
"""Does a POST request to /geocode-reverse. Convert a geographic coordinate (latitude and longitude) into a real world addr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Geolocation:
"""A Controller to access Endpoints in the neutrino_api API."""
def geocode_reverse(self, latitude, longitude, language_code='en', zoom='address'):
"""Does a POST request to /geocode-reverse. Convert a geographic coordinate (latitude and longitude) into a real world address. See: htt... | the_stack_v2_python_sparse | neutrino_api/controllers/geolocation.py | NeutrinoAPI/NeutrinoAPI-Python | train | 3 |
f086918ec178c3c537664642139a4ab3518bd5aa | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"first = np.sum(X1 ** 2, axis=1).reshape(-1, 1)\nsecond = np.sum(X2 ** 2, axis=1)\nthird = -2 * np.dot(X1, X2.T)\nsqdist = first + second + third\nkernel_1 = self.sigma_f ** 2\nkernel_2 = np.exp(-0.5 / se... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
first = np.sum(X1 ** 2, axis=1).reshape(-1, 1)
second = np.sum(X2 ** 2, axis=1)
third = -2 * np.dot(X1,... | Gaussian Process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Gaussian Process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""* X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the b... | stack_v2_sparse_classes_75kplus_train_002016 | 2,959 | no_license | [
{
"docstring": "* X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_init - t is the number of initial samples * l is the length parameter... | 3 | stack_v2_sparse_classes_30k_train_024242 | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian Process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): * X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.... | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian Process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): * X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class GaussianProcess:
"""Gaussian Process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""* X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcess:
"""Gaussian Process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""* X_init is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function * Y_init is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box func... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
5f2f694c2e1912041c57d3aaaf8ffe52a4b0adff | [
"pointer = TreeNode(None)\nstack = [root]\nwhile stack:\n top = stack.pop()\n if top is None:\n continue\n stack.append(top.right)\n stack.append(top.left)\n pointer.right = top\n pointer.left = None\n pointer = top",
"self.pointer = None\n\ndef traverse(node):\n if node is None:\n ... | <|body_start_0|>
pointer = TreeNode(None)
stack = [root]
while stack:
top = stack.pop()
if top is None:
continue
stack.append(top.right)
stack.append(top.left)
pointer.right = top
pointer.left = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
"""展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_recu(self, root):
"""右-左-根 :param root: :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_002017 | 2,074 | no_license | [
{
"docstring": "展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": "右-左-根 :param root: :return:",
"name": "flatten_recu",
"signature": "def flatt... | 2 | stack_v2_sparse_classes_30k_train_049070 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): 展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten_recu(self, root): 右-左-根... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): 展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten_recu(self, root): 右-左-根... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def flatten(self, root):
"""展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_recu(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 flatten(self, root):
"""展开后的树,每一个节点的右孩子都是先序遍历的下一个节点 :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
pointer = TreeNode(None)
stack = [root]
while stack:
top = stack.pop()
if top is None:
... | the_stack_v2_python_sparse | python/dfs/flatten-bt-linked-list.py | euxuoh/leetcode | train | 0 | |
bf83363435517252a2e42964d33983aa4d143cb9 | [
"super().__init__(**kwargs)\nself._numparticle = numparticle\nself.expscale = expscale\nself.epsilon = epsilon",
"particle = tf.cast(inputs[:, 0], tf.int32)\nparticle_oh = tf.one_hot(particle, self._numparticle, dtype=tf.float32)\nenergy = inputs[:, 1] / 10000000000.0\ntheta = inputs[:, 2] / 90.0\nphi = inputs[:,... | <|body_start_0|>
super().__init__(**kwargs)
self._numparticle = numparticle
self.expscale = expscale
self.epsilon = epsilon
<|end_body_0|>
<|body_start_1|>
particle = tf.cast(inputs[:, 0], tf.int32)
particle_oh = tf.one_hot(particle, self._numparticle, dtype=tf.float32)
... | This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interface. | LabelMerger | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelMerger:
"""This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interface."""
def __init__(self, numparti... | stack_v2_sparse_classes_75kplus_train_002018 | 2,463 | permissive | [
{
"docstring": "Construct a LabelMerger instance. Parameters ---------- numparticle : int, optional Maximum number of particle types that should be generated (used for onehot encoding of particle types). Defaults to 6. expscale : bool, optional Flag to indicate if the model uses exponential scaling of outputs. ... | 2 | stack_v2_sparse_classes_30k_train_037406 | Implement the Python class `LabelMerger` described below.
Class description:
This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interfa... | Implement the Python class `LabelMerger` described below.
Class description:
This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interfa... | 7f0086d2cdec23b49958c5afc0e6d12a08598465 | <|skeleton|>
class LabelMerger:
"""This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interface."""
def __init__(self, numparti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabelMerger:
"""This class is used to bring label data into the right format. It performs onehot encoding of the particle type and logscaling for the energy if exponential scaling is used for the model. This class implements the tf.keras.layers.Layer interface."""
def __init__(self, numparticle=6, expsca... | the_stack_v2_python_sparse | src/models/gan/utils/labelmerger.py | image357/conex-generator | train | 0 |
86b4d576315d9603c2b98d08eb40655ff2e2695b | [
"if type(self.value) is not str:\n raise ValidationError('Validation Error: Secret Custom Setting should be a String')\nif self.value == '' and self.required:\n raise ValidationError('Required.')\nif self.value != '':\n self.value = secrets_signed_unsigned_value(self.name, self.value, self.tethys_app.packa... | <|body_start_0|>
if type(self.value) is not str:
raise ValidationError('Validation Error: Secret Custom Setting should be a String')
if self.value == '' and self.required:
raise ValidationError('Required.')
if self.value != '':
self.value = secrets_signed_unsi... | Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSetting default_name_setting = SecretCustomSettin... | SecretCustomSetting | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSe... | stack_v2_sparse_classes_75kplus_train_002019 | 45,827 | permissive | [
{
"docstring": "Validate prior to saving changes.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Get the value",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049686 | Implement the Python class `SecretCustomSetting` described below.
Class description:
Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys... | Implement the Python class `SecretCustomSetting` described below.
Class description:
Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys... | e9365fa55ec25d7658a75ca7fb0632013374d876 | <|skeleton|>
class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SecretCustomSetting:
"""Used to define a Custom Secret Setting. Attributes: name(str): Unique name used to identify the setting. description(str): Short description of the setting. required(bool): A value will be required if True. **Example:** :: from tethys_sdk.app_settings import SecretCustomSetting default... | the_stack_v2_python_sparse | tethys_apps/models.py | tethysplatform/tethys | train | 95 |
de7c16c9c2cc1b9558e3e93b39c28f11bb1ea3f1 | [
"left, right = (1, len(nums) - 1)\nwhile left <= right:\n mid = (left + right) // 2\n cnt = sum((num <= mid for num in nums))\n if cnt > mid:\n right = mid - 1\n else:\n left = mid + 1\nreturn left",
"slow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n f... | <|body_start_0|>
left, right = (1, len(nums) - 1)
while left <= right:
mid = (left + right) // 2
cnt = sum((num <= mid for num in nums))
if cnt > mid:
right = mid - 1
else:
left = mid + 1
return left
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
"""看做有环链表 :param nums: :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (1, len(nums) - 1)
... | stack_v2_sparse_classes_75kplus_train_002020 | 1,567 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": "看做有环链表 :param nums: :return: int",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000830 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): 看做有环链表 :param nums: :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): 看做有环链表 :param nums: :return: int
<|skeleton|>
class Solution:
def findDup... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
"""看做有环链表 :param nums: :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
left, right = (1, len(nums) - 1)
while left <= right:
mid = (left + right) // 2
cnt = sum((num <= mid for num in nums))
if cnt > mid:
right = mid - 1
... | the_stack_v2_python_sparse | python/bin-search/find-duplicate-number.py | euxuoh/leetcode | train | 0 | |
1fd3fb1b1a0e8eb6c2cd1b009babb13474eb33fc | [
"super(TrafficStreamsBaseClass, self).__init__()\nself.n_tunnels = 1024\nself.p2_geneve_start_vni = 1\nself.p1_src_start_ip = u'10.128.1.0'\nself.p1_dst_start_ip = u'10.0.1.0'\nself.p2_outer_src_ip = u'1.1.1.1'\nself.p2_outer_dst_ip = u'1.1.1.2'\nself.p2_inner_src_start_ip = u'10.0.1.0'\nself.p2_inner_dst_start_ip ... | <|body_start_0|>
super(TrafficStreamsBaseClass, self).__init__()
self.n_tunnels = 1024
self.p2_geneve_start_vni = 1
self.p1_src_start_ip = u'10.128.1.0'
self.p1_dst_start_ip = u'10.0.1.0'
self.p2_outer_src_ip = u'1.1.1.1'
self.p2_outer_dst_ip = u'1.1.1.2'
... | Stream profile. | TrafficStreams | [
"GPL-2.0-only",
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
<|body_0|>
def define_packets(self):
"""Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: P... | stack_v2_sparse_classes_75kplus_train_002021 | 7,809 | permissive | [
{
"docstring": "Initialization and setting of streams' parameters.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: Packets to be sent from the traffic generator. ... | 2 | stack_v2_sparse_classes_30k_train_010510 | Implement the Python class `TrafficStreams` described below.
Class description:
Stream profile.
Method signatures and docstrings:
- def __init__(self): Initialization and setting of streams' parameters.
- def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I... | Implement the Python class `TrafficStreams` described below.
Class description:
Stream profile.
Method signatures and docstrings:
- def __init__(self): Initialization and setting of streams' parameters.
- def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
<|body_0|>
def define_packets(self):
"""Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
super(TrafficStreamsBaseClass, self).__init__()
self.n_tunnels = 1024
self.p2_geneve_start_vni = 1
self.p1_src_start_ip = u'10.128.1.0'
self.p... | the_stack_v2_python_sparse | GPL/traffic_profiles/trex/trex-stl-2n-ethip4-geneve-1024t.py | FDio/csit | train | 28 |
c64def0f7699e1cad3a372b3efada128e44e97ec | [
"self._old_layer = old_layer\nself._new_layer = new_layer\nif filter_fn is None:\n self._filter_fn = lambda s: True\nelse:\n self._filter_fn = filter_fn",
"del meta_state\nshould_change = [self._filter_fn(s) for s in state[self._old_layer]]\nchange_inds = np.argwhere(should_change)[:, 0]\ncount_changed_alre... | <|body_start_0|>
self._old_layer = old_layer
self._new_layer = new_layer
if filter_fn is None:
self._filter_fn = lambda s: True
else:
self._filter_fn = filter_fn
<|end_body_0|>
<|body_start_1|>
del meta_state
should_change = [self._filter_fn(s) fo... | ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color. | ChangeLayer | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeLayer:
"""ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color."""
def __init__(self, old_layer, new_layer, filter_fn=None):
"""Cons... | stack_v2_sparse_classes_75kplus_train_002022 | 1,651 | permissive | [
{
"docstring": "Constructor. Args: old_layer: String. Must be a key in the environment state. Sprites in this layer will be considered for the layer change. new_layer: String. Must be a key in the environment state. Layer to which sprites in old_layer may be moved. filter_fn: Function sprite -> bool. Whether to... | 2 | stack_v2_sparse_classes_30k_train_010094 | Implement the Python class `ChangeLayer` described below.
Class description:
ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.
Method signatures and docstrings:
- def _... | Implement the Python class `ChangeLayer` described below.
Class description:
ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.
Method signatures and docstrings:
- def _... | 3e89e46a5918d59475851f9d4f1558956c110d38 | <|skeleton|>
class ChangeLayer:
"""ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color."""
def __init__(self, old_layer, new_layer, filter_fn=None):
"""Cons... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeLayer:
"""ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color."""
def __init__(self, old_layer, new_layer, filter_fn=None):
"""Constructor. Args... | the_stack_v2_python_sparse | moog/game_rules/change_layer.py | hokysung/moog.github.io | train | 0 |
a97339b2615d2167abc8d3c8c50babaa953a60ca | [
"self.stack = deque([])\nself.stack.append(nestedList)\nself.value = None",
"ret = self.value\nself.value = None\nreturn ret",
"if self.value:\n return True\nstack = self.stack\nwhile stack:\n top = stack.popleft()\n if len(top) == 1:\n if top[0].isInteger():\n self.value = top[0].get... | <|body_start_0|>
self.stack = deque([])
self.stack.append(nestedList)
self.value = None
<|end_body_0|>
<|body_start_1|>
ret = self.value
self.value = None
return ret
<|end_body_1|>
<|body_start_2|>
if self.value:
return True
stack = self.stac... | NestedIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus_train_002023 | 3,825 | permissive | [
{
"docstring": "Initialize your data structure here. :type nestedList: List[NestedInteger]",
"name": "__init__",
"signature": "def __init__(self, nestedList)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"nam... | 3 | stack_v2_sparse_classes_30k_train_003573 | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | 46caaf74aeab8af74861fb5b249eb4169baf8493 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
self.stack = deque([])
self.stack.append(nestedList)
self.value = None
def next(self):
""":rtype: int"""
ret = self.value
... | the_stack_v2_python_sparse | leetcode/Stack/341. Flatten Nested List Iterator.py | yanshengjia/algorithm | train | 69 | |
bc99e417fca7dfa497d470f64e67d27941eb6544 | [
"self.mechanism = mechanism\nself.classifier_factory = classifier_factory\nself.config = config",
"log.debug('Searching best attack for mechanism %s, classifier %s...', type(self.mechanism).__name__, type(self.classifier_factory).__name__)\nclassifier = self._train_classifier(a1, a2)\nwith time_measure('time_dete... | <|body_start_0|>
self.mechanism = mechanism
self.classifier_factory = classifier_factory
self.config = config
<|end_body_0|>
<|body_start_1|>
log.debug('Searching best attack for mechanism %s, classifier %s...', type(self.mechanism).__name__, type(self.classifier_factory).__name__)
... | The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds. | DPSniper | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPSniper:
"""The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds."""
def __init__(self, mechanism: Mechanism, classifier_factory: ClassifierFactory, config: DDConfig):
"""Create an optimizer. Ar... | stack_v2_sparse_classes_75kplus_train_002024 | 5,450 | permissive | [
{
"docstring": "Create an optimizer. Args: mechanism: mechanism to attack classifier_factory: factory creating instances the classifier to be used for the attack config: configuration",
"name": "__init__",
"signature": "def __init__(self, mechanism: Mechanism, classifier_factory: ClassifierFactory, conf... | 5 | null | Implement the Python class `DPSniper` described below.
Class description:
The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds.
Method signatures and docstrings:
- def __init__(self, mechanism: Mechanism, classifier_factory: Clas... | Implement the Python class `DPSniper` described below.
Class description:
The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds.
Method signatures and docstrings:
- def __init__(self, mechanism: Mechanism, classifier_factory: Clas... | ee087b2584ca97d1064154db5dd2bda0bb5a8ceb | <|skeleton|>
class DPSniper:
"""The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds."""
def __init__(self, mechanism: Mechanism, classifier_factory: ClassifierFactory, config: DDConfig):
"""Create an optimizer. Ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DPSniper:
"""The main DP-Sniper algorithm. This optimizer finds an MlAttack for a given input pair by training a classifier and deriving attack thresholds."""
def __init__(self, mechanism: Mechanism, classifier_factory: ClassifierFactory, config: DDConfig):
"""Create an optimizer. Args: mechanism... | the_stack_v2_python_sparse | dpsniper/attack/dpsniper.py | zhangzhizheng/dp-sniper | train | 0 |
749cb62adc0e5f60e11a859c015727f20c46d617 | [
"clf = None\nif not is_categorical:\n clf = neighbors.KNeighborsRegressor(n_neighbors=k)\nelse:\n clf = neighbors.KNeighborsClassifier(n_neighbors=k)\nmissing_idxes = np.where(pd.isnull(X[:, column]))[0]\nif len(missing_idxes) == 0:\n return None\nX_copy = np.delete(X, missing_idxes, 0)\nX_train = np.delet... | <|body_start_0|>
clf = None
if not is_categorical:
clf = neighbors.KNeighborsRegressor(n_neighbors=k)
else:
clf = neighbors.KNeighborsClassifier(n_neighbors=k)
missing_idxes = np.where(pd.isnull(X[:, column]))[0]
if len(missing_idxes) == 0:
ret... | Imputer class. | Imputer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti... | stack_v2_sparse_classes_75kplus_train_002025 | 4,549 | no_license | [
{
"docstring": "Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or categorical feature - Returns: clf: trained k nearest neighbour classifier",
"name": "_... | 4 | stack_v2_sparse_classes_30k_train_038235 | Implement the Python class `Imputer` described below.
Class description:
Imputer class.
Method signatures and docstrings:
- def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares... | Implement the Python class `Imputer` described below.
Class description:
Imputer class.
Method signatures and docstrings:
- def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares... | f940ab166ba57f06288a64ae0b6978c11450a806 | <|skeleton|>
class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or cate... | the_stack_v2_python_sparse | ForML/imputerBybwanglzu.py | JRLi/untitled | train | 0 |
8b99a72899fc813c32451ef2f5897f64c2c35de7 | [
"self.sounds = Sounds(sounds_volume)\nself.animations = Animations()\nself.textures = Textures()\nself.score_label = Color('#FFFFFF')\nself.background = Color('#F2F2F2')",
"self.animations.update()\nself.textures.update()\nself.sounds.update()"
] | <|body_start_0|>
self.sounds = Sounds(sounds_volume)
self.animations = Animations()
self.textures = Textures()
self.score_label = Color('#FFFFFF')
self.background = Color('#F2F2F2')
<|end_body_0|>
<|body_start_1|>
self.animations.update()
self.textures.update()
... | Class that stores all game resources: textures, animated textures, sounds, etc. . | Resources | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""Class that stores all game resources: textures, animated textures, sounds, etc. ."""
def __init__(self, sounds_volume):
"""Initialize Resource object Loads all game resources"""
<|body_0|>
def update(self):
"""Update animations and sounds"""
... | stack_v2_sparse_classes_75kplus_train_002026 | 2,949 | no_license | [
{
"docstring": "Initialize Resource object Loads all game resources",
"name": "__init__",
"signature": "def __init__(self, sounds_volume)"
},
{
"docstring": "Update animations and sounds",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049787 | Implement the Python class `Resources` described below.
Class description:
Class that stores all game resources: textures, animated textures, sounds, etc. .
Method signatures and docstrings:
- def __init__(self, sounds_volume): Initialize Resource object Loads all game resources
- def update(self): Update animations ... | Implement the Python class `Resources` described below.
Class description:
Class that stores all game resources: textures, animated textures, sounds, etc. .
Method signatures and docstrings:
- def __init__(self, sounds_volume): Initialize Resource object Loads all game resources
- def update(self): Update animations ... | 038511ec5e274d82c528e1e1f6e25f6d01dbeba8 | <|skeleton|>
class Resources:
"""Class that stores all game resources: textures, animated textures, sounds, etc. ."""
def __init__(self, sounds_volume):
"""Initialize Resource object Loads all game resources"""
<|body_0|>
def update(self):
"""Update animations and sounds"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resources:
"""Class that stores all game resources: textures, animated textures, sounds, etc. ."""
def __init__(self, sounds_volume):
"""Initialize Resource object Loads all game resources"""
self.sounds = Sounds(sounds_volume)
self.animations = Animations()
self.textures ... | the_stack_v2_python_sparse | src/classes/resources.py | KoroLion/gora_original | train | 1 |
727f70fb22f30954acfd58df6e8a17a5c806acab | [
"if self.action in ['retrieve', 'update', 'partial_update']:\n permission_classes = [permissions.IsOrganizationAdmin]\nelif self.action in ['list']:\n permission_classes = [permissions.UserIsAuthenticated]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes... | <|body_start_0|>
if self.action in ['retrieve', 'update', 'partial_update']:
permission_classes = [permissions.IsOrganizationAdmin]
elif self.action in ['list']:
permission_classes = [permissions.UserIsAuthenticated]
else:
try:
permission_class... | ViewSet for all organization-related interactions. | OrganizationViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002027 | 8,277 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "override get_queryset based on the request... | 2 | stack_v2_sparse_classes_30k_train_027289 | Implement the Python class `OrganizationViewSet` described below.
Class description:
ViewSet for all organization-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the V... | Implement the Python class `OrganizationViewSet` described below.
Class description:
ViewSet for all organization-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the V... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
if self.action in ['retrieve'... | the_stack_v2_python_sparse | src/backend/marsha/core/api/account.py | openfun/marsha | train | 92 |
936cbf39aad3dea586698a13f3f60c2569e98161 | [
"data_interface = current_app.config.data_interface\ntry:\n if action is None:\n if model_run_name is None:\n model_runs = data_interface.read_model_runs()\n if 'status' in request.args.keys():\n data = []\n for model_run in model_runs:\n ... | <|body_start_0|>
data_interface = current_app.config.data_interface
try:
if action is None:
if model_run_name is None:
model_runs = data_interface.read_model_runs()
if 'status' in request.args.keys():
data = []
... | Implement CRUD operations for model_run configuration data | ModelRunAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelRunAPI:
"""Implement CRUD operations for model_run configuration data"""
def get(self, model_run_name=None, action=None):
"""Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name"""
<|body_0|>
def post(self, model_run_name=None, action=None):
... | stack_v2_sparse_classes_75kplus_train_002028 | 15,681 | permissive | [
{
"docstring": "Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name",
"name": "get",
"signature": "def get(self, model_run_name=None, action=None)"
},
{
"docstring": "Create a model_run: - POST /api/v1/model_runs Perform an operation on a model_run - POST /api/v1/model_r... | 4 | stack_v2_sparse_classes_30k_train_007226 | Implement the Python class `ModelRunAPI` described below.
Class description:
Implement CRUD operations for model_run configuration data
Method signatures and docstrings:
- def get(self, model_run_name=None, action=None): Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name
- def post(self, mod... | Implement the Python class `ModelRunAPI` described below.
Class description:
Implement CRUD operations for model_run configuration data
Method signatures and docstrings:
- def get(self, model_run_name=None, action=None): Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name
- def post(self, mod... | 009aabbdb610aab0589aacebfa84c5199da7e6da | <|skeleton|>
class ModelRunAPI:
"""Implement CRUD operations for model_run configuration data"""
def get(self, model_run_name=None, action=None):
"""Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name"""
<|body_0|>
def post(self, model_run_name=None, action=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelRunAPI:
"""Implement CRUD operations for model_run configuration data"""
def get(self, model_run_name=None, action=None):
"""Get model_runs all: GET /api/v1/model_runs/ one: GET /api/vi/model_runs/name"""
data_interface = current_app.config.data_interface
try:
if ... | the_stack_v2_python_sparse | src/smif/http_api/crud.py | nismod/smif | train | 34 |
d68e3bd727fc9e9d1ed7559775c043f6489eeb98 | [
"if not root:\n return None\nqueue = deque()\nresult = [root.val]\nqueue.append(root)\nwhile queue:\n curr = queue.popleft()\n if curr.left:\n queue.append(curr.left)\n result.append(curr.left.val)\n else:\n result.append(curr.left)\n if curr.right:\n queue.append(curr.rig... | <|body_start_0|>
if not root:
return None
queue = deque()
result = [root.val]
queue.append(root)
while queue:
curr = queue.popleft()
if curr.left:
queue.append(curr.left)
result.append(curr.left.val)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002029 | 1,858 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 65f855c72b3d84270c46bd2af86f08593e196472 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return None
queue = deque()
result = [root.val]
queue.append(root)
while queue:
curr = queue.popleft()
if... | the_stack_v2_python_sparse | leetcode/python/Lc297SerializeAndDeserializeBinaryTree.py | jinver/leetcode | train | 0 | |
fe835a5934bee8120d6cd4578a76f714ea060533 | [
"json = dumps(self).encode('latin-1')\njson_size = len(json)\njson_size = VarInt(json_size)\njson_size = bytes(json_size)\npayload = json_size + json\npayload = bytes(self.packet_id) + payload\npayload_size = len(payload)\npayload_size = VarInt(payload_size)\npayload_size = bytes(payload_size)\nreturn payload_size ... | <|body_start_0|>
json = dumps(self).encode('latin-1')
json_size = len(json)
json_size = VarInt(json_size)
json_size = bytes(json_size)
payload = json_size + json
payload = bytes(self.packet_id) + payload
payload_size = len(payload)
payload_size = VarInt(pa... | A server list ping response. | SLPResponse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLPResponse:
"""A server list ping response."""
def __bytes__(self):
"""Returns the respective bytes."""
<|body_0|>
def read(cls, readfunc: Callable) -> SLPResponse:
"""Creates the SLP response from the respective payload."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_002030 | 2,393 | no_license | [
{
"docstring": "Returns the respective bytes.",
"name": "__bytes__",
"signature": "def __bytes__(self)"
},
{
"docstring": "Creates the SLP response from the respective payload.",
"name": "read",
"signature": "def read(cls, readfunc: Callable) -> SLPResponse"
}
] | 2 | stack_v2_sparse_classes_30k_train_027005 | Implement the Python class `SLPResponse` described below.
Class description:
A server list ping response.
Method signatures and docstrings:
- def __bytes__(self): Returns the respective bytes.
- def read(cls, readfunc: Callable) -> SLPResponse: Creates the SLP response from the respective payload. | Implement the Python class `SLPResponse` described below.
Class description:
A server list ping response.
Method signatures and docstrings:
- def __bytes__(self): Returns the respective bytes.
- def read(cls, readfunc: Callable) -> SLPResponse: Creates the SLP response from the respective payload.
<|skeleton|>
class... | b81bbe256987b12984f0b58f11d3639be4cb131f | <|skeleton|>
class SLPResponse:
"""A server list ping response."""
def __bytes__(self):
"""Returns the respective bytes."""
<|body_0|>
def read(cls, readfunc: Callable) -> SLPResponse:
"""Creates the SLP response from the respective payload."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SLPResponse:
"""A server list ping response."""
def __bytes__(self):
"""Returns the respective bytes."""
json = dumps(self).encode('latin-1')
json_size = len(json)
json_size = VarInt(json_size)
json_size = bytes(json_size)
payload = json_size + json
... | the_stack_v2_python_sparse | venv/Lib/site-packages/mcipc/server/datastructures.py | jacob-goodall/redditmc | train | 0 |
fd48449f57bf4f4884b2602a40510921a84a09fe | [
"if l1 is None:\n return l2\nelif l2 is None:\n return l1\nelif l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2",
"prehead = ListNode(-1)\nprev = prehead\nwhile l1 and l2:\n if l1.val <= l2.val:\n p... | <|body_start_0|>
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Recursion"""
<|body_0|>
def mergeTwoLists2(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Iteration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l1 i... | stack_v2_sparse_classes_75kplus_train_002031 | 1,700 | no_license | [
{
"docstring": "Recursion",
"name": "mergeTwoLists1",
"signature": "def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode'"
},
{
"docstring": "Iteration",
"name": "mergeTwoLists2",
"signature": "def mergeTwoLists2(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode'"
}
] | 2 | stack_v2_sparse_classes_30k_train_052547 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Recursion
- def mergeTwoLists2(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Iteration | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Recursion
- def mergeTwoLists2(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': Iteration
<|skeleton|... | 7694d0798fe55c69f350013b9329a5844c8c5e35 | <|skeleton|>
class Solution:
def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Recursion"""
<|body_0|>
def mergeTwoLists2(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Iteration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists1(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
"""Recursion"""
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
... | the_stack_v2_python_sparse | MergeSortedLinkedList (deleted e6c1755b7814d9883cf49e0d0465500a).py | annaymj/LeetCode | train | 4 | |
5dbb21a127644b1107ea44da4c5dff509fe527db | [
"if Patient.objects.get(pk=pk).deleted:\n return Response('the patient was not found', status=status.HTTP_400_BAD_REQUEST)\nbackground = Background.objects.all().filter(deleted=False, patient=pk).order_by('-date')\nserializer = BackgroundSerialize(background, many=True)\ndata_response = {'total': len(background)... | <|body_start_0|>
if Patient.objects.get(pk=pk).deleted:
return Response('the patient was not found', status=status.HTTP_400_BAD_REQUEST)
background = Background.objects.all().filter(deleted=False, patient=pk).order_by('-date')
serializer = BackgroundSerialize(background, many=True)
... | BackgroundListCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundListCreate:
def get(self, request, pk):
"""If patient was deleted, you can see background"""
<|body_0|>
def post(self, request, pk):
"""If patient was deleted, you can see background"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Patie... | stack_v2_sparse_classes_75kplus_train_002032 | 3,915 | no_license | [
{
"docstring": "If patient was deleted, you can see background",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "If patient was deleted, you can see background",
"name": "post",
"signature": "def post(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051666 | Implement the Python class `BackgroundListCreate` described below.
Class description:
Implement the BackgroundListCreate class.
Method signatures and docstrings:
- def get(self, request, pk): If patient was deleted, you can see background
- def post(self, request, pk): If patient was deleted, you can see background | Implement the Python class `BackgroundListCreate` described below.
Class description:
Implement the BackgroundListCreate class.
Method signatures and docstrings:
- def get(self, request, pk): If patient was deleted, you can see background
- def post(self, request, pk): If patient was deleted, you can see background
... | bdaf98bd7babe0da97e1394c5b94fa10253eddb6 | <|skeleton|>
class BackgroundListCreate:
def get(self, request, pk):
"""If patient was deleted, you can see background"""
<|body_0|>
def post(self, request, pk):
"""If patient was deleted, you can see background"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackgroundListCreate:
def get(self, request, pk):
"""If patient was deleted, you can see background"""
if Patient.objects.get(pk=pk).deleted:
return Response('the patient was not found', status=status.HTTP_400_BAD_REQUEST)
background = Background.objects.all().filter(delete... | the_stack_v2_python_sparse | api/views/background.py | ncrousset/mainDoctorNote | train | 0 | |
6f05d76584d418663f8e73ef0734adc34190bfca | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AttributeSet()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'description': lambda n: setattr(self, 'description', n.get_str_value()), 'maxAttributesPerSet': lambda n: setattr(se... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AttributeSet()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'description': lambda n: setattr(... | AttributeSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_75kplus_train_002033 | 2,525 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AttributeSet",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `AttributeSet` described below.
Class description:
Implement the AttributeSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeSet: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `AttributeSet` described below.
Class description:
Implement the AttributeSet class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeSet: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AttributeSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributeSet:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeSet:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AttributeSet""... | the_stack_v2_python_sparse | msgraph/generated/models/attribute_set.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5a767f0552ace7d210cec7993e209b57dd0e79ee | [
"np.random.seed(seed)\nself.base_learner = base_learner\nself.n_estimator = n_estimator\nself._estimators = [copy.deepcopy(self.base_learner) for _ in range(self.n_estimator)]",
"import random\ncol = []\nwhile len(col) < X.shape[0]:\n _idx = random.randint(0, X.shape[0] - 1)\n col.append(_idx)\nX_bootstrap ... | <|body_start_0|>
np.random.seed(seed)
self.base_learner = base_learner
self.n_estimator = n_estimator
self._estimators = [copy.deepcopy(self.base_learner) for _ in range(self.n_estimator)]
<|end_body_0|>
<|body_start_1|>
import random
col = []
while len(col) < X.... | Random Forest Classifier. Note that this class only support binary classification. | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
"""Random Forest Classifier. Note that this class only support binary classification."""
def __init__(self, base_learner, n_estimator, seed=2020):
"""Initialize the classifier. Args: base_learner: the base_learner should provide the .fit() and .predict() interface. n_es... | stack_v2_sparse_classes_75kplus_train_002034 | 2,680 | no_license | [
{
"docstring": "Initialize the classifier. Args: base_learner: the base_learner should provide the .fit() and .predict() interface. n_estimator (int): The number of base learners in RandomForest. seed (int): random seed",
"name": "__init__",
"signature": "def __init__(self, base_learner, n_estimator, se... | 4 | stack_v2_sparse_classes_30k_train_039963 | Implement the Python class `RandomForest` described below.
Class description:
Random Forest Classifier. Note that this class only support binary classification.
Method signatures and docstrings:
- def __init__(self, base_learner, n_estimator, seed=2020): Initialize the classifier. Args: base_learner: the base_learner... | Implement the Python class `RandomForest` described below.
Class description:
Random Forest Classifier. Note that this class only support binary classification.
Method signatures and docstrings:
- def __init__(self, base_learner, n_estimator, seed=2020): Initialize the classifier. Args: base_learner: the base_learner... | bc65b92b4ca14b025b8d1fe65812fc5abdf6492f | <|skeleton|>
class RandomForest:
"""Random Forest Classifier. Note that this class only support binary classification."""
def __init__(self, base_learner, n_estimator, seed=2020):
"""Initialize the classifier. Args: base_learner: the base_learner should provide the .fit() and .predict() interface. n_es... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomForest:
"""Random Forest Classifier. Note that this class only support binary classification."""
def __init__(self, base_learner, n_estimator, seed=2020):
"""Initialize the classifier. Args: base_learner: the base_learner should provide the .fit() and .predict() interface. n_estimator (int)... | the_stack_v2_python_sparse | assignment4/hw4_code(1)/ml2020fall_hw4/ensemble/random_forest.py | nc-yc/MachineLearningZJU | train | 0 |
e027a9183c2c149dd94aeeaa48900e5a483960bd | [
"super().__init__()\nself._img_size = config.get('img_size')\nself._input_channel = config.get('input_channel')\nself._filter_sizes = config.get('filter_size')\nself._kernel_size = config.get('kernel_size')\nself._padding = padding\nself._stride = stride\nself._dilation = dilation\nself._encoder_maxpool_count = con... | <|body_start_0|>
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = config.get('filter_size')
self._kernel_size = config.get('kernel_size')
self._padding = padding
self._stride = stride... | Deterministic_Conv_Encoder | Deterministic_Conv_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: ou... | stack_v2_sparse_classes_75kplus_train_002035 | 18,202 | no_license | [
{
"docstring": "NP",
"name": "__init__",
"signature": "def __init__(self, config, padding=0, stride=2, dilation=1)"
},
{
"docstring": "Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: output :",
"name": "forward",
"signature": "def forward(self, in... | 2 | stack_v2_sparse_classes_30k_train_043794 | Implement the Python class `Deterministic_Conv_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size,... | Implement the Python class `Deterministic_Conv_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size,... | c7e1bfb49ebaec6937ed7b186689227f95a43e0f | <|skeleton|>
class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, filter_size img_size, img_size) Return: ou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Deterministic_Conv_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = conf... | the_stack_v2_python_sparse | model/MAML/Part/encoder.py | MingyuKim87/MLwM | train | 0 |
d7eda09b64d4e8dc7259fb318f9a218f7b1d36f6 | [
"super(RnnEncoder, self).__init__()\ncell = cell.lower()\ncell_types = {'rnn': nn.RNN, 'gru': nn.GRU, 'lstm': nn.LSTM}\nif cell not in cell_types:\n raise ValueError(f'Unknown RNN Cell: {cell}')\nself.cell = cell_types[cell](input_size=embed_dim, batch_first=True, hidden_size=n_hidden, num_layers=num_layers)\nse... | <|body_start_0|>
super(RnnEncoder, self).__init__()
cell = cell.lower()
cell_types = {'rnn': nn.RNN, 'gru': nn.GRU, 'lstm': nn.LSTM}
if cell not in cell_types:
raise ValueError(f'Unknown RNN Cell: {cell}')
self.cell = cell_types[cell](input_size=embed_dim, batch_first... | Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0. | RnnEncoder | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RnnEncoder:
"""Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0."""
def __init__(self, vocab_size: int, embed_dim: int, n_hidde... | stack_v2_sparse_classes_75kplus_train_002036 | 2,624 | permissive | [
{
"docstring": "Arguments: vocab_size {int} -- The size of the input vocabulary (including eos) embed_dim {int} -- Dimensionality of the embeddings n_hidden {int} -- Dimensionality of the cell's hidden state Keyword Arguments: cell {str} -- Type of the cell ('rnn', 'gru', or 'lstm') (default: {'rnn'}) num_layer... | 2 | stack_v2_sparse_classes_30k_train_036737 | Implement the Python class `RnnEncoder` described below.
Class description:
Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0.
Method signatures and docst... | Implement the Python class `RnnEncoder` described below.
Class description:
Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0.
Method signatures and docst... | 18d72d86cf9706e7ad82f94719b56accd288e59a | <|skeleton|>
class RnnEncoder:
"""Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0."""
def __init__(self, vocab_size: int, embed_dim: int, n_hidde... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RnnEncoder:
"""Feeds a sequence into an RNN (vanilla RNN, GRU, LSTM) cell and returns a vector representation of it, which is found as the last hidden state of the last RNN layer. Assumes that the eos token has the id equal to 0."""
def __init__(self, vocab_size: int, embed_dim: int, n_hidden: int, cell:... | the_stack_v2_python_sparse | egg/core/rnn.py | facebookresearch/EGG | train | 304 |
3563d01ecfe238a029ec2cd878deb16e4cde0cb3 | [
"details = encoding.force_text(details)\nbody = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}\nreturn self._create('/os-systemlogs', body, 'systemlog')",
"if filters:\n url = '/os-systemlogs?filters=%s' % filters\nelse:\n url = '/os-systemlogs'\nLOG.info... | <|body_start_0|>
details = encoding.force_text(details)
body = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}
return self._create('/os-systemlogs', body, 'systemlog')
<|end_body_0|>
<|body_start_1|>
if filters:
url = '/os-... | SystemlogManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
<|body_0|>
def list(self, filters=None):
"""Get list of system logs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
details = encoding.force_text(de... | stack_v2_sparse_classes_75kplus_train_002037 | 995 | permissive | [
{
"docstring": "Create action logs.",
"name": "create",
"signature": "def create(self, name, event_subject, result, details)"
},
{
"docstring": "Get list of system logs.",
"name": "list",
"signature": "def list(self, filters=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008911 | Implement the Python class `SystemlogManager` described below.
Class description:
Implement the SystemlogManager class.
Method signatures and docstrings:
- def create(self, name, event_subject, result, details): Create action logs.
- def list(self, filters=None): Get list of system logs. | Implement the Python class `SystemlogManager` described below.
Class description:
Implement the SystemlogManager class.
Method signatures and docstrings:
- def create(self, name, event_subject, result, details): Create action logs.
- def list(self, filters=None): Get list of system logs.
<|skeleton|>
class Systemlog... | 54e45b2daa205132c05b0ff5a2c3db7fca2853a7 | <|skeleton|>
class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
<|body_0|>
def list(self, filters=None):
"""Get list of system logs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SystemlogManager:
def create(self, name, event_subject, result, details):
"""Create action logs."""
details = encoding.force_text(details)
body = {'systemlog': {'name': name, 'event_subject': event_subject, 'result': result, 'details': details}}
return self._create('/os-systeml... | the_stack_v2_python_sparse | novaclient/v2/systemlogs.py | xuweiliang/Codelibrary | train | 0 | |
62b6b015d08e3d1fa302ec62d95e94250b82c7f5 | [
"if not root:\n return True\nreturn self.check(root) != -1",
"if not root:\n return 0\nelse:\n left = self.check(root.left)\n right = self.check(root.right)\n if left == -1 or right == -1 or abs(left - right) > 1:\n return -1\n else:\n return max(left, right) + 1"
] | <|body_start_0|>
if not root:
return True
return self.check(root) != -1
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
else:
left = self.check(root.left)
right = self.check(root.right)
if left == -1 or right == -1 or abs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def check(self, root):
"""combine calculate depth of a tree (subtree) and examine whether subtrees are balanced together. If return -1 means current node is not balanced, else re... | stack_v2_sparse_classes_75kplus_train_002038 | 1,768 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": "combine calculate depth of a tree (subtree) and examine whether subtrees are balanced together. If return -1 means current node is not balanced, else return actu... | 2 | stack_v2_sparse_classes_30k_train_010141 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def check(self, root): combine calculate depth of a tree (subtree) and examine whether subtrees are balanced toget... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def check(self, root): combine calculate depth of a tree (subtree) and examine whether subtrees are balanced toget... | 2bcd0f6a704346cdac4ecccd6c0baef579d38fac | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def check(self, root):
"""combine calculate depth of a tree (subtree) and examine whether subtrees are balanced together. If return -1 means current node is not balanced, else re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
return self.check(root) != -1
def check(self, root):
"""combine calculate depth of a tree (subtree) and examine whether subtrees are balanced together. If ret... | the_stack_v2_python_sparse | BalancedBinaryTree.py | marsunique/LeetCodeOJ | train | 1 | |
797b48eba8b550b2169a53ff5a76e512e4f13e86 | [
"self.time_delta_val = time_delta\nself.time_grace_val = time_grace\nself.db_lookup = db_lookup\nself.data_binding = data_binding\nself.nowtime = nowtime\nself.formatter = formatter\nself.converter = converter\nself.time_delta = weewx.units.ValueHelper((time_delta, 'second', 'group_elapsed'), 'current', self.format... | <|body_start_0|>
self.time_delta_val = time_delta
self.time_grace_val = time_grace
self.db_lookup = db_lookup
self.data_binding = data_binding
self.nowtime = nowtime
self.formatter = formatter
self.converter = converter
self.time_delta = weewx.units.ValueH... | Helper class that calculates trends. This class allows tags such as: $trend.barometer | TrendObj | [
"GPL-3.0-only",
"GPL-1.0-or-later",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over w... | stack_v2_sparse_classes_75kplus_train_002039 | 23,688 | permissive | [
{
"docstring": "Initialize a Trend object time_delta: The time difference over which the trend is to be calculated time_grace: A time within this amount is accepted.",
"name": "__init__",
"signature": "def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **o... | 2 | stack_v2_sparse_classes_30k_train_028731 | Implement the Python class `TrendObj` described below.
Class description:
Helper class that calculates trends. This class allows tags such as: $trend.barometer
Method signatures and docstrings:
- def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict): Initial... | Implement the Python class `TrendObj` described below.
Class description:
Helper class that calculates trends. This class allows tags such as: $trend.barometer
Method signatures and docstrings:
- def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict): Initial... | 7085654f455d39b06acc688738fde27e1f78ad1e | <|skeleton|>
class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over which the tren... | the_stack_v2_python_sparse | dist/weewx-3.9.1/bin/weewx/tags.py | tomdotorg/docker-weewx | train | 21 |
f3dc5db833e1defacc02ab10e009868975eacf5d | [
"nums = set(nums)\nif len(nums) < 3:\n return max(nums)\nelse:\n nums.remove(max(nums))\n nums.remove(max(nums))\n return max(nums)",
"nums = set(nums)\nif len(nums) < 3:\n return max(nums)\nelse:\n return sorted(nums)[len(nums) - 3]"
] | <|body_start_0|>
nums = set(nums)
if len(nums) < 3:
return max(nums)
else:
nums.remove(max(nums))
nums.remove(max(nums))
return max(nums)
<|end_body_0|>
<|body_start_1|>
nums = set(nums)
if len(nums) < 3:
return max(num... | Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1."""
def thirdMaxBest(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax(self, nums):
""":ty... | stack_v2_sparse_classes_75kplus_train_002040 | 940 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "thirdMaxBest",
"signature": "def thirdMaxBest(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "thirdMax",
"signature": "def thirdMax(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010648 | Implement the Python class `Solution` described below.
Class description:
Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Method signatures and docstrings:
- def thirdMaxBest(self, nums): :type nums: List[int] :rtype: int
- def thir... | Implement the Python class `Solution` described below.
Class description:
Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Method signatures and docstrings:
- def thirdMaxBest(self, nums): :type nums: List[int] :rtype: int
- def thir... | 0420fbcbebad3b746db63b9e9a5878b4af8ad6ac | <|skeleton|>
class Solution:
"""Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1."""
def thirdMaxBest(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def thirdMax(self, nums):
""":ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Problem: https://leetcode.com/problems/third-maximum-number/ Example: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1."""
def thirdMaxBest(self, nums):
""":type nums: List[int] :rtype: int"""
nums = set(nums)
if len(nums) < 3:
return max(num... | the_stack_v2_python_sparse | leetcode/array/easy/thirdMax.py | joway/PyAlgorithm | train | 1 |
27946086427f3fb6dd1892af440f0f524bc51e07 | [
"maxprofit = 0\nfor i in range(len(prices)):\n for j in range(i, len(prices)):\n tmp = prices[j] - prices[i]\n if tmp > 0 and tmp > maxprofit:\n maxprofit = tmp\nreturn maxprofit",
"if len(prices) < 2:\n return 0\nminprice = prices[0]\nmaxprofit = prices[1] - minprice\nfor i in rang... | <|body_start_0|>
maxprofit = 0
for i in range(len(prices)):
for j in range(i, len(prices)):
tmp = prices[j] - prices[i]
if tmp > 0 and tmp > maxprofit:
maxprofit = tmp
return maxprofit
<|end_body_0|>
<|body_start_1|>
if len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""时间复杂度为O(n) 空间复杂度为O(1)"""
<|body_1|>
def maxProfit2(self, prices: List[int]... | stack_v2_sparse_classes_75kplus_train_002041 | 2,609 | no_license | [
{
"docstring": "暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "时间复杂度为O(n) 空间复杂度为O(1)",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices: List[int]) -> int"
},
... | 4 | stack_v2_sparse_classes_30k_train_027603 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)
- def maxProfit1(self, prices: List[int]) -> int: 时间复杂度为O(n) 空间复杂度为O(1)
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)
- def maxProfit1(self, prices: List[int]) -> int: 时间复杂度为O(n) 空间复杂度为O(1)
- de... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""时间复杂度为O(n) 空间复杂度为O(1)"""
<|body_1|>
def maxProfit2(self, prices: List[int]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力解法 暴力解法固然可以解决问题,但是时间复杂度就爆炸了 时间复杂度为:O(mn) 空间复杂度为:O(1)"""
maxprofit = 0
for i in range(len(prices)):
for j in range(i, len(prices)):
tmp = prices[j] - prices[i]
if tmp > 0 and tmp > ... | the_stack_v2_python_sparse | LeetCode_practice/DynamicProgramming/0121.BestTimeToBuyAndSellStock_1.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
f8f00c84b39fbfc47da8edb6cc68243aa298f503 | [
"self.num = num\nself.queue = queue\nself.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()",
"while True:\n if self.queue.empty():\n print('[{}] Doing something imporant in the background'.format(self.num))\n else:\n val = self.queu... | <|body_start_0|>
self.num = num
self.queue = queue
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
<|end_body_0|>
<|body_start_1|>
while True:
if self.queue.empty():
prin... | Threading example class The run() method will be started and it will run in the background until the application exits. | ThreadingExample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body... | stack_v2_sparse_classes_75kplus_train_002042 | 1,475 | no_license | [
{
"docstring": "Constructor :type interval: int :param interval: Check interval, in seconds",
"name": "__init__",
"signature": "def __init__(self, num, queue, interval=1)"
},
{
"docstring": "Method that runs forever",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032966 | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, num, queue, interval=1): Constructor :type interval: int :par... | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, num, queue, interval=1): Constructor :type interval: int :par... | 5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
self.num = num
... | the_stack_v2_python_sparse | python/test-multiprocessing/threading_example.py | hyunjun/practice | train | 3 |
16815a40c2a1a091e12b896b6d2c9fe45b171de9 | [
"super().setUp()\nself.VIP = os.environ.get('TEST_VIP00', None)\nif self.VIP is None:\n self.fail(\"Environment variable 'TEST_VIP00' is required.\")",
"config = {'service_ips': self.VIP}\nlogging.info('Configuring %s as a Service IP for %s unit.', self.VIP, self.UNIT)\nzaza_model.set_application_config(self.A... | <|body_start_0|>
super().setUp()
self.VIP = os.environ.get('TEST_VIP00', None)
if self.VIP is None:
self.fail("Environment variable 'TEST_VIP00' is required.")
<|end_body_0|>
<|body_start_1|>
config = {'service_ips': self.VIP}
logging.info('Configuring %s as a Servic... | Tests for configuration of Service IPs. | DesignateBindServiceIPsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DesignateBindServiceIPsTest:
"""Tests for configuration of Service IPs."""
def setUp(self):
"""Verify that TEST_VIP00 env variable is set."""
<|body_0|>
def test_configure_ips(self):
"""Configure and un-configure 'service_ips' option."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_002043 | 2,751 | permissive | [
{
"docstring": "Verify that TEST_VIP00 env variable is set.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Configure and un-configure 'service_ips' option.",
"name": "test_configure_ips",
"signature": "def test_configure_ips(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001359 | Implement the Python class `DesignateBindServiceIPsTest` described below.
Class description:
Tests for configuration of Service IPs.
Method signatures and docstrings:
- def setUp(self): Verify that TEST_VIP00 env variable is set.
- def test_configure_ips(self): Configure and un-configure 'service_ips' option. | Implement the Python class `DesignateBindServiceIPsTest` described below.
Class description:
Tests for configuration of Service IPs.
Method signatures and docstrings:
- def setUp(self): Verify that TEST_VIP00 env variable is set.
- def test_configure_ips(self): Configure and un-configure 'service_ips' option.
<|skel... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class DesignateBindServiceIPsTest:
"""Tests for configuration of Service IPs."""
def setUp(self):
"""Verify that TEST_VIP00 env variable is set."""
<|body_0|>
def test_configure_ips(self):
"""Configure and un-configure 'service_ips' option."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DesignateBindServiceIPsTest:
"""Tests for configuration of Service IPs."""
def setUp(self):
"""Verify that TEST_VIP00 env variable is set."""
super().setUp()
self.VIP = os.environ.get('TEST_VIP00', None)
if self.VIP is None:
self.fail("Environment variable 'TES... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/designate_bind/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
1a9e2019ff4b3e3f12191602dfc223928053b7de | [
"if v is not None:\n if urllib.parse.urlparse(values['repository']).scheme != 'https':\n raise InvalidRepositoryURLError(\"Crendentials can only be used with GitHub repositories using the 'HTTPS' format. You must either remove the credential if you wish to use the 'SSH' format and are not using a private ... | <|body_start_0|>
if v is not None:
if urllib.parse.urlparse(values['repository']).scheme != 'https':
raise InvalidRepositoryURLError("Crendentials can only be used with GitHub repositories using the 'HTTPS' format. You must either remove the credential if you wish to use the 'SSH' fo... | Interact with files stored on GitHub repositories. | GitHub | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitHub:
"""Interact with files stored on GitHub repositories."""
def _ensure_credentials_go_with_https(cls, v: str, values: dict) -> str:
"""Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: validates `access_token` specifically so that it only fires wh... | stack_v2_sparse_classes_75kplus_train_002044 | 34,075 | permissive | [
{
"docstring": "Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: validates `access_token` specifically so that it only fires when private repositories are used.",
"name": "_ensure_credentials_go_with_https",
"signature": "def _ensure_credentials_go_with_https(cls, v: str,... | 4 | stack_v2_sparse_classes_30k_val_000868 | Implement the Python class `GitHub` described below.
Class description:
Interact with files stored on GitHub repositories.
Method signatures and docstrings:
- def _ensure_credentials_go_with_https(cls, v: str, values: dict) -> str: Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: valid... | Implement the Python class `GitHub` described below.
Class description:
Interact with files stored on GitHub repositories.
Method signatures and docstrings:
- def _ensure_credentials_go_with_https(cls, v: str, values: dict) -> str: Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: valid... | 2c50d2b64c811c364cbc5faa2b5c80a742572090 | <|skeleton|>
class GitHub:
"""Interact with files stored on GitHub repositories."""
def _ensure_credentials_go_with_https(cls, v: str, values: dict) -> str:
"""Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: validates `access_token` specifically so that it only fires wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitHub:
"""Interact with files stored on GitHub repositories."""
def _ensure_credentials_go_with_https(cls, v: str, values: dict) -> str:
"""Ensure that credentials are not provided with 'SSH' formatted GitHub URLs. Note: validates `access_token` specifically so that it only fires when private re... | the_stack_v2_python_sparse | src/prefect/filesystems.py | PrefectHQ/prefect | train | 12,917 |
77edb2fd91d572b5070ff7452c87abea7b33c232 | [
"self._validateValues(crowdGroupName=crowdGroupName, crowdDirectoryName=crowdDirectoryName, crowdAccountName=crowdAccountName, bitbucketRepoName=bitbucketRepoName, bitbucketPermission=bitbucketPermission, bitbucketAccountName=bitbucketAccountName)\nif type(bitbucketPermission).__name__ != 'BitbucketPermission':\n ... | <|body_start_0|>
self._validateValues(crowdGroupName=crowdGroupName, crowdDirectoryName=crowdDirectoryName, crowdAccountName=crowdAccountName, bitbucketRepoName=bitbucketRepoName, bitbucketPermission=bitbucketPermission, bitbucketAccountName=bitbucketAccountName)
if type(bitbucketPermission).__name__ !=... | Bitbucket tools PyLabs extension | Bitbucket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bitbucket:
"""Bitbucket tools PyLabs extension"""
def crowdGroupSync(self, crowdGroupName, crowdDirectoryName, crowdAccountName, bitbucketRepoName, bitbucketPermission, bitbucketAccountName):
"""Sync a Bitbucket group with a Crowd group and give the specified Bitbucket group some pri... | stack_v2_sparse_classes_75kplus_train_002045 | 4,687 | no_license | [
{
"docstring": "Sync a Bitbucket group with a Crowd group and give the specified Bitbucket group some privileges on a Bitbucket repository @param crowdGroupName: Crowd group name @type crowdGroupName: string @param crowdDirectoryName: Crowd directory name @type crowdDirectoryName: string @param crowdAccountName... | 2 | null | Implement the Python class `Bitbucket` described below.
Class description:
Bitbucket tools PyLabs extension
Method signatures and docstrings:
- def crowdGroupSync(self, crowdGroupName, crowdDirectoryName, crowdAccountName, bitbucketRepoName, bitbucketPermission, bitbucketAccountName): Sync a Bitbucket group with a Cr... | Implement the Python class `Bitbucket` described below.
Class description:
Bitbucket tools PyLabs extension
Method signatures and docstrings:
- def crowdGroupSync(self, crowdGroupName, crowdDirectoryName, crowdAccountName, bitbucketRepoName, bitbucketPermission, bitbucketAccountName): Sync a Bitbucket group with a Cr... | 53d349fa6bee0ccead29afd6676979b44c109a61 | <|skeleton|>
class Bitbucket:
"""Bitbucket tools PyLabs extension"""
def crowdGroupSync(self, crowdGroupName, crowdDirectoryName, crowdAccountName, bitbucketRepoName, bitbucketPermission, bitbucketAccountName):
"""Sync a Bitbucket group with a Crowd group and give the specified Bitbucket group some pri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bitbucket:
"""Bitbucket tools PyLabs extension"""
def crowdGroupSync(self, crowdGroupName, crowdDirectoryName, crowdAccountName, bitbucketRepoName, bitbucketPermission, bitbucketAccountName):
"""Sync a Bitbucket group with a Crowd group and give the specified Bitbucket group some privileges on a ... | the_stack_v2_python_sparse | extensions/tools/Bitbucket.py | racktivity/ext-pylabs-core | train | 0 |
64ffda6ed86aaee36da250f53f9f1dc306cdb1a1 | [
"majorindex = 0\ncount = 1\nfor i in range(1, len(nums)):\n if count == 0:\n majorindex = i\n count = 1\n continue\n if nums[i] == nums[majorindex]:\n count += 1\n else:\n count -= 1\nreturn nums[majorindex]",
"majorindex = 0\ncount = 1\nfor i in range(1, len(nums)):\n ... | <|body_start_0|>
majorindex = 0
count = 1
for i in range(1, len(nums)):
if count == 0:
majorindex = i
count = 1
continue
if nums[i] == nums[majorindex]:
count += 1
else:
count -= 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_75kplus_train_002046 | 1,420 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type ... | 3 | stack_v2_sparse_classes_30k_train_009645 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type n... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
majorindex = 0
count = 1
for i in range(1, len(nums)):
if count == 0:
majorindex = i
count = 1
continue
if nums[i] == nums[... | the_stack_v2_python_sparse | Python_leetcode/169_majority_elements.py | xiangcao/Leetcode | train | 0 | |
8830d03f7afc24bf42f2bbd190460924c67e853d | [
"self.nlabel = nlabel\nself.lamb = lamb\nself.value1 = value1\nself.value2 = value2\nself.niter = niter\nself.pairwise_cost = -self.value1 * self.lamb * np.eye(self.nlabel)\nself.pairwise_cost = self.pairwise_cost.astype(np.int32)",
"assert unary_term.shape[1] == self.nlabel, 'Unary term have wrong labels'\nnvert... | <|body_start_0|>
self.nlabel = nlabel
self.lamb = lamb
self.value1 = value1
self.value2 = value2
self.niter = niter
self.pairwise_cost = -self.value1 * self.lamb * np.eye(self.nlabel)
self.pairwise_cost = self.pairwise_cost.astype(np.int32)
<|end_body_0|>
<|body_... | DiscreteEnergyMinimize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
<|body_0|>
def solve(self, unary_term, pairwise_term, k):
... | stack_v2_sparse_classes_75kplus_train_002047 | 2,206 | permissive | [
{
"docstring": "Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000",
"name": "__init__",
"signature": "def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10)"
},
{
"docstring": "Args : unary_term - Numpy 2d array [nv... | 2 | stack_v2_sparse_classes_30k_train_040515 | Implement the Python class `DiscreteEnergyMinimize` described below.
Class description:
Implement the DiscreteEnergyMinimize class.
Method signatures and docstrings:
- def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10): Args: nlabel - int lamb - float should be positive value1 - int defaults to be 1... | Implement the Python class `DiscreteEnergyMinimize` described below.
Class description:
Implement the DiscreteEnergyMinimize class.
Method signatures and docstrings:
- def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10): Args: nlabel - int lamb - float should be positive value1 - int defaults to be 1... | 62c811c37001302e6759a18d6143b8ad657e4910 | <|skeleton|>
class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
<|body_0|>
def solve(self, unary_term, pairwise_term, k):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
self.nlabel = nlabel
self.lamb = lamb
self.value1 = value1
... | the_stack_v2_python_sparse | utils/pygco_op.py | snu-mllab/Deep-Hash-Table-CVPR19 | train | 12 | |
4ae8860b465affd7ad23dad0192080657d756186 | [
"self.type_renamings = type_renamings\nself.reverse_name_map = {}\nself.type_name_conflicts = {}\nself.type_renamed_to_builtin_scalar_conflicts = {}\nself.invalid_type_names = {}\nself.query_type = query_type\nself.custom_scalar_names = frozenset(custom_scalar_names)\nself.suppressed_type_names = set()",
"type_na... | <|body_start_0|>
self.type_renamings = type_renamings
self.reverse_name_map = {}
self.type_name_conflicts = {}
self.type_renamed_to_builtin_scalar_conflicts = {}
self.invalid_type_names = {}
self.query_type = query_type
self.custom_scalar_names = frozenset(custom_... | Traverse a Document AST, editing the names of nodes. | RenameSchemaTypesVisitor | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenameSchemaTypesVisitor:
"""Traverse a Document AST, editing the names of nodes."""
def __init__(self, type_renamings: TypeRenamingMapping, query_type: str, custom_scalar_names: AbstractSet[str]) -> None:
"""Create a visitor for renaming types in a schema AST. Args: type_renamings: ... | stack_v2_sparse_classes_75kplus_train_002048 | 44,550 | permissive | [
{
"docstring": "Create a visitor for renaming types in a schema AST. Args: type_renamings: maps original type name to renamed name or None (for type suppression). A type named \"Foo\" will be unchanged iff type_renamings does not map \"Foo\" to anything, i.e. type_renamings.get(\"Foo\", \"Foo\") returns \"Foo\"... | 3 | stack_v2_sparse_classes_30k_test_001732 | Implement the Python class `RenameSchemaTypesVisitor` described below.
Class description:
Traverse a Document AST, editing the names of nodes.
Method signatures and docstrings:
- def __init__(self, type_renamings: TypeRenamingMapping, query_type: str, custom_scalar_names: AbstractSet[str]) -> None: Create a visitor f... | Implement the Python class `RenameSchemaTypesVisitor` described below.
Class description:
Traverse a Document AST, editing the names of nodes.
Method signatures and docstrings:
- def __init__(self, type_renamings: TypeRenamingMapping, query_type: str, custom_scalar_names: AbstractSet[str]) -> None: Create a visitor f... | 4e68d592fc97855ca043dc20bdf59be4298647ab | <|skeleton|>
class RenameSchemaTypesVisitor:
"""Traverse a Document AST, editing the names of nodes."""
def __init__(self, type_renamings: TypeRenamingMapping, query_type: str, custom_scalar_names: AbstractSet[str]) -> None:
"""Create a visitor for renaming types in a schema AST. Args: type_renamings: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RenameSchemaTypesVisitor:
"""Traverse a Document AST, editing the names of nodes."""
def __init__(self, type_renamings: TypeRenamingMapping, query_type: str, custom_scalar_names: AbstractSet[str]) -> None:
"""Create a visitor for renaming types in a schema AST. Args: type_renamings: maps original... | the_stack_v2_python_sparse | graphql_compiler/schema_transformation/rename_schema.py | justinaustin/graphql-compiler | train | 0 |
6ea306a5c764dd69bcce8f04250033793caeb478 | [
"super().__init__(key, parent)\nself.height = 0\nself.skew = 0",
"left_height = self.left.height if self.left else -1\nright_height = self.right.height if self.right else -1\nself.height = max(left_height, right_height) + 1\nself.skew = right_height - left_height",
"node, c = (self.left, self.right)\na, b = (se... | <|body_start_0|>
super().__init__(key, parent)
self.height = 0
self.skew = 0
<|end_body_0|>
<|body_start_1|>
left_height = self.left.height if self.left else -1
right_height = self.right.height if self.right else -1
self.height = max(left_height, right_height) + 1
... | AVL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AVL:
def __init__(self, key=None, parent=None):
"""Augment BST with height and skew"""
<|body_0|>
def update(self):
"""Update height and skew"""
<|body_1|>
def right_rotate(self):
"""Rotate left to right, assuming left is not None __s__ __n__ _n_... | stack_v2_sparse_classes_75kplus_train_002049 | 8,262 | no_license | [
{
"docstring": "Augment BST with height and skew",
"name": "__init__",
"signature": "def __init__(self, key=None, parent=None)"
},
{
"docstring": "Update height and skew",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Rotate left to right, assuming left is ... | 6 | stack_v2_sparse_classes_30k_train_053112 | Implement the Python class `AVL` described below.
Class description:
Implement the AVL class.
Method signatures and docstrings:
- def __init__(self, key=None, parent=None): Augment BST with height and skew
- def update(self): Update height and skew
- def right_rotate(self): Rotate left to right, assuming left is not ... | Implement the Python class `AVL` described below.
Class description:
Implement the AVL class.
Method signatures and docstrings:
- def __init__(self, key=None, parent=None): Augment BST with height and skew
- def update(self): Update height and skew
- def right_rotate(self): Rotate left to right, assuming left is not ... | 1c79b0cd8552c1472a564230fd89f97c83deae78 | <|skeleton|>
class AVL:
def __init__(self, key=None, parent=None):
"""Augment BST with height and skew"""
<|body_0|>
def update(self):
"""Update height and skew"""
<|body_1|>
def right_rotate(self):
"""Rotate left to right, assuming left is not None __s__ __n__ _n_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AVL:
def __init__(self, key=None, parent=None):
"""Augment BST with height and skew"""
super().__init__(key, parent)
self.height = 0
self.skew = 0
def update(self):
"""Update height and skew"""
left_height = self.left.height if self.left else -1
rig... | the_stack_v2_python_sparse | 3/AVL.py | alvinzhu33/6.006 | train | 0 | |
551d351319962976d1c5729157cc9c054385d368 | [
"def call(user, perm):\n return getattr(self, perm)(obj, cls, user)\nfor func in inspect.getmembers(type(self), predicate=inspect.ismethod):\n if not isinstance(self, func[1].__self__.__class__):\n setattr(call, func[0], functools.partial(func[1], obj, cls))\n else:\n setattr(call, func[0], f... | <|body_start_0|>
def call(user, perm):
return getattr(self, perm)(obj, cls, user)
for func in inspect.getmembers(type(self), predicate=inspect.ismethod):
if not isinstance(self, func[1].__self__.__class__):
setattr(call, func[0], functools.partial(func[1], obj, cl... | Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provide permissions Node.has_permission = NodePermission() # Check class permissio... | Permission | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Permission:
"""Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provide permissions Node.has_permission = No... | stack_v2_sparse_classes_75kplus_train_002050 | 3,550 | permissive | [
{
"docstring": "Hacking object internals to provide means for the mentioned interface",
"name": "__get__",
"signature": "def __get__(self, obj, cls)"
},
{
"docstring": "Aggregates cls methods to self class",
"name": "_aggregate",
"signature": "def _aggregate(self, obj, cls, perm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024952 | Implement the Python class `Permission` described below.
Class description:
Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provi... | Implement the Python class `Permission` described below.
Class description:
Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provi... | 49c84f13a8f92427b01231615136549fb5be3a78 | <|skeleton|>
class Permission:
"""Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provide permissions Node.has_permission = No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Permission:
"""Base class used for defining class and instance permissions. Enabling an ''intuitive'' interface for checking permissions: # Define permissions class NodePermission(Permission): def change(self, obj, cls, user): return obj.user == user # Provide permissions Node.has_permission = NodePermission(... | the_stack_v2_python_sparse | orchestra/permissions/options.py | Ro9ueAdmin/django-orchestra | train | 0 |
e3284950e1e6fbff19757390c56a718c79881351 | [
"assert not self.running, 'Tried to start an already running ExtendedLoopingCall.'\nif interval < 0:\n raise ValueError('interval must be >= 0')\nself.running = True\ndeferred = self._deferred = Deferred()\nself.starttime = self.clock.seconds()\nself.interval = interval\nself._runAtStart = now\nself.callcount = ... | <|body_start_0|>
assert not self.running, 'Tried to start an already running ExtendedLoopingCall.'
if interval < 0:
raise ValueError('interval must be >= 0')
self.running = True
deferred = self._deferred = Deferred()
self.starttime = self.clock.seconds()
self.... | LoopingCall that can start at a delay different than `self.interval`. | ExtendedLoopingCall | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtendedLoopingCall:
"""LoopingCall that can start at a delay different than `self.interval`."""
def start(self, interval, now=True, start_delay=None, count_start=0):
"""Start running function every interval seconds. This overloads the LoopingCall default by offering the start_delay ... | stack_v2_sparse_classes_75kplus_train_002051 | 23,253 | permissive | [
{
"docstring": "Start running function every interval seconds. This overloads the LoopingCall default by offering the start_delay keyword and ability to repeat. Args: interval (int): Repeat interval in seconds. now (bool, optional): Whether to start immediately or after `start_delay` seconds. start_delay (int):... | 4 | stack_v2_sparse_classes_30k_train_030414 | Implement the Python class `ExtendedLoopingCall` described below.
Class description:
LoopingCall that can start at a delay different than `self.interval`.
Method signatures and docstrings:
- def start(self, interval, now=True, start_delay=None, count_start=0): Start running function every interval seconds. This overl... | Implement the Python class `ExtendedLoopingCall` described below.
Class description:
LoopingCall that can start at a delay different than `self.interval`.
Method signatures and docstrings:
- def start(self, interval, now=True, start_delay=None, count_start=0): Start running function every interval seconds. This overl... | 5e97df013399e1a401d0a7ec184c4b9eb3100edd | <|skeleton|>
class ExtendedLoopingCall:
"""LoopingCall that can start at a delay different than `self.interval`."""
def start(self, interval, now=True, start_delay=None, count_start=0):
"""Start running function every interval seconds. This overloads the LoopingCall default by offering the start_delay ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtendedLoopingCall:
"""LoopingCall that can start at a delay different than `self.interval`."""
def start(self, interval, now=True, start_delay=None, count_start=0):
"""Start running function every interval seconds. This overloads the LoopingCall default by offering the start_delay keyword and a... | the_stack_v2_python_sparse | evennia-engine/evennia/evennia/scripts/scripts.py | rajammanabrolu/WorldGeneration | train | 69 |
de5cc6767c3f9066a3bc76aa323be54addad780c | [
"try:\n firewallController = FirewallController()\n json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404... | <|body_start_0|>
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as v... | Interface_ifEntry_Ipv4Configuration_MacAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
<|body_0|>
def put(self, id):
"""Update the default gw of an interface"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_002052 | 12,460 | no_license | [
{
"docstring": "Get the default gw address of an interface",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update the default gw of an interface",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005382 | Implement the Python class `Interface_ifEntry_Ipv4Configuration_MacAddress` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_MacAddress class.
Method signatures and docstrings:
- def get(self, id): Get the default gw address of an interface
- def put(self, id): Update the default ... | Implement the Python class `Interface_ifEntry_Ipv4Configuration_MacAddress` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_MacAddress class.
Method signatures and docstrings:
- def get(self, id): Get the default gw address of an interface
- def put(self, id): Update the default ... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
<|body_0|>
def put(self, id):
"""Update the default gw of an interface"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))
resp ... | the_stack_v2_python_sparse | configuration-agent/firewall/rest_api/resources/interface.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
2305f2f0d959554ce14adc6c6bf39e80efc65800 | [
"if not root:\n return 0\nif not root.left and (not root.right):\n return 1\nif not root.left:\n return 1 + self.minDepthRecursive(root.right)\nif not root.right:\n return 1 + self.minDepthRecursive(root.left)\nreturn 1 + min(self.minDepthRecursive(root.left), self.minDepthRecursive(root.right))",
"if... | <|body_start_0|>
if not root:
return 0
if not root.left and (not root.right):
return 1
if not root.left:
return 1 + self.minDepthRecursive(root.right)
if not root.right:
return 1 + self.minDepthRecursive(root.left)
return 1 + min(se... | MinimumDepthOfBinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimumDepthOfBinaryTree:
def minDepthRecursive(self, root: TreeNode) -> int:
"""Recursive solution. Check all cases below, this is different from max depth of binary tree question 1. Base case: Leaf node. Return 1, because height of node is 1 2. Left subtree is null (right subtree is no... | stack_v2_sparse_classes_75kplus_train_002053 | 6,761 | no_license | [
{
"docstring": "Recursive solution. Check all cases below, this is different from max depth of binary tree question 1. Base case: Leaf node. Return 1, because height of node is 1 2. Left subtree is null (right subtree is non-null) 3. Right subtree is null (left subtree is non-null) 4. Left and Right subtree are... | 2 | stack_v2_sparse_classes_30k_train_011429 | Implement the Python class `MinimumDepthOfBinaryTree` described below.
Class description:
Implement the MinimumDepthOfBinaryTree class.
Method signatures and docstrings:
- def minDepthRecursive(self, root: TreeNode) -> int: Recursive solution. Check all cases below, this is different from max depth of binary tree que... | Implement the Python class `MinimumDepthOfBinaryTree` described below.
Class description:
Implement the MinimumDepthOfBinaryTree class.
Method signatures and docstrings:
- def minDepthRecursive(self, root: TreeNode) -> int: Recursive solution. Check all cases below, this is different from max depth of binary tree que... | 33184f22ac6346f8734d4fcb98f4b52cf157931e | <|skeleton|>
class MinimumDepthOfBinaryTree:
def minDepthRecursive(self, root: TreeNode) -> int:
"""Recursive solution. Check all cases below, this is different from max depth of binary tree question 1. Base case: Leaf node. Return 1, because height of node is 1 2. Left subtree is null (right subtree is no... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinimumDepthOfBinaryTree:
def minDepthRecursive(self, root: TreeNode) -> int:
"""Recursive solution. Check all cases below, this is different from max depth of binary tree question 1. Base case: Leaf node. Return 1, because height of node is 1 2. Left subtree is null (right subtree is non-null) 3. Rig... | the_stack_v2_python_sparse | DataStructures/TreesGraphs/MinimumDepthOfBinaryTree/MinimumDepthOfBinaryTree.py | cagriozcaglar/ProgrammingExamples | train | 0 | |
5356dd5168bed7de562f662f87e861244acb8bff | [
"super().__init__(bt)\nif benchmark is None:\n benchmark = query('SSEC_CLOSE', (bt.start_date, bt.end_date)).iloc[:, 0]\nself._benchmark = price2nav(benchmark)\nself._riskfree_rate = riskfree_rate\nself._result_cache = None",
"nav = self._bt.navpd\nself.basic_msg = nav.apply(lambda x: brief_report(x, self._ben... | <|body_start_0|>
super().__init__(bt)
if benchmark is None:
benchmark = query('SSEC_CLOSE', (bt.start_date, bt.end_date)).iloc[:, 0]
self._benchmark = price2nav(benchmark)
self._riskfree_rate = riskfree_rate
self._result_cache = None
<|end_body_0|>
<|body_start_1|>
... | 净值分析器,主要用来计算一般的净值评估指标 | NavAnalysor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NavAnalysor:
"""净值分析器,主要用来计算一般的净值评估指标"""
def __init__(self, bt, benchmark=None, riskfree_rate=0.04):
"""Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (SSEC_CLOSE)作为参考基准 riskfree_rate: float, default 0.04 无风险利... | stack_v2_sparse_classes_75kplus_train_002054 | 18,859 | no_license | [
{
"docstring": "Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (SSEC_CLOSE)作为参考基准 riskfree_rate: float, default 0.04 无风险利率",
"name": "__init__",
"signature": "def __init__(self, bt, benchmark=None, riskfree_rate=0.04)"
},
{
... | 5 | null | Implement the Python class `NavAnalysor` described below.
Class description:
净值分析器,主要用来计算一般的净值评估指标
Method signatures and docstrings:
- def __init__(self, bt, benchmark=None, riskfree_rate=0.04): Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (... | Implement the Python class `NavAnalysor` described below.
Class description:
净值分析器,主要用来计算一般的净值评估指标
Method signatures and docstrings:
- def __init__(self, bt, benchmark=None, riskfree_rate=0.04): Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (... | 4080154dbf05781f3b48f551ee830d9f66687f87 | <|skeleton|>
class NavAnalysor:
"""净值分析器,主要用来计算一般的净值评估指标"""
def __init__(self, bt, benchmark=None, riskfree_rate=0.04):
"""Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (SSEC_CLOSE)作为参考基准 riskfree_rate: float, default 0.04 无风险利... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NavAnalysor:
"""净值分析器,主要用来计算一般的净值评估指标"""
def __init__(self, bt, benchmark=None, riskfree_rate=0.04):
"""Parameter --------- bt: BackTest 需要被分析的回测实例 benchmark: pd.Series, default None 基准的净值数据,要求起始时间与bt相同,如果没有给定,则自动使用同期的上证综指收盘价 (SSEC_CLOSE)作为参考基准 riskfree_rate: float, default 0.04 无风险利率"""
... | the_stack_v2_python_sparse | factortest/grouptest/analysis.py | rlcjj/GeneralLib | train | 0 |
ab138fde2857cb53d0dd8b9c5e3d0dc61b3681da | [
"super().__init__(parent, QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)\nself.horzLayout = QHBoxLayout()\nself.vertLayout = QVBoxLayout()\nself.spacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Fixed)\nself.btnPrint = QPushButton(self)\nself.btnPrint.se... | <|body_start_0|>
super().__init__(parent, QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinMaxButtonsHint | QtCore.Qt.WindowCloseButtonHint)
self.horzLayout = QHBoxLayout()
self.vertLayout = QVBoxLayout()
self.spacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Fixed)
sel... | Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons | HtmlDialog | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlDialog:
"""Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons"""
def __init__(self, parent=None):
"""Constructor of HtmlDialog :param parent: dialog parent :return:"""
<|body_0|>
def showHtml(self, html):
"""Show rendered value of ``ht... | stack_v2_sparse_classes_75kplus_train_002055 | 29,282 | permissive | [
{
"docstring": "Constructor of HtmlDialog :param parent: dialog parent :return:",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Show rendered value of ``html`` :param html: raw html data",
"name": "showHtml",
"signature": "def showHtml(self, html)"... | 2 | stack_v2_sparse_classes_30k_train_041794 | Implement the Python class `HtmlDialog` described below.
Class description:
Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor of HtmlDialog :param parent: dialog parent :return:
- def showHtml(self, html): Show r... | Implement the Python class `HtmlDialog` described below.
Class description:
Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor of HtmlDialog :param parent: dialog parent :return:
- def showHtml(self, html): Show r... | f6c86cc95218216cbd0f548b508d0c5fde11520e | <|skeleton|>
class HtmlDialog:
"""Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons"""
def __init__(self, parent=None):
"""Constructor of HtmlDialog :param parent: dialog parent :return:"""
<|body_0|>
def showHtml(self, html):
"""Show rendered value of ``ht... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HtmlDialog:
"""Generate a more complex HTML Viewer dialog window, with Prin/Close Buttons"""
def __init__(self, parent=None):
"""Constructor of HtmlDialog :param parent: dialog parent :return:"""
super().__init__(parent, QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinMaxButtonsHint | QtCo... | the_stack_v2_python_sparse | oPB/gui/utilities.py | pandel/opsiPackageBuilder | train | 10 |
951fce572d28139ec0941b85411fc1902183c911 | [
"if not payload.get('id') or not payload.get('username') or (not payload.get('email')):\n msg = 'Invalid user data'\n raise exceptions.NotAcceptable(detail=msg, code=status.HTTP_406_NOT_ACCEPTABLE)\ntoken = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256').decode()\nreturn token",
"try:\n user_... | <|body_start_0|>
if not payload.get('id') or not payload.get('username') or (not payload.get('email')):
msg = 'Invalid user data'
raise exceptions.NotAcceptable(detail=msg, code=status.HTTP_406_NOT_ACCEPTABLE)
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256').de... | JWTHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWTHelper:
def generate_token(self, payload):
"""Generates the JWT token Args: payload(dict): User data Returns: token: JWT token"""
<|body_0|>
def decode_token(self, token):
"""Decodes the token to get user data Args: token: JWT token Returns: User data"""
<... | stack_v2_sparse_classes_75kplus_train_002056 | 1,439 | permissive | [
{
"docstring": "Generates the JWT token Args: payload(dict): User data Returns: token: JWT token",
"name": "generate_token",
"signature": "def generate_token(self, payload)"
},
{
"docstring": "Decodes the token to get user data Args: token: JWT token Returns: User data",
"name": "decode_toke... | 2 | null | Implement the Python class `JWTHelper` described below.
Class description:
Implement the JWTHelper class.
Method signatures and docstrings:
- def generate_token(self, payload): Generates the JWT token Args: payload(dict): User data Returns: token: JWT token
- def decode_token(self, token): Decodes the token to get us... | Implement the Python class `JWTHelper` described below.
Class description:
Implement the JWTHelper class.
Method signatures and docstrings:
- def generate_token(self, payload): Generates the JWT token Args: payload(dict): User data Returns: token: JWT token
- def decode_token(self, token): Decodes the token to get us... | f0eb64c27e1fe37d5c81e4b9a8762dcf3c336a79 | <|skeleton|>
class JWTHelper:
def generate_token(self, payload):
"""Generates the JWT token Args: payload(dict): User data Returns: token: JWT token"""
<|body_0|>
def decode_token(self, token):
"""Decodes the token to get user data Args: token: JWT token Returns: User data"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JWTHelper:
def generate_token(self, payload):
"""Generates the JWT token Args: payload(dict): User data Returns: token: JWT token"""
if not payload.get('id') or not payload.get('username') or (not payload.get('email')):
msg = 'Invalid user data'
raise exceptions.NotAcce... | the_stack_v2_python_sparse | authors/apps/authentication/jwt_helper.py | andela/ah-backend-valkyrie | train | 0 | |
7ec2ca798e48eb8ebe95d67f18f5255830260600 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | MpfHardwareService | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MpfHardwareService:
def Start(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendSwitchChanges(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_002057 | 2,126 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Start",
"signature": "def Start(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "SendSwitchChanges",
"signature": "def SendSwitchChanges(self... | 3 | stack_v2_sparse_classes_30k_train_024298 | Implement the Python class `MpfHardwareService` described below.
Class description:
Implement the MpfHardwareService class.
Method signatures and docstrings:
- def Start(self, request, context): Missing associated documentation comment in .proto file.
- def SendSwitchChanges(self, request_iterator, context): Missing ... | Implement the Python class `MpfHardwareService` described below.
Class description:
Implement the MpfHardwareService class.
Method signatures and docstrings:
- def Start(self, request, context): Missing associated documentation comment in .proto file.
- def SendSwitchChanges(self, request_iterator, context): Missing ... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class MpfHardwareService:
def Start(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def SendSwitchChanges(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MpfHardwareService:
def Start(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Sen... | the_stack_v2_python_sparse | mpf/platforms/visual_pinball_engine/test_client.py | missionpinball/mpf | train | 191 | |
14ed18b1ddf10ab10326671cd9deca237f83900f | [
"self.warmup = warmup\nself.d_model = d_model\nsuper().__init__(optimizer, lr_lambda=self.lr_lambda, last_epoch=-1)",
"if step == 0 and self.warmup == 0:\n return 1.0 / self.d_model ** 0.5\nelif step > self.warmup:\n return 1.0 / self.d_model ** 0.5 / step ** 0.5\nelse:\n return step / self.d_model ** 0.... | <|body_start_0|>
self.warmup = warmup
self.d_model = d_model
super().__init__(optimizer, lr_lambda=self.lr_lambda, last_epoch=-1)
<|end_body_0|>
<|body_start_1|>
if step == 0 and self.warmup == 0:
return 1.0 / self.d_model ** 0.5
elif step > self.warmup:
... | Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch. | NoamScheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoamScheduler:
"""Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch."""
def __init__(self, optimizer, warmup: int, d_model:... | stack_v2_sparse_classes_75kplus_train_002058 | 1,530 | permissive | [
{
"docstring": "Initialize the NoamScheduler. Parameters ---------- optimizer : torch.optim.Optimizer Wrapped optimizer. warmup : int The number of linear warmup phases d_model : int, optional The index of last step. Default: -1",
"name": "__init__",
"signature": "def __init__(self, optimizer, warmup: i... | 2 | stack_v2_sparse_classes_30k_train_010216 | Implement the Python class `NoamScheduler` described below.
Class description:
Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch.
Method signatures a... | Implement the Python class `NoamScheduler` described below.
Class description:
Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch.
Method signatures a... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class NoamScheduler:
"""Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch."""
def __init__(self, optimizer, warmup: int, d_model:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoamScheduler:
"""Linear warmup and then quadratic decay. Linearly increases the learning rate from 0 to 1 over `warmup` steps. Quadratically decreases the learning rate after. This scheduler is generally used after every training batch."""
def __init__(self, optimizer, warmup: int, d_model: int):
... | the_stack_v2_python_sparse | flambe/optim/noam.py | cle-ros/flambe | train | 1 |
eac31d42d601a4726313908224fd8687c5e763e9 | [
"self.pool = []\nself.factory = factory\nself.factory.variablePool = self.pool",
"if self.pool:\n construct = self.pool.pop()\nelse:\n construct = self.factory.__class__.__new__(self.factory.__class__)\n construct.__dict__ = self.factory.__dict__.copy()\nreturn construct",
"construct = self.Get()\ncons... | <|body_start_0|>
self.pool = []
self.factory = factory
self.factory.variablePool = self.pool
<|end_body_0|>
<|body_start_1|>
if self.pool:
construct = self.pool.pop()
else:
construct = self.factory.__class__.__new__(self.factory.__class__)
con... | A base pool for providing objects. | BasePool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePool:
"""A base pool for providing objects."""
def __init__(self, factory):
"""Set up the pool itself, and the factory."""
<|body_0|>
def Get(self):
"""Return a new object, from the pool if possible."""
<|body_1|>
def New(self, vector, player=Non... | stack_v2_sparse_classes_75kplus_train_002059 | 894 | no_license | [
{
"docstring": "Set up the pool itself, and the factory.",
"name": "__init__",
"signature": "def __init__(self, factory)"
},
{
"docstring": "Return a new object, from the pool if possible.",
"name": "Get",
"signature": "def Get(self)"
},
{
"docstring": "Return a new object, editi... | 3 | null | Implement the Python class `BasePool` described below.
Class description:
A base pool for providing objects.
Method signatures and docstrings:
- def __init__(self, factory): Set up the pool itself, and the factory.
- def Get(self): Return a new object, from the pool if possible.
- def New(self, vector, player=None): ... | Implement the Python class `BasePool` described below.
Class description:
A base pool for providing objects.
Method signatures and docstrings:
- def __init__(self, factory): Set up the pool itself, and the factory.
- def Get(self): Return a new object, from the pool if possible.
- def New(self, vector, player=None): ... | 53004b4c6c8ca0143d94be2d41c35b4169affe97 | <|skeleton|>
class BasePool:
"""A base pool for providing objects."""
def __init__(self, factory):
"""Set up the pool itself, and the factory."""
<|body_0|>
def Get(self):
"""Return a new object, from the pool if possible."""
<|body_1|>
def New(self, vector, player=Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasePool:
"""A base pool for providing objects."""
def __init__(self, factory):
"""Set up the pool itself, and the factory."""
self.pool = []
self.factory = factory
self.factory.variablePool = self.pool
def Get(self):
"""Return a new object, from the pool if p... | the_stack_v2_python_sparse | Ash/Pool.py | TheNotChosenOne/ash | train | 2 |
c66b2f84ce24ea33550b5d285affae0f3cc43ffd | [
"if root is None:\n return '[]'\nlevel = [root]\nres = [root.val]\nwhile level:\n tmp = []\n n = len(level)\n for i in range(n):\n node = level[i]\n if node:\n tmp.append(node.left)\n tmp.append(node.right)\n if any(tmp):\n level = tmp\n res += [x.val... | <|body_start_0|>
if root is None:
return '[]'
level = [root]
res = [root.val]
while level:
tmp = []
n = len(level)
for i in range(n):
node = level[i]
if node:
tmp.append(node.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002060 | 4,482 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_038624 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 7edaa25ed7ee263318fc9e53fa262969e5074879 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return '[]'
level = [root]
res = [root.val]
while level:
tmp = []
n = len(level)
for i in range(n... | the_stack_v2_python_sparse | trees/serializer.py | psavine42/leetstuff | train | 0 | |
317339788e33b0306418d361215735dcf96ebca5 | [
"isPalindrome = lambda s: s == s[::-1]\nremove1Char_index = lambda s, i: s[:i] + s[i + 1:]\nl, r = (0, len(s) - 1)\nwhile l < r:\n if s[l] != s[r]:\n leftpart = remove1Char_index(s, l)\n rightpart = remove1Char_index(s, r)\n return isPalindrome(leftpart) or isPalindrome(rightpart)\n l += ... | <|body_start_0|>
isPalindrome = lambda s: s == s[::-1]
remove1Char_index = lambda s, i: s[:i] + s[i + 1:]
l, r = (0, len(s) - 1)
while l < r:
if s[l] != s[r]:
leftpart = remove1Char_index(s, l)
rightpart = remove1Char_index(s, r)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
isPalindrome = lambda s: s == s[::-1]
remove1Char_... | stack_v2_sparse_classes_75kplus_train_002061 | 1,077 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome1",
"signature": "def validPalindrome1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013198 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome1(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): :type s: str :rtype: bool
- def validPalindrome1(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def validPalindrome(self, s)... | a0f270c1adce25be11df92877813037f2e73e28b | <|skeleton|>
class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def validPalindrome(self, s):
""":type s: str :rtype: bool"""
isPalindrome = lambda s: s == s[::-1]
remove1Char_index = lambda s, i: s[:i] + s[i + 1:]
l, r = (0, len(s) - 1)
while l < r:
if s[l] != s[r]:
leftpart = remove1Char_index... | the_stack_v2_python_sparse | leetcode/680_valid_palindrome_II.py | lvraikkonen/GoodCode | train | 0 | |
99c67e91df42f2e8a65bcd192ba5f7915b6609ea | [
"code = request.query_params.get('code')\nif code is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\nweiboauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID, client_secret=settings.WEIBO_CLIENT_SECRET, redirect_uri=settings.WEIBO_REDIRECT_URI, state=next)\naccess_token = weiboauth.get_access_token... | <|body_start_0|>
code = request.query_params.get('code')
if code is None:
return Response(status=status.HTTP_400_BAD_REQUEST)
weiboauth = OAuthWeibo(client_id=settings.WEIBO_CLIENT_ID, client_secret=settings.WEIBO_CLIENT_SECRET, redirect_uri=settings.WEIBO_REDIRECT_URI, state=next)
... | 验证微博登录 | WeiboOauthView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeiboOauthView:
"""验证微博登录"""
def get(self, request):
"""第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass"""
<|body_0|>
def post(self, request):
"""微博用户未绑定,绑定微博用户 :return:"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_002062 | 9,593 | no_license | [
{
"docstring": "第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "微博用户未绑定,绑定微博用户 :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054003 | Implement the Python class `WeiboOauthView` described below.
Class description:
验证微博登录
Method signatures and docstrings:
- def get(self, request): 第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass
- def post(self, request): 微博用户未绑定,绑定微博用户 :return: | Implement the Python class `WeiboOauthView` described below.
Class description:
验证微博登录
Method signatures and docstrings:
- def get(self, request): 第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass
- def post(self, request): 微博用户未绑定,绑定微博用户 :return:
<|skeleton|>
class WeiboO... | 93f5c1159de7c2fcb5a4de0cfeee15b19529abf5 | <|skeleton|>
class WeiboOauthView:
"""验证微博登录"""
def get(self, request):
"""第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass"""
<|body_0|>
def post(self, request):
"""微博用户未绑定,绑定微博用户 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeiboOauthView:
"""验证微博登录"""
def get(self, request):
"""第三方登录检查 oauth/sina/user/ ?code=0e67548e9e075577630cc983ff79fa6a :param request: :return: pass"""
code = request.query_params.get('code')
if code is None:
return Response(status=status.HTTP_400_BAD_REQUEST)
... | the_stack_v2_python_sparse | mall/apps/oauth/views.py | studygroupfirst/meiduoshangcheng | train | 0 |
5df2c57202ea135e86aed4baa07b7e5ee8e2d5ab | [
"self.check_permissions(request, org_id, 'organizations.edit')\ncontext = dict(nav_active='memb', org_id=org_id)\nreturn render(request, 'organization/memb/select_person.html', context)",
"action = 'memberships.create'\nperson_ids = request.POST.getlist('person_id')\nself.check_permissions(request, org_id, action... | <|body_start_0|>
self.check_permissions(request, org_id, 'organizations.edit')
context = dict(nav_active='memb', org_id=org_id)
return render(request, 'organization/memb/select_person.html', context)
<|end_body_0|>
<|body_start_1|>
action = 'memberships.create'
person_ids = requ... | This page enables the user to choose one or more people to add as members to the organization. | SelectPerson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectPerson:
"""This page enables the user to choose one or more people to add as members to the organization."""
def get(self, request, org_id):
"""Show a form for selecting people to add as members."""
<|body_0|>
def post(self, request, org_id=None):
"""Create... | stack_v2_sparse_classes_75kplus_train_002063 | 3,181 | no_license | [
{
"docstring": "Show a form for selecting people to add as members.",
"name": "get",
"signature": "def get(self, request, org_id)"
},
{
"docstring": "Create a membership for each selected person.",
"name": "post",
"signature": "def post(self, request, org_id=None)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000440 | Implement the Python class `SelectPerson` described below.
Class description:
This page enables the user to choose one or more people to add as members to the organization.
Method signatures and docstrings:
- def get(self, request, org_id): Show a form for selecting people to add as members.
- def post(self, request,... | Implement the Python class `SelectPerson` described below.
Class description:
This page enables the user to choose one or more people to add as members to the organization.
Method signatures and docstrings:
- def get(self, request, org_id): Show a form for selecting people to add as members.
- def post(self, request,... | 0fecdba8d1ac5f26b2ff62bd6a431873588433ff | <|skeleton|>
class SelectPerson:
"""This page enables the user to choose one or more people to add as members to the organization."""
def get(self, request, org_id):
"""Show a form for selecting people to add as members."""
<|body_0|>
def post(self, request, org_id=None):
"""Create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelectPerson:
"""This page enables the user to choose one or more people to add as members to the organization."""
def get(self, request, org_id):
"""Show a form for selecting people to add as members."""
self.check_permissions(request, org_id, 'organizations.edit')
context = dict... | the_stack_v2_python_sparse | anthropod/collect/views/org_memb.py | AGarrow/blank_anthropod | train | 0 |
ee7db4b9afceb27427d76dba24bb87372a816b22 | [
"question = self.get_object()\nscore, created = MultipleChoiceScore.objects.get_or_create(question=question, user=request.user)\nscore.correct += 1\nscore.save()\nreturn Response({'status': 'ok'})",
"question = self.get_object()\nscore, created = MultipleChoiceScore.objects.get_or_create(question=question, user=r... | <|body_start_0|>
question = self.get_object()
score, created = MultipleChoiceScore.objects.get_or_create(question=question, user=request.user)
score.correct += 1
score.save()
return Response({'status': 'ok'})
<|end_body_0|>
<|body_start_1|>
question = self.get_object()
... | A viewset for viewing and editing quiz instances. | MultipleChoiceQuestionViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultipleChoiceQuestionViewSet:
"""A viewset for viewing and editing quiz instances."""
def correct(self, request, pk=None):
"""A view to track a correct answer for question and current user."""
<|body_0|>
def incorrect(self, request, pk=None):
"""A view to track ... | stack_v2_sparse_classes_75kplus_train_002064 | 5,413 | no_license | [
{
"docstring": "A view to track a correct answer for question and current user.",
"name": "correct",
"signature": "def correct(self, request, pk=None)"
},
{
"docstring": "A view to track an incorrect answer for question and current user.",
"name": "incorrect",
"signature": "def incorrect... | 2 | stack_v2_sparse_classes_30k_train_022917 | Implement the Python class `MultipleChoiceQuestionViewSet` described below.
Class description:
A viewset for viewing and editing quiz instances.
Method signatures and docstrings:
- def correct(self, request, pk=None): A view to track a correct answer for question and current user.
- def incorrect(self, request, pk=No... | Implement the Python class `MultipleChoiceQuestionViewSet` described below.
Class description:
A viewset for viewing and editing quiz instances.
Method signatures and docstrings:
- def correct(self, request, pk=None): A view to track a correct answer for question and current user.
- def incorrect(self, request, pk=No... | 788e4b92a6ed14a78a7458b8389b9a7bd30d870e | <|skeleton|>
class MultipleChoiceQuestionViewSet:
"""A viewset for viewing and editing quiz instances."""
def correct(self, request, pk=None):
"""A view to track a correct answer for question and current user."""
<|body_0|>
def incorrect(self, request, pk=None):
"""A view to track ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultipleChoiceQuestionViewSet:
"""A viewset for viewing and editing quiz instances."""
def correct(self, request, pk=None):
"""A view to track a correct answer for question and current user."""
question = self.get_object()
score, created = MultipleChoiceScore.objects.get_or_create... | the_stack_v2_python_sparse | studytime/questions/views.py | atypicalrobot/studytime_backend | train | 0 |
3c59f48bf7f1b88b435c291f4b78a6bf5c1c3694 | [
"self.size = size\nself.arr = []\nself.sum = 0",
"if len(self.arr) > 0 and len(self.arr) == self.size:\n left = self.arr.pop(0)\n self.sum -= left\nself.sum += val\nself.arr.append(val)\nreturn self.sum / float(len(self.arr))"
] | <|body_start_0|>
self.size = size
self.arr = []
self.sum = 0
<|end_body_0|>
<|body_start_1|>
if len(self.arr) > 0 and len(self.arr) == self.size:
left = self.arr.pop(0)
self.sum -= left
self.sum += val
self.arr.append(val)
return self.sum ... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.arr = [... | stack_v2_sparse_classes_75kplus_train_002065 | 704 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003802 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.arr = []
self.sum = 0
def next(self, val):
""":type val: int :rtype: float"""
if len(self.arr) > 0 and len(self.arr) == self.size:
... | the_stack_v2_python_sparse | leetcode/346-moving-average-from-data-stream/main.py | shriharshs/AlgoDaily | train | 0 | |
c0939baa98447151e4ab21bd60f0ddc0e625c9d9 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('aheckman_jfimbres', 'aheckman_jfimbres')\nurl = 'http://datamechanics.io/data/carbon_adjusted.json'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nr = json.loads(response)\ns = json.dump... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aheckman_jfimbres', 'aheckman_jfimbres')
url = 'http://datamechanics.io/data/carbon_adjusted.json'
response = urllib.request.urlopen(url).read().d... | get_carbon_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class get_carbon_data:
def execute(trial=False):
"""Retrieve data sets on carbon emissions from datamechanics.io."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in... | stack_v2_sparse_classes_75kplus_train_002066 | 5,701 | no_license | [
{
"docstring": "Retrieve data sets on carbon emissions from datamechanics.io.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describ... | 2 | null | Implement the Python class `get_carbon_data` described below.
Class description:
Implement the get_carbon_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve data sets on carbon emissions from datamechanics.io.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None... | Implement the Python class `get_carbon_data` described below.
Class description:
Implement the get_carbon_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve data sets on carbon emissions from datamechanics.io.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class get_carbon_data:
def execute(trial=False):
"""Retrieve data sets on carbon emissions from datamechanics.io."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class get_carbon_data:
def execute(trial=False):
"""Retrieve data sets on carbon emissions from datamechanics.io."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aheckman_jfimbres', 'aheckman_jfimbres')
u... | the_stack_v2_python_sparse | aheckman_jfimbres/get_carbon_data.py | maximega/course-2019-spr-proj | train | 2 | |
4fb1f70fba72e3428983219409a1eae99c237abf | [
"self.data = kwargs.get('data', None)\ntry:\n self.timezone = self.data.index.tz\nexcept:\n self.timezone = kwargs.get('timezone', None)\nself.longitude = kwargs.get('longitude', None)\nself.latitude = kwargs.get('latitude', None)\nself.geometry = kwargs.get('geometry', None)\nself.data_height = kwargs.get('d... | <|body_start_0|>
self.data = kwargs.get('data', None)
try:
self.timezone = self.data.index.tz
except:
self.timezone = kwargs.get('timezone', None)
self.longitude = kwargs.get('longitude', None)
self.latitude = kwargs.get('latitude', None)
self.geom... | FeedinWeather | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedinWeather:
def __init__(self, **kwargs):
"""Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing the time series of the different parameters as columns timezone : string, optional Containing the nam... | stack_v2_sparse_classes_75kplus_train_002067 | 4,658 | permissive | [
{
"docstring": "Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing the time series of the different parameters as columns timezone : string, optional Containing the name of the time zone using the naming of the IANA (Interne... | 2 | stack_v2_sparse_classes_30k_train_038424 | Implement the Python class `FeedinWeather` described below.
Class description:
Implement the FeedinWeather class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing... | Implement the Python class `FeedinWeather` described below.
Class description:
Implement the FeedinWeather class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing... | dd0635864bf2c65473b6ace5a28ceb56850e5c29 | <|skeleton|>
class FeedinWeather:
def __init__(self, **kwargs):
"""Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing the time series of the different parameters as columns timezone : string, optional Containing the nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeedinWeather:
def __init__(self, **kwargs):
"""Class, containing all meta informations regarding the weather data set. Parameters ---------- data : pandas.DataFrame, optional Containing the time series of the different parameters as columns timezone : string, optional Containing the name of the time ... | the_stack_v2_python_sparse | feedinlib/weather.py | PascalKerkeling/SESMG | train | 0 | |
c617086e66313b8b4aed037a22c5d89bf5d14f15 | [
"serializer = AddressSerializer(data=request.data)\nif serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\nelse:\n return Response(serializer.errors, status=422)",
"addresses = Address.objects.all()\nserializer = AddressSerializer(addresses, many=True)\nreturn Response(serializ... | <|body_start_0|>
serializer = AddressSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=422)
<|end_body_0|>
<|body_start_1|>
addresses = Address.ob... | AddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressView:
def post(self, request):
"""Create new address"""
<|body_0|>
def get(self, request):
"""Returns all addresses"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
serializer = AddressSerializer(data=request.data)
if serializer.is_val... | stack_v2_sparse_classes_75kplus_train_002068 | 995 | no_license | [
{
"docstring": "Create new address",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Returns all addresses",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051544 | Implement the Python class `AddressView` described below.
Class description:
Implement the AddressView class.
Method signatures and docstrings:
- def post(self, request): Create new address
- def get(self, request): Returns all addresses | Implement the Python class `AddressView` described below.
Class description:
Implement the AddressView class.
Method signatures and docstrings:
- def post(self, request): Create new address
- def get(self, request): Returns all addresses
<|skeleton|>
class AddressView:
def post(self, request):
"""Create... | d8709440b9bacbd28c64c2aca7eb37a61d29fe19 | <|skeleton|>
class AddressView:
def post(self, request):
"""Create new address"""
<|body_0|>
def get(self, request):
"""Returns all addresses"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressView:
def post(self, request):
"""Create new address"""
serializer = AddressSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=422)... | the_stack_v2_python_sparse | authApp/views.py | ArturRejment/gym-app-api | train | 1 | |
09424938ae1b1cd1ad6bfd5585a32064fbe8454d | [
"result = []\nfor v in words:\n value = v.upper()\n index = 0\n for i in value:\n t = self.keyboard[i]\n if index == 0:\n index = t\n elif index != t:\n index = -1\n break\n if index != -1:\n result.append(v)\nreturn result",
"keybrds = ['QW... | <|body_start_0|>
result = []
for v in words:
value = v.upper()
index = 0
for i in value:
t = self.keyboard[i]
if index == 0:
index = t
elif index != t:
index = -1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def findWords1(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
for v in wor... | stack_v2_sparse_classes_75kplus_train_002069 | 1,390 | permissive | [
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "findWords",
"signature": "def findWords(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "findWords1",
"signature": "def findWords1(self, words)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014892 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, words): :type words: List[str] :rtype: List[str]
- def findWords1(self, words): :type words: List[str] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, words): :type words: List[str] :rtype: List[str]
- def findWords1(self, words): :type words: List[str] :rtype: List[str]
<|skeleton|>
class Solution:
de... | 59fe045608dda924cb993dde957da4daff769438 | <|skeleton|>
class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_0|>
def findWords1(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findWords(self, words):
""":type words: List[str] :rtype: List[str]"""
result = []
for v in words:
value = v.upper()
index = 0
for i in value:
t = self.keyboard[i]
if index == 0:
index... | the_stack_v2_python_sparse | Python/Codes/Practice/LeetCodeCN/500 Keyboard row.py | QuincyWork/AllCodes | train | 0 | |
73dd82b1ee8421354e8d90215bb50ef0afa3f6c5 | [
"self.submission.is_source_processed = True\nself.submission.preview = mock.MagicMock(spec=Preview, source_id=1234, source_checksum='foochex==', preview_checksum='foochex==', size_bytes=1234578, added=datetime.now(UTC))\nmock_preview_service = mock.MagicMock()\nmock_preview_service.has_preview.return_value = True\n... | <|body_start_0|>
self.submission.is_source_processed = True
self.submission.preview = mock.MagicMock(spec=Preview, source_id=1234, source_checksum='foochex==', preview_checksum='foochex==', size_bytes=1234578, added=datetime.now(UTC))
mock_preview_service = mock.MagicMock()
mock_preview_... | Test :const:`.PDFProcess`. | TestCheckPDF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCheckPDF:
"""Test :const:`.PDFProcess`."""
def test_check_successful(self, mock_PreviewService):
"""Source is processed and a preview is present."""
<|body_0|>
def test_check_preview_not_found(self, mock_PreviewService):
"""Source is not processed, and there ... | stack_v2_sparse_classes_75kplus_train_002070 | 22,173 | permissive | [
{
"docstring": "Source is processed and a preview is present.",
"name": "test_check_successful",
"signature": "def test_check_successful(self, mock_PreviewService)"
},
{
"docstring": "Source is not processed, and there is no preview.",
"name": "test_check_preview_not_found",
"signature":... | 2 | null | Implement the Python class `TestCheckPDF` described below.
Class description:
Test :const:`.PDFProcess`.
Method signatures and docstrings:
- def test_check_successful(self, mock_PreviewService): Source is processed and a preview is present.
- def test_check_preview_not_found(self, mock_PreviewService): Source is not ... | Implement the Python class `TestCheckPDF` described below.
Class description:
Test :const:`.PDFProcess`.
Method signatures and docstrings:
- def test_check_successful(self, mock_PreviewService): Source is processed and a preview is present.
- def test_check_preview_not_found(self, mock_PreviewService): Source is not ... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class TestCheckPDF:
"""Test :const:`.PDFProcess`."""
def test_check_successful(self, mock_PreviewService):
"""Source is processed and a preview is present."""
<|body_0|>
def test_check_preview_not_found(self, mock_PreviewService):
"""Source is not processed, and there ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCheckPDF:
"""Test :const:`.PDFProcess`."""
def test_check_successful(self, mock_PreviewService):
"""Source is processed and a preview is present."""
self.submission.is_source_processed = True
self.submission.preview = mock.MagicMock(spec=Preview, source_id=1234, source_checksu... | the_stack_v2_python_sparse | core/arxiv/submission/process/tests.py | arXiv/arxiv-submission-core | train | 14 |
683aa450de08efbc5807f226a4e7b562771af962 | [
"super(LazyProperty, self).__init__()\nself.dependency = depends_on\nself.handlers = WeakKeyDictionary()\nif trait is not None:\n self.default_value_type = trait.default_value_type",
"cache_name = '_%s_lazy_property_cache' % name\ndct = obj.__dict__\nif cache_name not in dct:\n method_name = '_get_%s' % nam... | <|body_start_0|>
super(LazyProperty, self).__init__()
self.dependency = depends_on
self.handlers = WeakKeyDictionary()
if trait is not None:
self.default_value_type = trait.default_value_type
<|end_body_0|>
<|body_start_1|>
cache_name = '_%s_lazy_property_cache' % na... | A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated during component instantiation. | LazyProperty | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazyProperty:
"""A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated during component instantiation."""
... | stack_v2_sparse_classes_75kplus_train_002071 | 20,546 | permissive | [
{
"docstring": "Initialize a LazyProperty. Parameters ---------- trait : TraitType, optional An optional trait type for the values returned by the property. List is required if using extending trait name syntax for e.g. list listeners. depends_on : string, optional The traits notification string for the depende... | 3 | stack_v2_sparse_classes_30k_train_052498 | Implement the Python class `LazyProperty` described below.
Class description:
A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated... | Implement the Python class `LazyProperty` described below.
Class description:
A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated... | 96828b254ac9fdfa2e5b6b31eff93a4933cbc0aa | <|skeleton|>
class LazyProperty:
"""A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated during component instantiation."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LazyProperty:
"""A trait which behaves like a read-only cached property, but which lazily defers binding the dependency notifiers until the first time the value is retrieved. It is used to avoid situations where a property dependency in prematurely evaluated during component instantiation."""
def __init_... | the_stack_v2_python_sparse | enaml/core/trait_types.py | agrawalprash/enaml | train | 0 |
eb3fa2b0bcd7a9623abb8e7934ac851881ead229 | [
"super().__init__(coordinator=coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{coordinator.data.info.serial_number}_{description.key}'",
"try:\n await self.entity_description.press_fn(self.coordinator.client)\nexcept ElgatoError as error:\n raise HomeAssistantError('An error oc... | <|body_start_0|>
super().__init__(coordinator=coordinator)
self.entity_description = description
self._attr_unique_id = f'{coordinator.data.info.serial_number}_{description.key}'
<|end_body_0|>
<|body_start_1|>
try:
await self.entity_description.press_fn(self.coordinator.cli... | Defines an Elgato button. | ElgatoButtonEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElgatoButtonEntity:
"""Defines an Elgato button."""
def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None:
"""Initialize the button entity."""
<|body_0|>
async def async_press(self) -> None:
"""Trigger bu... | stack_v2_sparse_classes_75kplus_train_002072 | 2,840 | permissive | [
{
"docstring": "Initialize the button entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None"
},
{
"docstring": "Trigger button press on the Elgato device.",
"name": "async_press",
"sign... | 2 | null | Implement the Python class `ElgatoButtonEntity` described below.
Class description:
Defines an Elgato button.
Method signatures and docstrings:
- def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None: Initialize the button entity.
- async def async_press(self... | Implement the Python class `ElgatoButtonEntity` described below.
Class description:
Defines an Elgato button.
Method signatures and docstrings:
- def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None: Initialize the button entity.
- async def async_press(self... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ElgatoButtonEntity:
"""Defines an Elgato button."""
def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None:
"""Initialize the button entity."""
<|body_0|>
async def async_press(self) -> None:
"""Trigger bu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElgatoButtonEntity:
"""Defines an Elgato button."""
def __init__(self, coordinator: ElgatoDataUpdateCoordinator, description: ElgatoButtonEntityDescription) -> None:
"""Initialize the button entity."""
super().__init__(coordinator=coordinator)
self.entity_description = description... | the_stack_v2_python_sparse | homeassistant/components/elgato/button.py | home-assistant/core | train | 35,501 |
95400d35d973a11887c6073d57a98c2e27cc9f85 | [
"self.file_system = file_system\nself.name = name\nself.storage_array = storage_array\nself.mtype = mtype",
"if dictionary is None:\n return None\nfile_system = cohesity_management_sdk.models.flash_blade_file_system.FlashBladeFileSystem.from_dictionary(dictionary.get('fileSystem')) if dictionary.get('fileSyste... | <|body_start_0|>
self.file_system = file_system
self.name = name
self.storage_array = storage_array
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
file_system = cohesity_management_sdk.models.flash_blade_file_system.Flas... | Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System information. This is set only when the object type is 'kFileSystem'. name (string): Specifies a ... | FlashBladeProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlashBladeProtectionSource:
"""Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System information. This is set only when the obj... | stack_v2_sparse_classes_75kplus_train_002073 | 3,009 | permissive | [
{
"docstring": "Constructor for the FlashBladeProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, file_system=None, name=None, storage_array=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | stack_v2_sparse_classes_30k_test_001900 | Implement the Python class `FlashBladeProtectionSource` described below.
Class description:
Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System inf... | Implement the Python class `FlashBladeProtectionSource` described below.
Class description:
Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System inf... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FlashBladeProtectionSource:
"""Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System information. This is set only when the obj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlashBladeProtectionSource:
"""Implementation of the 'FlashBladeProtectionSource' model. Specifies a Protection Source in Pure Storage FlashBlade environment. Attributes: file_system (FlashBladeFileSystem): Specifies a Pure Storage FlashBlade File System information. This is set only when the object type is '... | the_stack_v2_python_sparse | cohesity_management_sdk/models/flash_blade_protection_source.py | cohesity/management-sdk-python | train | 24 |
e9865d083f0dfedb17b080a0f9616f88dc18c6eb | [
"toolbox.register('attr_int', random.randint, 0, 1)\ntoolbox.register('individual', tools.initRepeat, creator.Individual, toolbox.attr_int, n=self.n_decoding * len(self.empirical_model.parameters_names()))\ntoolbox.register('evaluate', error_binary, self)\ntoolbox.register('population', tools.initRepeat, list, tool... | <|body_start_0|>
toolbox.register('attr_int', random.randint, 0, 1)
toolbox.register('individual', tools.initRepeat, creator.Individual, toolbox.attr_int, n=self.n_decoding * len(self.empirical_model.parameters_names()))
toolbox.register('evaluate', error_binary, self)
toolbox.register('... | Evolution class using binary representation. | EvolutionBinary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvolutionBinary:
"""Evolution class using binary representation."""
def _individual(self, toolbox):
"""Set individual enconding using binary."""
<|body_0|>
def unscale_parameters_final(self, individual):
"""First convert to float from binary and then unscale para... | stack_v2_sparse_classes_75kplus_train_002074 | 17,432 | no_license | [
{
"docstring": "Set individual enconding using binary.",
"name": "_individual",
"signature": "def _individual(self, toolbox)"
},
{
"docstring": "First convert to float from binary and then unscale parameters.",
"name": "unscale_parameters_final",
"signature": "def unscale_parameters_fina... | 2 | null | Implement the Python class `EvolutionBinary` described below.
Class description:
Evolution class using binary representation.
Method signatures and docstrings:
- def _individual(self, toolbox): Set individual enconding using binary.
- def unscale_parameters_final(self, individual): First convert to float from binary ... | Implement the Python class `EvolutionBinary` described below.
Class description:
Evolution class using binary representation.
Method signatures and docstrings:
- def _individual(self, toolbox): Set individual enconding using binary.
- def unscale_parameters_final(self, individual): First convert to float from binary ... | cc81edc2d9cb5f4c281b186a7a32888ced1c6904 | <|skeleton|>
class EvolutionBinary:
"""Evolution class using binary representation."""
def _individual(self, toolbox):
"""Set individual enconding using binary."""
<|body_0|>
def unscale_parameters_final(self, individual):
"""First convert to float from binary and then unscale para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvolutionBinary:
"""Evolution class using binary representation."""
def _individual(self, toolbox):
"""Set individual enconding using binary."""
toolbox.register('attr_int', random.randint, 0, 1)
toolbox.register('individual', tools.initRepeat, creator.Individual, toolbox.attr_int... | the_stack_v2_python_sparse | pkp/evolution.py | mighelone/pkpcoal | train | 3 |
67a73320bcec5dabe5f7f5919ea4e7df3aa0289f | [
"super().__init__()\nassert len(bitmap) <= window_size, 'You cannot specified more bitmap than windows'\nself.bitmap = bitmap\nself.window_size = window_size\nself.size = len(bitmap)\nreturn",
"out = ''\nfor bit in self.bitmap:\n if bit:\n out += '1'\n else:\n out += '0'\nreturn out",
"if se... | <|body_start_0|>
super().__init__()
assert len(bitmap) <= window_size, 'You cannot specified more bitmap than windows'
self.bitmap = bitmap
self.window_size = window_size
self.size = len(bitmap)
return
<|end_body_0|>
<|body_start_1|>
out = ''
for bit in s... | Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization | CompressedBitmap | [
"LicenseRef-scancode-ietf-trust",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : Lis... | stack_v2_sparse_classes_75kplus_train_002075 | 2,011 | permissive | [
{
"docstring": "Compressed Bitmap constructor Parameters ---------- bitmap : List[bool] Bitmap, it has to have a length of at most window size window_size : int Size of window",
"name": "__init__",
"signature": "def __init__(self, bitmap, window_size)"
},
{
"docstring": "Returns the bytes repres... | 3 | stack_v2_sparse_classes_30k_train_045129 | Implement the Python class `CompressedBitmap` described below.
Class description:
Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization
Method signatures and docstrings:
- def __init__(self, bitmap, window_size): Compres... | Implement the Python class `CompressedBitmap` described below.
Class description:
Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization
Method signatures and docstrings:
- def __init__(self, bitmap, window_size): Compres... | 2b1d9ed7d7c9857cbb362bdee5c77f7234838ddd | <|skeleton|>
class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : Lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompressedBitmap:
"""Compressed Bitmap Class Attributes ---------- bitmap : List[bool] Bitmap of tile send in a window window_size : int WINDOW SIZE given on initialization"""
def __init__(self, bitmap, window_size):
"""Compressed Bitmap constructor Parameters ---------- bitmap : List[bool] Bitma... | the_stack_v2_python_sparse | fragmentation_layer/code/schc_messages/schc_header/compressed_bitmap.py | CristianWulfing/PySCHC | train | 0 |
dbb50fd1ea93ee7b5d369d25c3eb98016d8c1d5b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CalendarSharingMessageAction()",
"from .calendar_sharing_action import CalendarSharingAction\nfrom .calendar_sharing_action_importance import CalendarSharingActionImportance\nfrom .calendar_sharing_action_type import CalendarSharingAct... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CalendarSharingMessageAction()
<|end_body_0|>
<|body_start_1|>
from .calendar_sharing_action import CalendarSharingAction
from .calendar_sharing_action_importance import CalendarSharingA... | CalendarSharingMessageAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarSharingMessageAction:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarSharingMessageAction:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value... | stack_v2_sparse_classes_75kplus_train_002076 | 3,763 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: CalendarSharingMessageAction",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_train_045883 | Implement the Python class `CalendarSharingMessageAction` described below.
Class description:
Implement the CalendarSharingMessageAction class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarSharingMessageAction: Creates a new instance of the a... | Implement the Python class `CalendarSharingMessageAction` described below.
Class description:
Implement the CalendarSharingMessageAction class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarSharingMessageAction: Creates a new instance of the a... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CalendarSharingMessageAction:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarSharingMessageAction:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalendarSharingMessageAction:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarSharingMessageAction:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | the_stack_v2_python_sparse | msgraph/generated/models/calendar_sharing_message_action.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
2b25b68905da913bf8ca1696a312b4c893948d34 | [
"res = dict()\nres[KeyPair.DICT_PUBLIC_KEY] = key_pair.public\nres[KeyPair.DICT_SECRET_KEY] = key_pair.secret\nreturn res",
"if KeyPair.DICT_PUBLIC_KEY not in data:\n raise ParseError(\"required key '\" + KeyPair.DICT_PUBLIC_KEY + \"' is missing\")\nif KeyPair.DICT_SECRET_KEY not in data:\n raise ParseError... | <|body_start_0|>
res = dict()
res[KeyPair.DICT_PUBLIC_KEY] = key_pair.public
res[KeyPair.DICT_SECRET_KEY] = key_pair.secret
return res
<|end_body_0|>
<|body_start_1|>
if KeyPair.DICT_PUBLIC_KEY not in data:
raise ParseError("required key '" + KeyPair.DICT_PUBLIC_KEY ... | Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret. | KeyPairSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After ... | stack_v2_sparse_classes_75kplus_train_002077 | 1,532 | permissive | [
{
"docstring": "Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After that, the dict may be persisted and deserialized later. For example, the dict representation may be converted into JSON using the standard json library.",
"name": "as_dict",
"signature": "def as_dic... | 2 | stack_v2_sparse_classes_30k_train_014560 | Implement the Python class `KeyPairSerializer` described below.
Class description:
Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret.
Method signatures and docstrings:
- def as_dict(self, key_pair: KeyPair) -> dict: Transforms a KeyPair into a dicti... | Implement the Python class `KeyPairSerializer` described below.
Class description:
Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret.
Method signatures and docstrings:
- def as_dict(self, key_pair: KeyPair) -> dict: Transforms a KeyPair into a dicti... | b5e7489eff3e65d2e7d802802afd0dd38ddd2e96 | <|skeleton|>
class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyPairSerializer:
"""Can be used to serialize and deserialize a KeyPair derived alias such as an AccountSecret instance or an AddressSecret."""
def as_dict(self, key_pair: KeyPair) -> dict:
"""Transforms a KeyPair into a dictionary that contains all attributes of the KeyPair. After that, the dic... | the_stack_v2_python_sparse | waves_gateway/serializer/key_pair_serializer.py | jansenmarc/WavesGatewayFramework | train | 26 |
093a863cb41b3fbf75196ad2afac399a126f68c0 | [
"self._start = None\nself._end = None\nself._secs = None\nself._msecs = None\nself._running = False",
"self._start = time.time()\nself._running = True\nself._end = None\nself._secs = None\nself._msecs = None",
"self._start = time.time()\nself._end = None\nself._secs = None\nself._msecs = None",
"if self._runn... | <|body_start_0|>
self._start = None
self._end = None
self._secs = None
self._msecs = None
self._running = False
<|end_body_0|>
<|body_start_1|>
self._start = time.time()
self._running = True
self._end = None
self._secs = None
self._msecs =... | Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch. | Stopwatch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
<|body_0|>
def start(self):
"""Mark current time as the starting time.""... | stack_v2_sparse_classes_75kplus_train_002078 | 2,432 | permissive | [
{
"docstring": "Create and initialize a Stopwatch.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Mark current time as the starting time.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Reset the timer to zero. This doesn't stop th... | 6 | stack_v2_sparse_classes_30k_test_000995 | Implement the Python class `Stopwatch` described below.
Class description:
Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch.
Method signatures and docstrings:
- def __init__(self): Create and initialize a Stopwatch.
- def start(self): Mark current time as... | Implement the Python class `Stopwatch` described below.
Class description:
Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch.
Method signatures and docstrings:
- def __init__(self): Create and initialize a Stopwatch.
- def start(self): Mark current time as... | 9b5e355d79642e9b5998031872ec0ee2f1a6f08d | <|skeleton|>
class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
<|body_0|>
def start(self):
"""Mark current time as the starting time.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
self._start = None
self._end = None
self._secs = None
self._msecs = None
... | the_stack_v2_python_sparse | src/stopwatch.py | TechnoJays/robot2018 | train | 0 |
d45662f4dd4be5a127e11579b8d510877b610a82 | [
"self.ss = ss\nself.n_step = n_step\nself.mu = mu\nself.sigma = sigma\nself.step_time = step_time",
"step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)])\nu = np.zeros(shape=dim)\nj = 0\nfor i in range(len(t)):\n if t[i] % self.step_time == 0 and t[i] != 0 and (j + 1 != len(... | <|body_start_0|>
self.ss = ss
self.n_step = n_step
self.mu = mu
self.sigma = sigma
self.step_time = step_time
<|end_body_0|>
<|body_start_1|>
step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)])
u = np.zeros(shape=dim)
... | GaussStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set... | stack_v2_sparse_classes_75kplus_train_002079 | 8,036 | no_license | [
{
"docstring": "Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set.",
"name": "__init__",
"signature": "def __init__(self, step_time, mu=None, sigma=None,... | 2 | stack_v2_sparse_classes_30k_train_029294 | Implement the Python class `GaussStep` described below.
Class description:
Implement the GaussStep class.
Method signatures and docstrings:
- def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None): Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step chan... | Implement the Python class `GaussStep` described below.
Class description:
Implement the GaussStep class.
Method signatures and docstrings:
- def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None): Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step chan... | cf548475295f25407ba968546c2fc85c26f9343c | <|skeleton|>
class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set."""
s... | the_stack_v2_python_sparse | SourceCode/simulation/signal.py | martin-bachorik/Master-Thesis-Project | train | 0 | |
a435e7f9e41df576c7d3988c7958dc4c57f699dc | [
"super(self.__class__, self).__init__()\nself.logger = logging.getLogger(__name__ + '.Fullmonty')\nself.logger.addHandler(logging.NullHandler())\nself.dannet = Dannet()\nself.gutenberg = Gutenberg()\nself.lcc = LCC()\nself.europarl = Europarl()",
"self.logger.info('Downloading all corpora')\nself.dannet.download(... | <|body_start_0|>
super(self.__class__, self).__init__()
self.logger = logging.getLogger(__name__ + '.Fullmonty')
self.logger.addHandler(logging.NullHandler())
self.dannet = Dannet()
self.gutenberg = Gutenberg()
self.lcc = LCC()
self.europarl = Europarl()
<|end_bod... | All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl. | Fullmonty | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fullmonty:
"""All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl."""
def __init__(self):
"""Set up objects for logger and corpora."""
<|body_0|>
def download(self):
"""Download all corpora."""
<|bo... | stack_v2_sparse_classes_75kplus_train_002080 | 14,008 | permissive | [
{
"docstring": "Set up objects for logger and corpora.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Download all corpora.",
"name": "download",
"signature": "def download(self)"
},
{
"docstring": "Iterate over sentences from all corpora. Yields -----... | 3 | stack_v2_sparse_classes_30k_train_029692 | Implement the Python class `Fullmonty` described below.
Class description:
All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl.
Method signatures and docstrings:
- def __init__(self): Set up objects for logger and corpora.
- def download(self): Download all cor... | Implement the Python class `Fullmonty` described below.
Class description:
All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl.
Method signatures and docstrings:
- def __init__(self): Set up objects for logger and corpora.
- def download(self): Download all cor... | d8d1c5e68aedf758aee1ba83da063f1e0952c21d | <|skeleton|>
class Fullmonty:
"""All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl."""
def __init__(self):
"""Set up objects for logger and corpora."""
<|body_0|>
def download(self):
"""Download all corpora."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fullmonty:
"""All corpora. The corpora included in the Fullmonty aggregated corpora ae Dannet, Gutenberg, LCC and Europarl."""
def __init__(self):
"""Set up objects for logger and corpora."""
super(self.__class__, self).__init__()
self.logger = logging.getLogger(__name__ + '.Fullm... | the_stack_v2_python_sparse | dasem/fullmonty.py | eaksnes/dasem | train | 0 |
2bcfec2a764d234385faf327fccf4d72f014f64d | [
"try:\n return super().getTerm(value)\nexcept LookupError:\n if self._can_query_current_value():\n if value in self._query_current_value():\n return self._make_missing_term(value)\n raise",
"try:\n return super().getTermByToken(token)\nexcept LookupError:\n if self._can_query_curr... | <|body_start_0|>
try:
return super().getTerm(value)
except LookupError:
if self._can_query_current_value():
if value in self._query_current_value():
return self._make_missing_term(value)
raise
<|end_body_0|>
<|body_start_1|>
... | `MissingTermsMixin` adapted to collections. | MissingCollectionTermsMixin | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MissingCollectionTermsMixin:
"""`MissingTermsMixin` adapted to collections."""
def getTerm(self, value):
"""Get term matching given value"""
<|body_0|>
def getTermByToken(self, token):
"""Get term matching given token"""
<|body_1|>
def getValue(self,... | stack_v2_sparse_classes_75kplus_train_002081 | 11,899 | permissive | [
{
"docstring": "Get term matching given value",
"name": "getTerm",
"signature": "def getTerm(self, value)"
},
{
"docstring": "Get term matching given token",
"name": "getTermByToken",
"signature": "def getTermByToken(self, token)"
},
{
"docstring": "Get value matching given token... | 3 | stack_v2_sparse_classes_30k_train_007407 | Implement the Python class `MissingCollectionTermsMixin` described below.
Class description:
`MissingTermsMixin` adapted to collections.
Method signatures and docstrings:
- def getTerm(self, value): Get term matching given value
- def getTermByToken(self, token): Get term matching given token
- def getValue(self, tok... | Implement the Python class `MissingCollectionTermsMixin` described below.
Class description:
`MissingTermsMixin` adapted to collections.
Method signatures and docstrings:
- def getTerm(self, value): Get term matching given value
- def getTermByToken(self, token): Get term matching given token
- def getValue(self, tok... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class MissingCollectionTermsMixin:
"""`MissingTermsMixin` adapted to collections."""
def getTerm(self, value):
"""Get term matching given value"""
<|body_0|>
def getTermByToken(self, token):
"""Get term matching given token"""
<|body_1|>
def getValue(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MissingCollectionTermsMixin:
"""`MissingTermsMixin` adapted to collections."""
def getTerm(self, value):
"""Get term matching given value"""
try:
return super().getTerm(value)
except LookupError:
if self._can_query_current_value():
if value ... | the_stack_v2_python_sparse | src/pyams_form/term.py | Py-AMS/pyams-form | train | 0 |
0ce35f4a37ef0f9b0bc791242bb3dc0e16daf286 | [
"self._compute = compute_client.apitools_client\nself._messages = compute_client.messages\nself._http = compute_client.apitools_client.http\nself._batch_url = compute_client.batch_url",
"errors = []\nrequests = []\nzone_names = set()\nfor resource_ref in resource_refs:\n if resource_ref.zone not in zone_names:... | <|body_start_0|>
self._compute = compute_client.apitools_client
self._messages = compute_client.messages
self._http = compute_client.apitools_client.http
self._batch_url = compute_client.batch_url
<|end_body_0|>
<|body_start_1|>
errors = []
requests = []
zone_nam... | A (small) collection of utils for working with zones. | ZoneResourceFetcher | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneResourceFetcher:
"""A (small) collection of utils for working with zones."""
def __init__(self, compute_client):
"""Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derive... | stack_v2_sparse_classes_75kplus_train_002082 | 4,350 | permissive | [
{
"docstring": "Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on \"base_classes\" class layout (properties side-derived from one of base_class class). This function can be used to avoid unfeasible inheritance and use composition instead when refact... | 3 | stack_v2_sparse_classes_30k_train_042796 | Implement the Python class `ZoneResourceFetcher` described below.
Class description:
A (small) collection of utils for working with zones.
Method signatures and docstrings:
- def __init__(self, compute_client): Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class dependi... | Implement the Python class `ZoneResourceFetcher` described below.
Class description:
A (small) collection of utils for working with zones.
Method signatures and docstrings:
- def __init__(self, compute_client): Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class dependi... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class ZoneResourceFetcher:
"""A (small) collection of utils for working with zones."""
def __init__(self, compute_client):
"""Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derive... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZoneResourceFetcher:
"""A (small) collection of utils for working with zones."""
def __init__(self, compute_client):
"""Instantiate ZoneResourceFetcher and embed all required data into it. ZoneResourceFetcher is a class depending on "base_classes" class layout (properties side-derived from one of... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/zone_utils.py | KaranToor/MA450 | train | 1 |
30d16061e5d35c0b7cf7061e9787f9bf524500e9 | [
"self.current_shoot_params = {'video_file': '', 'audio_file': '', 'merged_file': ''}\nself.current_shot_params = {'file': ''}\nself.current_video_file = ''\nself.current_audio_file = ''\nself.current_merged_file = ''\nself.shoot_formats = {'video': shoot_formats[0], 'audio': shoot_formats[1], 'merged': shoot_format... | <|body_start_0|>
self.current_shoot_params = {'video_file': '', 'audio_file': '', 'merged_file': ''}
self.current_shot_params = {'file': ''}
self.current_video_file = ''
self.current_audio_file = ''
self.current_merged_file = ''
self.shoot_formats = {'video': shoot_format... | Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_system.recordation.RecordManager.merge_audio_and_video` for merging separate au... | Recorder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Recorder:
"""Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_system.recordation.RecordManager.merge_audi... | stack_v2_sparse_classes_75kplus_train_002083 | 18,130 | permissive | [
{
"docstring": "Initialization method of :class:`t_system.recordation.Recorder` class. Args: shot_format (str): Format of the shot. (jpg, png etc.) shoot_formats (list): Formats of the records for video, audio and merged. camera: Camera object from PiCamera. hearer: Hearer object.",
"name": "__init__",
... | 6 | stack_v2_sparse_classes_30k_train_005937 | Implement the Python class `Recorder` described below.
Class description:
Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_syst... | Implement the Python class `Recorder` described below.
Class description:
Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_syst... | 4cf34572b8f8eac54d6c339f37aa72b6a13d8934 | <|skeleton|>
class Recorder:
"""Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_system.recordation.RecordManager.merge_audi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Recorder:
"""Class to define a recording ability of tracking system. This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start` for creating a Record object and start recording by this object. :func:`t_system.recordation.RecordManager.merge_audio_and_video` ... | the_stack_v2_python_sparse | t_system/recordation.py | LookAtMe-Genius-Cameraman/T_System | train | 9 |
a6d68402552c6ddd6b515754cc9c29aa1bbcb9a4 | [
"self.numsDict = {num: [] for num in nums}\nfor index, num in enumerate(nums):\n self.numsDict[num].append(index)",
"result = None\nfor curRandomNumber in range(len(self.numsDict[target])):\n if random.randint(0, curRandomNumber) == 0:\n result = self.numsDict[target][curRandomNumber]\nreturn result"... | <|body_start_0|>
self.numsDict = {num: [] for num in nums}
for index, num in enumerate(nums):
self.numsDict[num].append(index)
<|end_body_0|>
<|body_start_1|>
result = None
for curRandomNumber in range(len(self.numsDict[target])):
if random.randint(0, curRandomNu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.numsDict = {num: [] for num in nums}
... | stack_v2_sparse_classes_75kplus_train_002084 | 753 | no_license | [
{
"docstring": ":type nums: List[int] :type numsSize: int",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type target: int :rtype: int",
"name": "pick",
"signature": "def pick(self, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032991 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int
<|skeleton|>
class Solution:
def __init__(self, ... | e05f29071d0badd081535e773f43ebc303aa12c4 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
self.numsDict = {num: [] for num in nums}
for index, num in enumerate(nums):
self.numsDict[num].append(index)
def pick(self, target):
""":type target: int :rtype: int"""
... | the_stack_v2_python_sparse | LeetCode/Reservoir Sampling/398_RandomPickIndex.py | HzCeee/Algorithms | train | 0 | |
6ac07c440b6a0da505d0dd13e6aedcbbebf44b5b | [
"if not root:\n return True\nqueue = []\nqueue.append(root)\nresult = True\nwhile queue and result:\n len_level = len(queue)\n result = self.is_equal(queue[:len_level], queue[:len_level][::-1])\n for i in range(len_level):\n cur = queue.pop(0)\n if not cur:\n continue\n q... | <|body_start_0|>
if not root:
return True
queue = []
queue.append(root)
result = True
while queue and result:
len_level = len(queue)
result = self.is_equal(queue[:len_level], queue[:len_level][::-1])
for i in range(len_level):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def test(self, root):
"""非递归"""
<|body_0|>
def is_equal(self, list1, list2):
"""判断两个节点列表的值是否相等"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return True
queue = []
queue.append(root)
resul... | stack_v2_sparse_classes_75kplus_train_002085 | 1,850 | no_license | [
{
"docstring": "非递归",
"name": "test",
"signature": "def test(self, root)"
},
{
"docstring": "判断两个节点列表的值是否相等",
"name": "is_equal",
"signature": "def is_equal(self, list1, list2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052029 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def test(self, root): 非递归
- def is_equal(self, list1, list2): 判断两个节点列表的值是否相等 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def test(self, root): 非递归
- def is_equal(self, list1, list2): 判断两个节点列表的值是否相等
<|skeleton|>
class Solution:
def test(self, root):
"""非递归"""
<|body_0|>
de... | ef6aee94c7990d734271c204034ec273b665226d | <|skeleton|>
class Solution:
def test(self, root):
"""非递归"""
<|body_0|>
def is_equal(self, list1, list2):
"""判断两个节点列表的值是否相等"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def test(self, root):
"""非递归"""
if not root:
return True
queue = []
queue.append(root)
result = True
while queue and result:
len_level = len(queue)
result = self.is_equal(queue[:len_level], queue[:len_level][::-1])
... | the_stack_v2_python_sparse | 剑指offer/对称二叉树.py | godzzbboss/leetcode | train | 0 | |
5effff3b30bdb1760d1beddee302f81d64b7cb59 | [
"self.scores = scores\nself.sequences = sequences\nself.superpositions = superpositions\nself.tm = scores['TM']\nself.length = scores['length']\nself.rmsd = scores['rmsd']\nself.seqid = scores['seqid']",
"if self.superpositions is None:\n return None\nif not all_regions and (not all_atoms):\n return self.su... | <|body_start_0|>
self.scores = scores
self.sequences = sequences
self.superpositions = superpositions
self.tm = scores['TM']
self.length = scores['length']
self.rmsd = scores['rmsd']
self.seqid = scores['seqid']
<|end_body_0|>
<|body_start_1|>
if self.sup... | Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned region. :ivar sequences: Tuple of sequences (chain 1, map, chain 2) | Result | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Result:
"""Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned region. :ivar sequences: Tuple of seque... | stack_v2_sparse_classes_75kplus_train_002086 | 12,398 | no_license | [
{
"docstring": "Construct a new Result. :param tuple scores: Dictionary of scores produced by TMAlign. :param tuple sequences: Tuple of sequences produced by TMAlign. :param tuple superpositions: Tuple of superpositions produced by TMAlign.",
"name": "__init__",
"signature": "def __init__(self, scores, ... | 3 | null | Implement the Python class `Result` described below.
Class description:
Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned ... | Implement the Python class `Result` described below.
Class description:
Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned ... | b029078dd871c9b95573b4fc31ca7b25dcecbad9 | <|skeleton|>
class Result:
"""Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned region. :ivar sequences: Tuple of seque... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Result:
"""Represents an alignment between two structures produced by TMalign. :ivar tm: Tuple of TM-scores (normalised by chain 1 and 2) :ivar length: Tuple of chain lengths. :ivar rmsd: RMSD over aligned region. :ivar seqid: Sequence identity over aligned region. :ivar sequences: Tuple of sequences (chain 1... | the_stack_v2_python_sparse | phyre_engine/tools/strucaln.py | PhyreEngine/phyre_engine | train | 0 |
958988360ac67288121bb5501351a043ac22d0b1 | [
"PuckDetectorCore.__init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster)\nself.m_displayOutput = i_displayOutput\nself.xPosInPixels = 0\nself.yPosInPixels = 0\nself.xPosInMeters = 0\nself.yPosInMeters = 0\nself.newInfo = False\nself.m_dimensionsConverter = i_dimensionsConverter",
"if i_puck... | <|body_start_0|>
PuckDetectorCore.__init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster)
self.m_displayOutput = i_displayOutput
self.xPosInPixels = 0
self.yPosInPixels = 0
self.xPosInMeters = 0
self.yPosInMeters = 0
self.newInfo = False
... | PuckDetector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the las... | stack_v2_sparse_classes_75kplus_train_002087 | 3,210 | permissive | [
{
"docstring": "PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the last known center of the puck Args: i_lowerColor: HSV values of the lower threshold used to identify the puck i_upperColor: HSV values of the Upper threshol... | 4 | stack_v2_sparse_classes_30k_train_014799 | Implement the Python class `PuckDetector` described below.
Class description:
Implement the PuckDetector class.
Method signatures and docstrings:
- def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True): PuckDetector class's constructor. Initiali... | Implement the Python class `PuckDetector` described below.
Class description:
Implement the PuckDetector class.
Method signatures and docstrings:
- def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True): PuckDetector class's constructor. Initiali... | 2130b462b0038a527061744ab7faf20c2996c04f | <|skeleton|>
class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the las... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PuckDetector:
def __init__(self, i_lowerColor, i_upperColor, i_radius, i_camera, i_broadcaster, i_dimensionsConverter, i_displayOutput=True):
"""PuckDetector class's constructor. Initializes, notably, self.xPosInPixels and self.yPosInPixels, that are attributes that correspond to the last known center... | the_stack_v2_python_sparse | vision/src/VisionPuckDetector/PuckDetector.py | victoriapc/HockusPockus | train | 0 | |
a4a2b61f7256a340878c334d9f742878b57ac30c | [
"self.Tmin = 300.0\nself.Tmax = 3000.0\nself.Pmin = 0.1\nself.Pmax = 100.0\nself.comment = 'foo bar'\nself.uncertainty = RateUncertainty(mu=0.3, var=0.6, Tref=1000.0, N=1, correlation='ab')\nself.km = KineticsModel(Tmin=(self.Tmin, 'K'), Tmax=(self.Tmax, 'K'), Pmin=(self.Pmin, 'bar'), Pmax=(self.Pmax, 'bar'), uncer... | <|body_start_0|>
self.Tmin = 300.0
self.Tmax = 3000.0
self.Pmin = 0.1
self.Pmax = 100.0
self.comment = 'foo bar'
self.uncertainty = RateUncertainty(mu=0.3, var=0.6, Tref=1000.0, N=1, correlation='ab')
self.km = KineticsModel(Tmin=(self.Tmin, 'K'), Tmax=(self.Tmax,... | Contains unit tests of the KineticsModel class | TestKineticsModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestKineticsModel:
"""Contains unit tests of the KineticsModel class"""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_is_identical_to(self):
"""Test that the KineticsModel.is_identical_to method works on itself. Th... | stack_v2_sparse_classes_75kplus_train_002088 | 7,835 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the KineticsModel.is_identical_to method works on itself. This just checks the Temperature range",
"name": "test_is_identical_to",
"signature... | 4 | stack_v2_sparse_classes_30k_train_005478 | Implement the Python class `TestKineticsModel` described below.
Class description:
Contains unit tests of the KineticsModel class
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_is_identical_to(self): Test that the KineticsModel.is_identical_to metho... | Implement the Python class `TestKineticsModel` described below.
Class description:
Contains unit tests of the KineticsModel class
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_is_identical_to(self): Test that the KineticsModel.is_identical_to metho... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestKineticsModel:
"""Contains unit tests of the KineticsModel class"""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_is_identical_to(self):
"""Test that the KineticsModel.is_identical_to method works on itself. Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestKineticsModel:
"""Contains unit tests of the KineticsModel class"""
def setUp(self):
"""A function run before each unit test in this class."""
self.Tmin = 300.0
self.Tmax = 3000.0
self.Pmin = 0.1
self.Pmax = 100.0
self.comment = 'foo bar'
self.u... | the_stack_v2_python_sparse | rmgpy/kinetics/modelTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
a508299d1240fe746044a8a7b76303e7740db4fc | [
"self.index = defaultdict(list)\nfor i, word in enumerate(words):\n self.index[word].append(i)",
"index1, index2 = (self.index[word1], self.index[word2])\nmin_distance = abs(index1[0] - index2[0])\ni = j = 0\nwhile i < len(index1) and j < len(index2):\n min_distance = min(min_distance, abs(index1[i] - index... | <|body_start_0|>
self.index = defaultdict(list)
for i, word in enumerate(words):
self.index[word].append(i)
<|end_body_0|>
<|body_start_1|>
index1, index2 = (self.index[word1], self.index[word2])
min_distance = abs(index1[0] - index2[0])
i = j = 0
while i < l... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_002089 | 1,492 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_test_000617 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 086b7c9b3651a0e70c5794f6c264eb975cc90363 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.index = defaultdict(list)
for i, word in enumerate(words):
self.index[word].append(i)
def shortest(self, word1, word2):
"""Adds a word into the data ... | the_stack_v2_python_sparse | shortest_word_distance_ii.py | chunweiliu/leetcode2 | train | 4 | |
38f0c71dcef5d9f1d7ec529cbc9c995e9fc4b45a | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.bttn1 = Button(self, text='I do nothing!')\nself.bttn1.grid()\nself.bttn2 = Button(self)\nself.bttn2.grid()\nself.bttn2.configure(text='Me too!')\nself.bttn3 = Button(self)\nself.bttn3.grid()\nself.bttn3['text'] = 'The same thi... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.bttn1 = Button(self, text='I do nothing!')
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.configure... | Application based on GUI with three buttons. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application based on GUI with three buttons."""
def __init__(self, master):
"""Initialize frame."""
<|body_0|>
def create_widgets(self):
"""Create three buttons which do nothing."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_75kplus_train_002090 | 1,424 | no_license | [
{
"docstring": "Initialize frame.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create three buttons which do nothing.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002611 | Implement the Python class `Application` described below.
Class description:
Application based on GUI with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize frame.
- def create_widgets(self): Create three buttons which do nothing. | Implement the Python class `Application` described below.
Class description:
Application based on GUI with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize frame.
- def create_widgets(self): Create three buttons which do nothing.
<|skeleton|>
class Application:
"""Applica... | 120e2d62468a085424ec71a22effe27d6b38b548 | <|skeleton|>
class Application:
"""Application based on GUI with three buttons."""
def __init__(self, master):
"""Initialize frame."""
<|body_0|>
def create_widgets(self):
"""Create three buttons which do nothing."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Application based on GUI with three buttons."""
def __init__(self, master):
"""Initialize frame."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create three buttons which do nothing."... | the_stack_v2_python_sparse | Chapter 10/lazy_buttons_2.py | MartaSzuran/Python-for-the-Absolute-Beginner-M.Dawson | train | 1 |
50d72682001410c35cca31dec85e12b1c56c21b3 | [
"sampler_vals = [kwargs.pop(name) for name in property_names]\nsuper().__init__(grad=grad, **kwargs)\nself.augment_fn = augment_fn\nself.keys = keys\nself.property_names = property_names\nself.args = args\nself.kwargs = kwargs\nfor name, val in zip(property_names, sampler_vals):\n self.register_sampler(name, val... | <|body_start_0|>
sampler_vals = [kwargs.pop(name) for name in property_names]
super().__init__(grad=grad, **kwargs)
self.augment_fn = augment_fn
self.keys = keys
self.property_names = property_names
self.args = args
self.kwargs = kwargs
for name, val in zi... | Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key. | BaseTransform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTransform:
"""Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key."""
def __init__(self, augment_fn: augment_callable, *args, keys: S... | stack_v2_sparse_classes_75kplus_train_002091 | 8,879 | permissive | [
{
"docstring": "Args: augment_fn: function for augmentation *args: positional arguments passed to augment_fn keys: keys which should be augmented grad: enable gradient computation inside transformation property_names: a tuple containing all the properties to call during forward pass **kwargs: keyword arguments ... | 2 | null | Implement the Python class `BaseTransform` described below.
Class description:
Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key.
Method signatures and docstring... | Implement the Python class `BaseTransform` described below.
Class description:
Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key.
Method signatures and docstring... | ab6fbcfe7215c2a5b8e401b70909f6a32d0d167b | <|skeleton|>
class BaseTransform:
"""Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key."""
def __init__(self, augment_fn: augment_callable, *args, keys: S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseTransform:
"""Transform to apply a functional interface to given keys .. warning:: This transform should not be used with functions which have randomness build in because it will result in different augmentations per key."""
def __init__(self, augment_fn: augment_callable, *args, keys: Sequence=('dat... | the_stack_v2_python_sparse | rising/transforms/abstract.py | PhoenixDL/rising | train | 318 |
34d5e98202e1827b805e81bbc636716e46e973c7 | [
"self.browser.get(self.server_url + reverse('login'))\nusername_field = self.browser.find_element_by_name('username')\nusername_field.send_keys('edith')\npassword_field = self.browser.find_element_by_name('password')\npassword_field.send_keys('password')\npassword_field.send_keys(Keys.RETURN)\nself.browser.get(self... | <|body_start_0|>
self.browser.get(self.server_url + reverse('login'))
username_field = self.browser.find_element_by_name('username')
username_field.send_keys('edith')
password_field = self.browser.find_element_by_name('password')
password_field.send_keys('password')
passw... | LoginUserTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginUserTest:
def test_user_can_login_with_valid_credentials(self):
"""Test for checking if user can login with valid credentials"""
<|body_0|>
def test_user_cannot_login_with_INVALID_credentials(self):
"""Test for checking if user cannot login with INVALID credenti... | stack_v2_sparse_classes_75kplus_train_002092 | 1,855 | no_license | [
{
"docstring": "Test for checking if user can login with valid credentials",
"name": "test_user_can_login_with_valid_credentials",
"signature": "def test_user_can_login_with_valid_credentials(self)"
},
{
"docstring": "Test for checking if user cannot login with INVALID credentials",
"name": ... | 2 | stack_v2_sparse_classes_30k_test_001121 | Implement the Python class `LoginUserTest` described below.
Class description:
Implement the LoginUserTest class.
Method signatures and docstrings:
- def test_user_can_login_with_valid_credentials(self): Test for checking if user can login with valid credentials
- def test_user_cannot_login_with_INVALID_credentials(s... | Implement the Python class `LoginUserTest` described below.
Class description:
Implement the LoginUserTest class.
Method signatures and docstrings:
- def test_user_can_login_with_valid_credentials(self): Test for checking if user can login with valid credentials
- def test_user_cannot_login_with_INVALID_credentials(s... | 48826b70da4363197f7a9e8c6fefdcc708527a99 | <|skeleton|>
class LoginUserTest:
def test_user_can_login_with_valid_credentials(self):
"""Test for checking if user can login with valid credentials"""
<|body_0|>
def test_user_cannot_login_with_INVALID_credentials(self):
"""Test for checking if user cannot login with INVALID credenti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginUserTest:
def test_user_can_login_with_valid_credentials(self):
"""Test for checking if user can login with valid credentials"""
self.browser.get(self.server_url + reverse('login'))
username_field = self.browser.find_element_by_name('username')
username_field.send_keys('ed... | the_stack_v2_python_sparse | functional_tests/test_login_user.py | drager/toerh | train | 0 | |
9786a2bd63d93bb0b74875db0aabc863d984a1c8 | [
"with StdOutRedirector():\n self.assertEqual(distance([1, 2, 3, 4], [1, 1]), None)\n self.assertEqual(sys.stdout.getvalue(), 'ERROR: two lists of 2 elements expected, got 4, 2.\\n')",
"with StdOutRedirector():\n self.assertEqual(distance([1, 1], 'a'), None)\n self.assertEqual(sys.stdout.getvalue(), \"... | <|body_start_0|>
with StdOutRedirector():
self.assertEqual(distance([1, 2, 3, 4], [1, 1]), None)
self.assertEqual(sys.stdout.getvalue(), 'ERROR: two lists of 2 elements expected, got 4, 2.\n')
<|end_body_0|>
<|body_start_1|>
with StdOutRedirector():
self.assertEqual(... | This test case contains the negative tests for the function distance from module area_counter. | NegativeTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NegativeTests:
"""This test case contains the negative tests for the function distance from module area_counter."""
def test_too_many_coordinates_for_the_dot(self):
"""This test checks if function correctly deals with the incorrect input data - too many coordinates for the first dot.... | stack_v2_sparse_classes_75kplus_train_002093 | 3,189 | no_license | [
{
"docstring": "This test checks if function correctly deals with the incorrect input data - too many coordinates for the first dot.",
"name": "test_too_many_coordinates_for_the_dot",
"signature": "def test_too_many_coordinates_for_the_dot(self)"
},
{
"docstring": "This test checks if function c... | 5 | null | Implement the Python class `NegativeTests` described below.
Class description:
This test case contains the negative tests for the function distance from module area_counter.
Method signatures and docstrings:
- def test_too_many_coordinates_for_the_dot(self): This test checks if function correctly deals with the incor... | Implement the Python class `NegativeTests` described below.
Class description:
This test case contains the negative tests for the function distance from module area_counter.
Method signatures and docstrings:
- def test_too_many_coordinates_for_the_dot(self): This test checks if function correctly deals with the incor... | 023307a9b7f7f8dbb1589e222e794e128f1f365b | <|skeleton|>
class NegativeTests:
"""This test case contains the negative tests for the function distance from module area_counter."""
def test_too_many_coordinates_for_the_dot(self):
"""This test checks if function correctly deals with the incorrect input data - too many coordinates for the first dot.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NegativeTests:
"""This test case contains the negative tests for the function distance from module area_counter."""
def test_too_many_coordinates_for_the_dot(self):
"""This test checks if function correctly deals with the incorrect input data - too many coordinates for the first dot."""
w... | the_stack_v2_python_sparse | HW11/test_for_function_distance.py | Goopard/Study-2 | train | 0 |
e1c5109b542a581899d1684cb2889faeeb61edd7 | [
"super(Repoquery, self).__init__(None)\nself.name = name\nself.query_type = query_type\nself.show_duplicates = show_duplicates\nself.match_version = match_version\nself.ignore_excluders = ignore_excluders\nself.verbose = verbose\nif self.match_version:\n self.show_duplicates = True\nself.query_format = '%{versio... | <|body_start_0|>
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.ignore_excluders = ignore_excluders
self.verbose = verbose
if self.match_ver... | Class to wrap the repoquery | Repoquery | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_002094 | 6,322 | permissive | [
{
"docstring": "Constructor for YumList",
"name": "__init__",
"signature": "def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose)"
},
{
"docstring": "build the repoquery cmd options",
"name": "build_cmd",
"signature": "def build_cmd(self)"
},
... | 6 | stack_v2_sparse_classes_30k_train_022936 | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- d... | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- d... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, ignore_excluders, verbose):
"""Constructor for YumList"""
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show... | the_stack_v2_python_sparse | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_utils/src/class/repoquery.py | openshift/openshift-tools | train | 170 |
10bf85473929e704fb6f6d60fc3cb792afcabd0f | [
"basic_imf = IMF(a.mmin, a.mmax, a.mass_steps)\ngetattr(basic_imf, a.imf_type_name)(a.imf_parameter)\nbasic_sn2 = SN2_feedback()\ngetattr(basic_sn2, a.yield_table_name_sn2)()\nbasic_1a = SN1a_feedback()\ngetattr(basic_1a, a.yield_table_name_1a)()\nbasic_agb = AGB_feedback()\ngetattr(basic_agb, a.yield_table_name_ag... | <|body_start_0|>
basic_imf = IMF(a.mmin, a.mmax, a.mass_steps)
getattr(basic_imf, a.imf_type_name)(a.imf_parameter)
basic_sn2 = SN2_feedback()
getattr(basic_sn2, a.yield_table_name_sn2)()
basic_1a = SN1a_feedback()
getattr(basic_1a, a.yield_table_name_1a)()
basic_... | This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated. | SSP_wrap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSP_wrap:
"""This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated."""
def __init__(self, a):
"""Upon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields i... | stack_v2_sparse_classes_75kplus_train_002095 | 40,713 | permissive | [
{
"docstring": "Upon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields is loaded. INPUT: a = Modelparameter class. So the default IMF etc are loaded. If we want other yield sets etc. loaded we need to specify that in paramter.py",
"name": "__init__",
"signature": "def __init__(se... | 2 | stack_v2_sparse_classes_30k_train_016002 | Implement the Python class `SSP_wrap` described below.
Class description:
This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated.
Method signatures and docstrings:
- def __init__(self, a): Upon initialization the... | Implement the Python class `SSP_wrap` described below.
Class description:
This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated.
Method signatures and docstrings:
- def __init__(self, a): Upon initialization the... | 1ab0d0c56a03c4f4b710ee8f0142bcccc7e84e22 | <|skeleton|>
class SSP_wrap:
"""This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated."""
def __init__(self, a):
"""Upon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSP_wrap:
"""This is the wrapper around the SSP function. It preloads the needed classes and calls all nucleosynthetic enrichment processes when the enrichment is calculated."""
def __init__(self, a):
"""Upon initialization the default IMF, CC-SN yields, SN Ia yields and AGB yields is loaded. INP... | the_stack_v2_python_sparse | Chempy/wrapper.py | oliverphilcox/ChempyMulti | train | 8 |
90f01c7dc72e7a2462fc064b137cf49c22de6ea1 | [
"row, col = (len(matrix), len(matrix[0]))\nif matrix[row_index][col_index] == '0':\n return 0\nlength = 1\nmax_size = min(row - row_index, col - col_index)\nfor size in range(1, max_size):\n for i in range(row_index, row_index + size + 1):\n new_col = col_index + size\n if matrix[i][new_col] == ... | <|body_start_0|>
row, col = (len(matrix), len(matrix[0]))
if matrix[row_index][col_index] == '0':
return 0
length = 1
max_size = min(row - row_index, col - col_index)
for size in range(1, max_size):
for i in range(row_index, row_index + size + 1):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
<|body_0|>
def maximal_square(self, matrix: List[List[chr]]) -> int:
"""获取最大正方形 Args: matrix: 输入二... | stack_v2_sparse_classes_75kplus_train_002096 | 3,418 | permissive | [
{
"docstring": "获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量",
"name": "get_max",
"signature": "def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int"
},
{
"docstring": "获取最大正方形 Args: matrix: 输入二维数组 Returns: 最大正方形数量",
"name": "maximal_squ... | 3 | stack_v2_sparse_classes_30k_train_023383 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int: 获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量
- def maximal_square(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int: 获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量
- def maximal_square(sel... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
<|body_0|>
def maximal_square(self, matrix: List[List[chr]]) -> int:
"""获取最大正方形 Args: matrix: 输入二... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def get_max(self, matrix: List[List[int]], row_index: int, col_index: int) -> int:
"""获取最大值 Args: matrix: 二维数组 row_index: 行下标 col_index: 列下标 Returns: 最大长度数量"""
row, col = (len(matrix), len(matrix[0]))
if matrix[row_index][col_index] == '0':
return 0
length... | the_stack_v2_python_sparse | src/leetcodepython/array/maximal_square_221.py | zhangyu345293721/leetcode | train | 101 | |
01b2190cb7be36618ed0267af1d986cb8496af43 | [
"if not isinstance(data, np.ndarray):\n data = np.array(data)\nif len(data.shape) == 1:\n data = data.reshape(-1, 1)\nself.data = data\nself.N, self.d = self.data.shape",
"if not isinstance(new_data, np.ndarray):\n new_data = np.array(new_data)\nif len(new_data.shape) == 1:\n new_data = new_data.resha... | <|body_start_0|>
if not isinstance(data, np.ndarray):
data = np.array(data)
if len(data.shape) == 1:
data = data.reshape(-1, 1)
self.data = data
self.N, self.d = self.data.shape
<|end_body_0|>
<|body_start_1|>
if not isinstance(new_data, np.ndarray):
... | This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(new_data) Evaluates the chi-square kernel function at new_data. kernel_single... | ChiSquare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiSquare:
"""This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(new_data) Evaluates the chi-square kerne... | stack_v2_sparse_classes_75kplus_train_002097 | 3,671 | no_license | [
{
"docstring": "Parameters ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Evaluates the chi-square kernel function at new_data. Each entry is k(X_i, Y_j), where X_... | 3 | stack_v2_sparse_classes_30k_test_002032 | Implement the Python class `ChiSquare` described below.
Class description:
This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(n... | Implement the Python class `ChiSquare` described below.
Class description:
This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(n... | 33193676029a9be8ca67a1272960f2111ea7d2e4 | <|skeleton|>
class ChiSquare:
"""This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(new_data) Evaluates the chi-square kerne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChiSquare:
"""This is a class of evaluating the chi-square kernel function. Attributes ---------- data : numpy.ndarray The array at which the chi-square kernel function is to evaluated. N, d : int, int The shape of data array. Methods ------- kernel_matrix(new_data) Evaluates the chi-square kernel function at... | the_stack_v2_python_sparse | chisq.py | zhou-chenxi/kerneleval | train | 0 |
162a523422332f4d5446c069d3c7ed278c5e448c | [
"territories = [x.territories.all() for x in self.groups.prefetch_related('territories').all()]\nmerged_and_unique = list(set(list(itertools.chain(*territories))))\nreturn merged_and_unique",
"users = [x.users for x in self.groups.all()]\nmerged = list(itertools.chain(*users))\nreturn merged"
] | <|body_start_0|>
territories = [x.territories.all() for x in self.groups.prefetch_related('territories').all()]
merged_and_unique = list(set(list(itertools.chain(*territories))))
return merged_and_unique
<|end_body_0|>
<|body_start_1|>
users = [x.users for x in self.groups.all()]
... | Place | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Place:
def territories(self):
"""Returns territories from groups members"""
<|body_0|>
def advisors(self):
"""Returns users whose place belongs to groups"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
territories = [x.territories.all() for x in sel... | stack_v2_sparse_classes_75kplus_train_002098 | 2,780 | no_license | [
{
"docstring": "Returns territories from groups members",
"name": "territories",
"signature": "def territories(self)"
},
{
"docstring": "Returns users whose place belongs to groups",
"name": "advisors",
"signature": "def advisors(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035214 | Implement the Python class `Place` described below.
Class description:
Implement the Place class.
Method signatures and docstrings:
- def territories(self): Returns territories from groups members
- def advisors(self): Returns users whose place belongs to groups | Implement the Python class `Place` described below.
Class description:
Implement the Place class.
Method signatures and docstrings:
- def territories(self): Returns territories from groups members
- def advisors(self): Returns users whose place belongs to groups
<|skeleton|>
class Place:
def territories(self):
... | 95d21cd6036a99c5f399b700a5426e9e2e17e878 | <|skeleton|>
class Place:
def territories(self):
"""Returns territories from groups members"""
<|body_0|>
def advisors(self):
"""Returns users whose place belongs to groups"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Place:
def territories(self):
"""Returns territories from groups members"""
territories = [x.territories.all() for x in self.groups.prefetch_related('territories').all()]
merged_and_unique = list(set(list(itertools.chain(*territories))))
return merged_and_unique
def adviso... | the_stack_v2_python_sparse | dialogwatt/models/place.py | alexandrenorman/mixeur | train | 0 | |
2e6c8a09c9640b5f7aa0c6933f1c02fcf95bcd69 | [
"self._cmd = cmd\nself._preexec_fn = preexec_fn\nself._timeout_secs = timeout_secs",
"try:\n subprocess.check_call(self._cmd, timeout=self._timeout_secs, shell=True, preexec_fn=self._preexec_fn)\n return (True, None)\nexcept subprocess.CalledProcessError as reason:\n return (False, str(reason))\nexcept s... | <|body_start_0|>
self._cmd = cmd
self._preexec_fn = preexec_fn
self._timeout_secs = timeout_secs
<|end_body_0|>
<|body_start_1|>
try:
subprocess.check_call(self._cmd, timeout=self._timeout_secs, shell=True, preexec_fn=self._preexec_fn)
return (True, None)
... | ShellHealthCheck | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShellHealthCheck:
def __init__(self, cmd, preexec_fn=None, timeout_secs=None):
"""Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the c... | stack_v2_sparse_classes_75kplus_train_002099 | 2,179 | permissive | [
{
"docstring": "Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the child shell process is executed. :type preexec_fn: callable :param timeout_secs: Timeout in... | 2 | stack_v2_sparse_classes_30k_test_000161 | Implement the Python class `ShellHealthCheck` described below.
Class description:
Implement the ShellHealthCheck class.
Method signatures and docstrings:
- def __init__(self, cmd, preexec_fn=None, timeout_secs=None): Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected t... | Implement the Python class `ShellHealthCheck` described below.
Class description:
Implement the ShellHealthCheck class.
Method signatures and docstrings:
- def __init__(self, cmd, preexec_fn=None, timeout_secs=None): Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected t... | 88dddb51ed9ad070340edb33eef9fd12745b9f8a | <|skeleton|>
class ShellHealthCheck:
def __init__(self, cmd, preexec_fn=None, timeout_secs=None):
"""Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShellHealthCheck:
def __init__(self, cmd, preexec_fn=None, timeout_secs=None):
"""Initialize with the commmand we would like to call. :param cmd: Command to execute that is expected to have a 0 return code on success. :type cmd: str :param preexec_fn: Callable to invoke just before the child shell pro... | the_stack_v2_python_sparse | Chapter4/Aurora/src/main/python/apache/aurora/common/health_check/shell.py | PacktPublishing/Mastering-Mesos | train | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.