blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5f74d2d9173fb1ddd102625fc8f122dca8d7b73e | [
"self.script = script\nself.example_command = example_command\nself.searchtext = 'input'",
"opt_dict = parse_example_command(self.example_command)\ninputs = {}\nfor key, value in opt_dict.iteritems():\n if self.searchtext in key:\n for i, line in enumerate(self.script):\n line = line.strip()\... | <|body_start_0|>
self.script = script
self.example_command = example_command
self.searchtext = 'input'
<|end_body_0|>
<|body_start_1|>
opt_dict = parse_example_command(self.example_command)
inputs = {}
for key, value in opt_dict.iteritems():
if self.searchtex... | Input class for parsing inputs. | Input | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
"""Input class for parsing inputs."""
def __init__(self, script, example_command):
"""Initialize Input with searchtext = input."""
<|body_0|>
def find_inputs(self):
"""Find inputs in example command. This parses the R script and has NOTHING TO DO WITH kwds... | stack_v2_sparse_classes_36k_train_007000 | 5,433 | permissive | [
{
"docstring": "Initialize Input with searchtext = input.",
"name": "__init__",
"signature": "def __init__(self, script, example_command)"
},
{
"docstring": "Find inputs in example command. This parses the R script and has NOTHING TO DO WITH kwds",
"name": "find_inputs",
"signature": "de... | 2 | null | Implement the Python class `Input` described below.
Class description:
Input class for parsing inputs.
Method signatures and docstrings:
- def __init__(self, script, example_command): Initialize Input with searchtext = input.
- def find_inputs(self): Find inputs in example command. This parses the R script and has NO... | Implement the Python class `Input` described below.
Class description:
Input class for parsing inputs.
Method signatures and docstrings:
- def __init__(self, script, example_command): Initialize Input with searchtext = input.
- def find_inputs(self): Find inputs in example command. This parses the R script and has NO... | 063bf0dca5d465466aefa77edaf47df12c4ff932 | <|skeleton|>
class Input:
"""Input class for parsing inputs."""
def __init__(self, script, example_command):
"""Initialize Input with searchtext = input."""
<|body_0|>
def find_inputs(self):
"""Find inputs in example command. This parses the R script and has NOTHING TO DO WITH kwds... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Input:
"""Input class for parsing inputs."""
def __init__(self, script, example_command):
"""Initialize Input with searchtext = input."""
self.script = script
self.example_command = example_command
self.searchtext = 'input'
def find_inputs(self):
"""Find input... | the_stack_v2_python_sparse | .venv/lib/python2.7/site-packages/planemo/rscript_parse.py | maumauleon/galaxy-irri-dev | train | 1 |
bbe7b5f35ba210a46acc0a87f5904de5c2a072b3 | [
"self.network = network\nself.agency = agency\nself.route = route\nself.stop = stop\nself.data = data\nself.max_predictions = max_predictions\nself.minimum_time = minimum_time\nself.predictions = []\nself.last_query_time = -1000",
"try:\n url = 'http://webservices.nextbus.com/service/publicXMLFeed?' + 'command... | <|body_start_0|>
self.network = network
self.agency = agency
self.route = route
self.stop = stop
self.data = data
self.max_predictions = max_predictions
self.minimum_time = minimum_time
self.predictions = []
self.last_query_time = -1000
<|end_body_... | Class to handle NextBus prediction times for one route & stop. | NextBus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NextBus:
"""Class to handle NextBus prediction times for one route & stop."""
def __init__(self, network, agency, route, stop, data=None, max_predictions=3, minimum_time=300):
"""Constructor expects a Requests-capable Network object, strings for transit agency, route, and stop ID, pl... | stack_v2_sparse_classes_36k_train_007001 | 3,391 | permissive | [
{
"docstring": "Constructor expects a Requests-capable Network object, strings for transit agency, route, and stop ID, plus optional per-stop data as defined by an application (e.g. text description, but could be an object or tuple of data, or None, or whatever's needed by the app), limits for the maximum numbe... | 3 | stack_v2_sparse_classes_30k_train_011990 | Implement the Python class `NextBus` described below.
Class description:
Class to handle NextBus prediction times for one route & stop.
Method signatures and docstrings:
- def __init__(self, network, agency, route, stop, data=None, max_predictions=3, minimum_time=300): Constructor expects a Requests-capable Network o... | Implement the Python class `NextBus` described below.
Class description:
Class to handle NextBus prediction times for one route & stop.
Method signatures and docstrings:
- def __init__(self, network, agency, route, stop, data=None, max_predictions=3, minimum_time=300): Constructor expects a Requests-capable Network o... | 5eaa7a15a437c533b89f359a25983e24bb6b5438 | <|skeleton|>
class NextBus:
"""Class to handle NextBus prediction times for one route & stop."""
def __init__(self, network, agency, route, stop, data=None, max_predictions=3, minimum_time=300):
"""Constructor expects a Requests-capable Network object, strings for transit agency, route, and stop ID, pl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NextBus:
"""Class to handle NextBus prediction times for one route & stop."""
def __init__(self, network, agency, route, stop, data=None, max_predictions=3, minimum_time=300):
"""Constructor expects a Requests-capable Network object, strings for transit agency, route, and stop ID, plus optional p... | the_stack_v2_python_sparse | MagTag_NextBus/nextbus.py | adafruit/Adafruit_Learning_System_Guides | train | 937 |
e87a8683d4300f34018575e8d42abaf0fb780b5c | [
"super().__init__(model, copy)\nself.outputs = outputs\nself.exclude_outputs = exclude_outputs",
"model = self.load()\nif self.outputs == constants.MARK_ALL:\n G_LOGGER.verbose('Marking all ONNX tensors as outputs')\n model = onnx_util.mark_layerwise(model)\nelif self.outputs is not None:\n model = onnx_... | <|body_start_0|>
super().__init__(model, copy)
self.outputs = outputs
self.exclude_outputs = exclude_outputs
<|end_body_0|>
<|body_start_1|>
model = self.load()
if self.outputs == constants.MARK_ALL:
G_LOGGER.verbose('Marking all ONNX tensors as outputs')
... | Functor that modifies the outputs of an ONNX model. | ModifyOutputs | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModifyOutputs:
"""Functor that modifies the outputs of an ONNX model."""
def __init__(self, model, outputs=None, exclude_outputs=None, copy=None):
"""Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): An ONNX model or a callable th... | stack_v2_sparse_classes_36k_train_007002 | 37,448 | permissive | [
{
"docstring": "Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): An ONNX model or a callable that returns one. outputs (Sequence[str]): Names of tensors to mark as outputs. If provided, this will override the existing model outputs. If a value of `constants... | 2 | stack_v2_sparse_classes_30k_train_020966 | Implement the Python class `ModifyOutputs` described below.
Class description:
Functor that modifies the outputs of an ONNX model.
Method signatures and docstrings:
- def __init__(self, model, outputs=None, exclude_outputs=None, copy=None): Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callab... | Implement the Python class `ModifyOutputs` described below.
Class description:
Functor that modifies the outputs of an ONNX model.
Method signatures and docstrings:
- def __init__(self, model, outputs=None, exclude_outputs=None, copy=None): Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callab... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class ModifyOutputs:
"""Functor that modifies the outputs of an ONNX model."""
def __init__(self, model, outputs=None, exclude_outputs=None, copy=None):
"""Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): An ONNX model or a callable th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModifyOutputs:
"""Functor that modifies the outputs of an ONNX model."""
def __init__(self, model, outputs=None, exclude_outputs=None, copy=None):
"""Modifies outputs of an ONNX model. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): An ONNX model or a callable that returns on... | the_stack_v2_python_sparse | tools/Polygraphy/polygraphy/backend/onnx/loader.py | NVIDIA/TensorRT | train | 8,026 |
0da743e9fd2ee531cf516f7f91c5835232851ffa | [
"test, traceback = super(SetPulseModulationTask, self).check(*args, **kwargs)\nif test and self.switch:\n try:\n switch = self.format_and_eval_string(self.switch)\n except Exception:\n return (False, traceback)\n if switch not in ('Off', 'On', 0, 1):\n test = False\n traceback[s... | <|body_start_0|>
test, traceback = super(SetPulseModulationTask, self).check(*args, **kwargs)
if test and self.switch:
try:
switch = self.format_and_eval_string(self.switch)
except Exception:
return (False, traceback)
if switch not in (... | Switch on/off the pulse modulation of the source. | SetPulseModulationTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetPulseModulationTask:
"""Switch on/off the pulse modulation of the source."""
def check(self, *args, **kwargs):
"""Validate the value of the switch."""
<|body_0|>
def i_perform(self, switch=None):
"""Default interface behavior."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_007003 | 7,840 | permissive | [
{
"docstring": "Validate the value of the switch.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
},
{
"docstring": "Default interface behavior.",
"name": "i_perform",
"signature": "def i_perform(self, switch=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014026 | Implement the Python class `SetPulseModulationTask` described below.
Class description:
Switch on/off the pulse modulation of the source.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Validate the value of the switch.
- def i_perform(self, switch=None): Default interface behavior. | Implement the Python class `SetPulseModulationTask` described below.
Class description:
Switch on/off the pulse modulation of the source.
Method signatures and docstrings:
- def check(self, *args, **kwargs): Validate the value of the switch.
- def i_perform(self, switch=None): Default interface behavior.
<|skeleton|... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class SetPulseModulationTask:
"""Switch on/off the pulse modulation of the source."""
def check(self, *args, **kwargs):
"""Validate the value of the switch."""
<|body_0|>
def i_perform(self, switch=None):
"""Default interface behavior."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetPulseModulationTask:
"""Switch on/off the pulse modulation of the source."""
def check(self, *args, **kwargs):
"""Validate the value of the switch."""
test, traceback = super(SetPulseModulationTask, self).check(*args, **kwargs)
if test and self.switch:
try:
... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/instr/rf_tasks.py | Exopy/exopy_hqc_legacy | train | 0 |
f308abf8c7b30a9f6c849548a9fdce340a3fb450 | [
"self.hostname = hostname\nself.username = username\nself.password = password\nself.rpc_queue = rpc_queue\nself.channel = None\nself.response = None\nself.connection = None\nself.callback_queue = None\nself.correlation_id = None\nself.open()",
"self.connection = amqpstorm.Connection(self.hostname, self.username, ... | <|body_start_0|>
self.hostname = hostname
self.username = username
self.password = password
self.rpc_queue = rpc_queue
self.channel = None
self.response = None
self.connection = None
self.callback_queue = None
self.correlation_id = None
sel... | RPC Client for Prov Service. | RpcClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcClient:
"""RPC Client for Prov Service."""
def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue'):
"""Client init function."""
<|body_0|>
def open(self):
"""Open communication channel. :return:"""
<|bod... | stack_v2_sparse_classes_36k_train_007004 | 2,007 | no_license | [
{
"docstring": "Client init function.",
"name": "__init__",
"signature": "def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue')"
},
{
"docstring": "Open communication channel. :return:",
"name": "open",
"signature": "def open(self)"
},... | 5 | stack_v2_sparse_classes_30k_train_015733 | Implement the Python class `RpcClient` described below.
Class description:
RPC Client for Prov Service.
Method signatures and docstrings:
- def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue'): Client init function.
- def open(self): Open communication channel. :ret... | Implement the Python class `RpcClient` described below.
Class description:
RPC Client for Prov Service.
Method signatures and docstrings:
- def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue'): Client init function.
- def open(self): Open communication channel. :ret... | 69d37a99c31596365cfe8fd0e665dcb6b75dff6b | <|skeleton|>
class RpcClient:
"""RPC Client for Prov Service."""
def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue'):
"""Client init function."""
<|body_0|>
def open(self):
"""Open communication channel. :return:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RpcClient:
"""RPC Client for Prov Service."""
def __init__(self, hostname='127.0.0.1', username='guest', password='guest', rpc_queue='base.rpc_queue'):
"""Client init function."""
self.hostname = hostname
self.username = username
self.password = password
self.rpc_q... | the_stack_v2_python_sparse | src/prov/applib/messaging_client.py | blankdots/provenance-service | train | 0 |
0e8bcdb437fb52f3fdc680172d9051b6a0a27817 | [
"self.capacity = capacity\nself.keyMap = defaultdict(lambda: None)\nself.list = DoubleList()\nself.len = 0",
"if key in self.keyMap:\n p = self.keyMap[key]\n self.list.move(self.list.head, self.list, p)\n return p.value\nelse:\n return -1",
"if key in self.keyMap:\n p = self.keyMap[key]\n p.va... | <|body_start_0|>
self.capacity = capacity
self.keyMap = defaultdict(lambda: None)
self.list = DoubleList()
self.len = 0
<|end_body_0|>
<|body_start_1|>
if key in self.keyMap:
p = self.keyMap[key]
self.list.move(self.list.head, self.list, p)
re... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_007005 | 5,014 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 2ec3a30e278263b86eeb7bfd0a1eadc234095ec3 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.keyMap = defaultdict(lambda: None)
self.list = DoubleList()
self.len = 0
def get(self, key):
""":type key: int :rtype: int"""
if key in self.keyMap:
... | the_stack_v2_python_sparse | 146. LRU Cache.py | Barret-ma/leetcode | train | 2 | |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = CollaboratorSerializer(username=username, repo_base=repo_base, request=request)\ncollaborators = serializer.describe_collaborator(repo_name, collaborator)\nreturn Response(collaborators, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nser... | <|body_start_0|>
username = request.user.get_username()
serializer = CollaboratorSerializer(username=username, repo_base=repo_base, request=request)
collaborators = serializer.describe_collaborator(repo_name, collaborator)
return Response(collaborators, status=status.HTTP_200_OK)
<|end_b... | View, Modify and delete existing collaborators. | Collaborator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collaborator:
"""View, Modify and delete existing collaborators."""
def get(self, request, repo_base, repo_name, collaborator, format=None):
"""View collaborator permissions on a given repo"""
<|body_0|>
def delete(self, request, repo_base, repo_name, collaborator, forma... | stack_v2_sparse_classes_36k_train_007006 | 31,465 | permissive | [
{
"docstring": "View collaborator permissions on a given repo",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, collaborator, format=None)"
},
{
"docstring": "Remove a collaborator from a given repo",
"name": "delete",
"signature": "def delete(self, request, rep... | 2 | stack_v2_sparse_classes_30k_train_014986 | Implement the Python class `Collaborator` described below.
Class description:
View, Modify and delete existing collaborators.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, collaborator, format=None): View collaborator permissions on a given repo
- def delete(self, request, repo_base... | Implement the Python class `Collaborator` described below.
Class description:
View, Modify and delete existing collaborators.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, collaborator, format=None): View collaborator permissions on a given repo
- def delete(self, request, repo_base... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Collaborator:
"""View, Modify and delete existing collaborators."""
def get(self, request, repo_base, repo_name, collaborator, format=None):
"""View collaborator permissions on a given repo"""
<|body_0|>
def delete(self, request, repo_base, repo_name, collaborator, forma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Collaborator:
"""View, Modify and delete existing collaborators."""
def get(self, request, repo_base, repo_name, collaborator, format=None):
"""View collaborator permissions on a given repo"""
username = request.user.get_username()
serializer = CollaboratorSerializer(username=user... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 |
b9bd3458b762e0efbd989a72ccde4469b2984ed8 | [
"default_headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'piper-key', 'Access-Control-Allow-Credentials': True}\nif headers:\n default_headers.update(headers)\nself.status_code = status_code\nself.headers = default_headers\nself.message = message\nself.body = body",
"kwargs = {}\... | <|body_start_0|>
default_headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'piper-key', 'Access-Control-Allow-Credentials': True}
if headers:
default_headers.update(headers)
self.status_code = status_code
self.headers = default_headers
sel... | Custom HTTP class that is used to return objects that API gateway uses to return. | HttpResponse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpResponse:
"""Custom HTTP class that is used to return objects that API gateway uses to return."""
def __init__(self, status_code: int=400, headers: Dict=None, message: str='', body: Any=None) -> None:
"""Construct a HttpResponse object. :param status_code: int, HTTP status code. ... | stack_v2_sparse_classes_36k_train_007007 | 1,633 | no_license | [
{
"docstring": "Construct a HttpResponse object. :param status_code: int, HTTP status code. see http://bit.ly/1ZKo4EE :param headers: Dict of headers, defaults to empty :param message: str, status message with info :param body: optional body",
"name": "__init__",
"signature": "def __init__(self, status_... | 2 | null | Implement the Python class `HttpResponse` described below.
Class description:
Custom HTTP class that is used to return objects that API gateway uses to return.
Method signatures and docstrings:
- def __init__(self, status_code: int=400, headers: Dict=None, message: str='', body: Any=None) -> None: Construct a HttpRes... | Implement the Python class `HttpResponse` described below.
Class description:
Custom HTTP class that is used to return objects that API gateway uses to return.
Method signatures and docstrings:
- def __init__(self, status_code: int=400, headers: Dict=None, message: str='', body: Any=None) -> None: Construct a HttpRes... | 70f651db8af4edb625f6ba249556d3c2d04a350b | <|skeleton|>
class HttpResponse:
"""Custom HTTP class that is used to return objects that API gateway uses to return."""
def __init__(self, status_code: int=400, headers: Dict=None, message: str='', body: Any=None) -> None:
"""Construct a HttpResponse object. :param status_code: int, HTTP status code. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpResponse:
"""Custom HTTP class that is used to return objects that API gateway uses to return."""
def __init__(self, status_code: int=400, headers: Dict=None, message: str='', body: Any=None) -> None:
"""Construct a HttpResponse object. :param status_code: int, HTTP status code. see http://bi... | the_stack_v2_python_sparse | serverless/piper-budget/common/http.py | phouse512/piper | train | 0 |
7f549b8e87c02b1983d8640f731d6fe530f1a91c | [
"a = int(input('Birinci Sayı:'))\nb = int(input('İkinci Sayı:'))\nif Singleton.__instance == None:\n Singleton()\nreturn ('Toplam:', a + b, 'fark: ', a - b, 'Carpim: ', a * b, 'bolum: ', a / b)",
"if Singleton.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Singleton.__instan... | <|body_start_0|>
a = int(input('Birinci Sayı:'))
b = int(input('İkinci Sayı:'))
if Singleton.__instance == None:
Singleton()
return ('Toplam:', a + b, 'fark: ', a - b, 'Carpim: ', a * b, 'bolum: ', a / b)
<|end_body_0|>
<|body_start_1|>
if Singleton.__instance != Non... | Singleton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = int(input('Birinci Sayı:'))
b = int(input('İkinci Sayı:'))
... | stack_v2_sparse_classes_36k_train_007008 | 768 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018554 | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `Singleton` described below.
Class description:
Implement the Singleton class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class Singleton:
def getInstance():
"""Static access me... | 259836447db6512c49df18fb847a6dd5ae0c308b | <|skeleton|>
class Singleton:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Singleton:
def getInstance():
"""Static access method."""
a = int(input('Birinci Sayı:'))
b = int(input('İkinci Sayı:'))
if Singleton.__instance == None:
Singleton()
return ('Toplam:', a + b, 'fark: ', a - b, 'Carpim: ', a * b, 'bolum: ', a / b)
def __i... | the_stack_v2_python_sparse | singletiondortislem.py | komurkara/GoruntuIsleme | train | 0 | |
2e314d5b6e8a356503455f0160e0f595f239d004 | [
"self.check_dependencies()\nimport xesmf as xe\nself.grid_in = {'lat': lats, 'lon': lons}\nlons, lats = np.meshgrid(np.linspace(min_lon, max_lon, n_lons), np.linspace(min_lat, max_lat, n_lats))\nself.grid_out = {'lat': lats, 'lon': lons}\nself.new_lat_lon = np.zeros((*lats.shape, 2))\nself.new_lat_lon[..., 0] = lat... | <|body_start_0|>
self.check_dependencies()
import xesmf as xe
self.grid_in = {'lat': lats, 'lon': lons}
lons, lats = np.meshgrid(np.linspace(min_lon, max_lon, n_lons), np.linspace(min_lat, max_lat, n_lats))
self.grid_out = {'lat': lats, 'lon': lons}
self.new_lat_lon = np.... | Regridder class for stitching domains | Regridder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regridder:
"""Regridder class for stitching domains"""
def __init__(self, lats, lons, min_lat, max_lat, min_lon, max_lon, n_lats, n_lons):
"""Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray Array of longitudes for input grid min_lat : float Minim... | stack_v2_sparse_classes_36k_train_007009 | 15,917 | permissive | [
{
"docstring": "Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray Array of longitudes for input grid min_lat : float Minimum lat for output grid max_lat : float Maximum lat for output grid min_lon : float Minimum lon for output grid max_lon : float Maximum lon for output grid... | 3 | stack_v2_sparse_classes_30k_train_004248 | Implement the Python class `Regridder` described below.
Class description:
Regridder class for stitching domains
Method signatures and docstrings:
- def __init__(self, lats, lons, min_lat, max_lat, min_lon, max_lon, n_lats, n_lons): Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray... | Implement the Python class `Regridder` described below.
Class description:
Regridder class for stitching domains
Method signatures and docstrings:
- def __init__(self, lats, lons, min_lat, max_lat, min_lon, max_lon, n_lats, n_lons): Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray... | f3803a823c7bb0afd7ab6064625908dca0be3476 | <|skeleton|>
class Regridder:
"""Regridder class for stitching domains"""
def __init__(self, lats, lons, min_lat, max_lat, min_lon, max_lon, n_lats, n_lons):
"""Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray Array of longitudes for input grid min_lat : float Minim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Regridder:
"""Regridder class for stitching domains"""
def __init__(self, lats, lons, min_lat, max_lat, min_lon, max_lon, n_lats, n_lons):
"""Parameters ---------- lats : ndarray Array of latitudes for input grid lons : ndarray Array of longitudes for input grid min_lat : float Minimum lat for ou... | the_stack_v2_python_sparse | sup3r/utilities/stitching.py | NREL/sup3r | train | 20 |
8a62f6b885148ba8f39a86c9eaf934d56ee9c4e4 | [
"with tf.name_scope('MaskedLMTask/losses'):\n metrics = dict([(metric.name, metric) for metric in metrics])\n lm_prediction_losses = tf.keras.losses.sparse_categorical_crossentropy(labels['masked_lm_ids'], tf.cast(model_outputs['mlm_logits'], tf.float32), from_logits=True)\n lm_label_weights = labels['mask... | <|body_start_0|>
with tf.name_scope('MaskedLMTask/losses'):
metrics = dict([(metric.name, metric) for metric in metrics])
lm_prediction_losses = tf.keras.losses.sparse_categorical_crossentropy(labels['masked_lm_ids'], tf.cast(model_outputs['mlm_logits'], tf.float32), from_logits=True)
... | Task object for Mask language modeling. | TokenDropMaskedLMTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenDropMaskedLMTask:
"""Task object for Mask language modeling."""
def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]:
"""Return the final loss, and the masked-lm loss."""
<|body_0|>
def train_step(self, inputs, model... | stack_v2_sparse_classes_36k_train_007010 | 4,551 | permissive | [
{
"docstring": "Return the final loss, and the masked-lm loss.",
"name": "build_losses",
"signature": "def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]"
},
{
"docstring": "Does forward and backward. Args: inputs: a dictionary of input tensors... | 3 | stack_v2_sparse_classes_30k_train_021361 | Implement the Python class `TokenDropMaskedLMTask` described below.
Class description:
Task object for Mask language modeling.
Method signatures and docstrings:
- def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]: Return the final loss, and the masked-lm loss.
- de... | Implement the Python class `TokenDropMaskedLMTask` described below.
Class description:
Task object for Mask language modeling.
Method signatures and docstrings:
- def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]: Return the final loss, and the masked-lm loss.
- de... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class TokenDropMaskedLMTask:
"""Task object for Mask language modeling."""
def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]:
"""Return the final loss, and the masked-lm loss."""
<|body_0|>
def train_step(self, inputs, model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenDropMaskedLMTask:
"""Task object for Mask language modeling."""
def build_losses(self, labels, model_outputs, metrics, aux_losses=None) -> Tuple[tf.Tensor, tf.Tensor]:
"""Return the final loss, and the masked-lm loss."""
with tf.name_scope('MaskedLMTask/losses'):
metrics ... | the_stack_v2_python_sparse | official/projects/token_dropping/masked_lm.py | jianzhnie/models | train | 2 |
01d8d93faf2243867486267cf13d8ba124fbcb9f | [
"self.size = size\nself.left_eye_tex = gloo.Texture2D(shape=(4096, 4096) + (3,))\nself.right_eye_tex = gloo.Texture2D(shape=(4096, 4096) + (3,))\nself.left_eye = gloo.FrameBuffer(self.left_eye_tex, gloo.RenderBuffer(self.size))\nself.right_eye = gloo.FrameBuffer(self.right_eye_tex, gloo.RenderBuffer(self.size))\nse... | <|body_start_0|>
self.size = size
self.left_eye_tex = gloo.Texture2D(shape=(4096, 4096) + (3,))
self.right_eye_tex = gloo.Texture2D(shape=(4096, 4096) + (3,))
self.left_eye = gloo.FrameBuffer(self.left_eye_tex, gloo.RenderBuffer(self.size))
self.right_eye = gloo.FrameBuffer(self.... | Distorter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Distorter:
def __init__(self, size=(1600, 900), no_distort=False):
"""Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply distortion or not?"""
<|body_0|>
def draw_no_distortion(self, *Contexts):
""... | stack_v2_sparse_classes_36k_train_007011 | 7,514 | no_license | [
{
"docstring": "Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply distortion or not?",
"name": "__init__",
"signature": "def __init__(self, size=(1600, 900), no_distort=False)"
},
{
"docstring": "Distorter WITHOUT applying di... | 3 | stack_v2_sparse_classes_30k_train_005031 | Implement the Python class `Distorter` described below.
Class description:
Implement the Distorter class.
Method signatures and docstrings:
- def __init__(self, size=(1600, 900), no_distort=False): Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply... | Implement the Python class `Distorter` described below.
Class description:
Implement the Distorter class.
Method signatures and docstrings:
- def __init__(self, size=(1600, 900), no_distort=False): Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply... | 7cb82784d4b1c243935f047696f3d42e0c21be32 | <|skeleton|>
class Distorter:
def __init__(self, size=(1600, 900), no_distort=False):
"""Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply distortion or not?"""
<|body_0|>
def draw_no_distortion(self, *Contexts):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Distorter:
def __init__(self, size=(1600, 900), no_distort=False):
"""Distorter object: Applies distortion to Contexts and drawables - size (X, Y): Size of monitor - distortion (Bool): Apply distortion or not?"""
self.size = size
self.left_eye_tex = gloo.Texture2D(shape=(4096, 4096) + ... | the_stack_v2_python_sparse | computer/src/python/libVisar/libVisar/OpenGL/shaders/make_distortion.py | prashant87/visar | train | 0 | |
023bfd34c453b2458a6fc054d60fe99290dab58f | [
"super().__init__()\nself.depth = depth\nself.embedding_dim = embedding_dim\nself.num_heads = num_heads\nself.mlp_dim = mlp_dim\nself.layers = nn.LayerList()\nfor i in range(depth):\n self.layers.append(TwoWayAttentionBlock(embedding_dim=embedding_dim, num_heads=num_heads, mlp_dim=mlp_dim, activation=activation,... | <|body_start_0|>
super().__init__()
self.depth = depth
self.embedding_dim = embedding_dim
self.num_heads = num_heads
self.mlp_dim = mlp_dim
self.layers = nn.LayerList()
for i in range(depth):
self.layers.append(TwoWayAttentionBlock(embedding_dim=embedd... | TwoWayTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied.... | stack_v2_sparse_classes_36k_train_007012 | 8,182 | permissive | [
{
"docstring": "A transformer decoder that attends to an input image using queries whose positional embedding is supplied. Args: depth (int): number of layers in the transformer embedding_dim (int): the channel dimension for the input embeddings num_heads (int): the number of heads for multihead attention. Must... | 2 | null | Implement the Python class `TwoWayTransformer` described below.
Class description:
Implement the TwoWayTransformer class.
Method signatures and docstrings:
- def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None: ... | Implement the Python class `TwoWayTransformer` described below.
Class description:
Implement the TwoWayTransformer class.
Method signatures and docstrings:
- def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None: ... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied. Args: depth (... | the_stack_v2_python_sparse | contrib/SegmentAnything/segment_anything/modeling/transformer.py | PaddlePaddle/PaddleSeg | train | 8,531 | |
30747c5412a025436f26bda3e0ab9bdfac74ad09 | [
"super(Test_eliminate, self).__init__(methodName)\nself.interpreter = Interpreter(show_script=False, raise_relax_error=True)\nself.interpreter.populate_self()\nself.interpreter.on(verbose=False)\nself.eliminate_fns = Container()\nself.eliminate_fns.eliminate = self.interpreter.eliminate",
"for data in DATA_TYPES:... | <|body_start_0|>
super(Test_eliminate, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise_relax_error=True)
self.interpreter.populate_self()
self.interpreter.on(verbose=False)
self.eliminate_fns = Container()
self.eliminate_fns.eliminate = ... | Unit tests for the functions of the 'prompt.eliminate' module. | Test_eliminate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_eliminate:
"""Unit tests for the functions of the 'prompt.eliminate' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_eliminate_function(self):
"""The function arg unit test of the eli... | stack_v2_sparse_classes_36k_train_007013 | 3,649 | no_license | [
{
"docstring": "Set up the test case class for the system tests.",
"name": "__init__",
"signature": "def __init__(self, methodName=None)"
},
{
"docstring": "The function arg unit test of the eliminate() user function.",
"name": "test_eliminate_function",
"signature": "def test_eliminate_... | 3 | stack_v2_sparse_classes_30k_val_000502 | Implement the Python class `Test_eliminate` described below.
Class description:
Unit tests for the functions of the 'prompt.eliminate' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_eliminate_function(self): The function arg... | Implement the Python class `Test_eliminate` described below.
Class description:
Unit tests for the functions of the 'prompt.eliminate' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_eliminate_function(self): The function arg... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Test_eliminate:
"""Unit tests for the functions of the 'prompt.eliminate' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_eliminate_function(self):
"""The function arg unit test of the eli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_eliminate:
"""Unit tests for the functions of the 'prompt.eliminate' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
super(Test_eliminate, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise... | the_stack_v2_python_sparse | test_suite/unit_tests/_prompt/test_eliminate.py | jlec/relax | train | 4 |
db8186266507d83e15de3066aefa05e145dd106d | [
"self.domain = domain\nself.nas_protocol = nas_protocol\nself.nas_type = nas_type\nself.password = password\nself.skip_validation = skip_validation\nself.username = username",
"if dictionary is None:\n return None\ndomain = dictionary.get('domain')\nnas_protocol = dictionary.get('nasProtocol')\nnas_type = dict... | <|body_start_0|>
self.domain = domain
self.nas_protocol = nas_protocol
self.nas_type = nas_type
self.password = password
self.skip_validation = skip_validation
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None... | Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtocolEnum): Specifies the protocol used by the NAS server. Specifies the protocol used by a NAS... | NasMountCredentialParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NasMountCredentialParams:
"""Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtocolEnum): Specifies the protocol used by ... | stack_v2_sparse_classes_36k_train_007014 | 3,350 | permissive | [
{
"docstring": "Constructor for the NasMountCredentialParams class",
"name": "__init__",
"signature": "def __init__(self, domain=None, nas_protocol=None, nas_type=None, password=None, skip_validation=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Arg... | 2 | null | Implement the Python class `NasMountCredentialParams` described below.
Class description:
Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtoco... | Implement the Python class `NasMountCredentialParams` described below.
Class description:
Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtoco... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NasMountCredentialParams:
"""Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtocolEnum): Specifies the protocol used by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NasMountCredentialParams:
"""Implementation of the 'NasMountCredentialParams' model. Specifies the credentials to mount a volume on a NetApp server. Attributes: domain (string): Specifies the domain in which this credential is valid. nas_protocol (NasProtocolEnum): Specifies the protocol used by the NAS serve... | the_stack_v2_python_sparse | cohesity_management_sdk/models/nas_mount_credential_params.py | cohesity/management-sdk-python | train | 24 |
f51e1d097372a31ab33b82037a7d422a477cf4e6 | [
"device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)\nif device_class == media_player.MediaPlayerDeviceClass.SPEAKER:\n return [DisplayCategory.SPEAKER]\nreturn [DisplayCategory.TV]",
"yield AlexaPowerController(self.entity)\nsupported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)\nif suppo... | <|body_start_0|>
device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)
if device_class == media_player.MediaPlayerDeviceClass.SPEAKER:
return [DisplayCategory.SPEAKER]
return [DisplayCategory.TV]
<|end_body_0|>
<|body_start_1|>
yield AlexaPowerController(self.entity)
... | Class to represent MediaPlayer capabilities. | MediaPlayerCapabilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaPlayerCapabilities:
"""Class to represent MediaPlayer capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yield... | stack_v2_sparse_classes_36k_train_007015 | 35,310 | permissive | [
{
"docstring": "Return the display categories for this entity.",
"name": "default_display_categories",
"signature": "def default_display_categories(self) -> list[str]"
},
{
"docstring": "Yield the supported interfaces.",
"name": "interfaces",
"signature": "def interfaces(self) -> Generat... | 2 | null | Implement the Python class `MediaPlayerCapabilities` described below.
Class description:
Class to represent MediaPlayer capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str]: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapabilit... | Implement the Python class `MediaPlayerCapabilities` described below.
Class description:
Class to represent MediaPlayer capabilities.
Method signatures and docstrings:
- def default_display_categories(self) -> list[str]: Return the display categories for this entity.
- def interfaces(self) -> Generator[AlexaCapabilit... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MediaPlayerCapabilities:
"""Class to represent MediaPlayer capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
<|body_0|>
def interfaces(self) -> Generator[AlexaCapability, None, None]:
"""Yield... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MediaPlayerCapabilities:
"""Class to represent MediaPlayer capabilities."""
def default_display_categories(self) -> list[str]:
"""Return the display categories for this entity."""
device_class = self.entity.attributes.get(ATTR_DEVICE_CLASS)
if device_class == media_player.MediaPla... | the_stack_v2_python_sparse | homeassistant/components/alexa/entities.py | home-assistant/core | train | 35,501 |
acafa8e3003a5ed7f10c1318ea4c181e7b482f87 | [
"self.word2indices = defaultdict(list)\nfor i, w in enumerate(words):\n self.word2indices[w].append(i)",
"l1, l2 = (self.word2indices[word1], self.word2indices[word2])\nlen1, len2 = (len(l1), len(l2))\ni, j = (0, 0)\nmin_sofar = float('inf')\nwhile i < len1 and j < len2:\n min_sofar = min(min_sofar, abs(l1[... | <|body_start_0|>
self.word2indices = defaultdict(list)
for i, w in enumerate(words):
self.word2indices[w].append(i)
<|end_body_0|>
<|body_start_1|>
l1, l2 = (self.word2indices[word1], self.word2indices[word2])
len1, len2 = (len(l1), len(l2))
i, j = (0, 0)
min... | WordDistance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.word2indices = defaultdict(list)... | stack_v2_sparse_classes_36k_train_007016 | 2,342 | permissive | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 91db15a686a2f36bf0a00c9bedd5b14b46aaa97b | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.word2indices = defaultdict(list)
for i, w in enumerate(words):
self.word2indices[w].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
... | the_stack_v2_python_sparse | problems/244_shortest-word-distance-ii/main.py | young-geng/leet_code | train | 0 | |
0d76a877cfd52fece0000c716266c9693a5c3ec3 | [
"s = ArrayQueue()\nself.assertEqual(0, len(s))\nself.assertEqual(5, len(s._array))\nArrayQueue.ARRAY_SIZE = 10\ns = ArrayQueue()\nself.assertEqual(0, len(s))\nself.assertEqual(10, len(s._array))\nArrayQueue.ARRAY_SIZE = 5",
"s = ArrayQueue()\nself.assertEqual(0, len(s))\ns.enqueue(1)\nself.assertEqual(1, len(s))\... | <|body_start_0|>
s = ArrayQueue()
self.assertEqual(0, len(s))
self.assertEqual(5, len(s._array))
ArrayQueue.ARRAY_SIZE = 10
s = ArrayQueue()
self.assertEqual(0, len(s))
self.assertEqual(10, len(s._array))
ArrayQueue.ARRAY_SIZE = 5
<|end_body_0|>
<|body_st... | TestArrayQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestArrayQueue:
def test_instantiation(self):
"""Test basic object creation."""
<|body_0|>
def test_enqueue(self):
"""Test stack push operation."""
<|body_1|>
def test_dequeue(self):
"""Test Queue dequeue operation."""
<|body_2|>
def... | stack_v2_sparse_classes_36k_train_007017 | 6,934 | no_license | [
{
"docstring": "Test basic object creation.",
"name": "test_instantiation",
"signature": "def test_instantiation(self)"
},
{
"docstring": "Test stack push operation.",
"name": "test_enqueue",
"signature": "def test_enqueue(self)"
},
{
"docstring": "Test Queue dequeue operation.",... | 5 | stack_v2_sparse_classes_30k_train_020369 | Implement the Python class `TestArrayQueue` described below.
Class description:
Implement the TestArrayQueue class.
Method signatures and docstrings:
- def test_instantiation(self): Test basic object creation.
- def test_enqueue(self): Test stack push operation.
- def test_dequeue(self): Test Queue dequeue operation.... | Implement the Python class `TestArrayQueue` described below.
Class description:
Implement the TestArrayQueue class.
Method signatures and docstrings:
- def test_instantiation(self): Test basic object creation.
- def test_enqueue(self): Test stack push operation.
- def test_dequeue(self): Test Queue dequeue operation.... | 66e553842998e22ee8ec4f9ebe901f76089128de | <|skeleton|>
class TestArrayQueue:
def test_instantiation(self):
"""Test basic object creation."""
<|body_0|>
def test_enqueue(self):
"""Test stack push operation."""
<|body_1|>
def test_dequeue(self):
"""Test Queue dequeue operation."""
<|body_2|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestArrayQueue:
def test_instantiation(self):
"""Test basic object creation."""
s = ArrayQueue()
self.assertEqual(0, len(s))
self.assertEqual(5, len(s._array))
ArrayQueue.ARRAY_SIZE = 10
s = ArrayQueue()
self.assertEqual(0, len(s))
self.assertEqu... | the_stack_v2_python_sparse | python/dsa/queues_test.py | nehararora/practise-code | train | 0 | |
4f19f44a7a50ff8249974e5808e28af36c989232 | [
"self.debug = debug\nif self.debug:\n print('CloudformationValidator - __init__' + lineno())",
"if self.debug:\n print('\\n\\n##################################################')\n print('CloudformationValidator - validate - validating following string' + lineno())\n print(str(cloudformation_string) +... | <|body_start_0|>
self.debug = debug
if self.debug:
print('CloudformationValidator - __init__' + lineno())
<|end_body_0|>
<|body_start_1|>
if self.debug:
print('\n\n##################################################')
print('CloudformationValidator - validate ... | Cloudformation validator | CloudformationValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudformationValidator:
"""Cloudformation validator"""
def __init__(self, debug=False):
"""Initialize :param debug:"""
<|body_0|>
def validate(self, cloudformation_string):
"""Validating the schema for a cloudformation segment :param cloudformation_string: :retu... | stack_v2_sparse_classes_36k_train_007018 | 3,077 | permissive | [
{
"docstring": "Initialize :param debug:",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Validating the schema for a cloudformation segment :param cloudformation_string: :return:",
"name": "validate",
"signature": "def validate(self, cloudformation... | 3 | null | Implement the Python class `CloudformationValidator` described below.
Class description:
Cloudformation validator
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize :param debug:
- def validate(self, cloudformation_string): Validating the schema for a cloudformation segment :param cloudfo... | Implement the Python class `CloudformationValidator` described below.
Class description:
Cloudformation validator
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize :param debug:
- def validate(self, cloudformation_string): Validating the schema for a cloudformation segment :param cloudfo... | a9d0335a532acdb4070e5537155b03b34915b73e | <|skeleton|>
class CloudformationValidator:
"""Cloudformation validator"""
def __init__(self, debug=False):
"""Initialize :param debug:"""
<|body_0|>
def validate(self, cloudformation_string):
"""Validating the schema for a cloudformation segment :param cloudformation_string: :retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudformationValidator:
"""Cloudformation validator"""
def __init__(self, debug=False):
"""Initialize :param debug:"""
self.debug = debug
if self.debug:
print('CloudformationValidator - __init__' + lineno())
def validate(self, cloudformation_string):
"""V... | the_stack_v2_python_sparse | terraform_model/validator/CloudformationValidator.py | rubelw/terraform-validator | train | 7 |
f601b0feb922a4b4c310e867c1dd6cb1c09ae4b8 | [
"division = Division()\nif start == end:\n division.max_value = nums[start]\n division.min_value = nums[start]\n division.max_str = str(nums[start])\n division.min_str = str(nums[start])\n return division\nfor i in range(start, end):\n left = self.bruteForce(start, i, nums, '')\n right = self.b... | <|body_start_0|>
division = Division()
if start == end:
division.max_value = nums[start]
division.min_value = nums[start]
division.max_str = str(nums[start])
division.min_str = str(nums[start])
return division
for i in range(start, end)... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bruteForce(self, start, end, nums, res):
"""suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max"""
<|body_0|>
def optimalDivision(self, nums):
""":type nums: List[int] :rtype: str"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_007019 | 3,466 | permissive | [
{
"docstring": "suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max",
"name": "bruteForce",
"signature": "def bruteForce(self, start, end, nums, res)"
},
{
"docstring": ":type nums: List[int] :rtype: str",
"name": "optimalDivision",
"signa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bruteForce(self, start, end, nums, res): suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max
- def optimalDivision(self, nums... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bruteForce(self, start, end, nums, res): suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max
- def optimalDivision(self, nums... | 1ed22267156fb968671731c2e983b0e65f670750 | <|skeleton|>
class Solution:
def bruteForce(self, start, end, nums, res):
"""suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max"""
<|body_0|>
def optimalDivision(self, nums):
""":type nums: List[int] :rtype: str"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def bruteForce(self, start, end, nums, res):
"""suppose we split the list into 2 parts by i result = left.max / right.min min = left.min / right.max"""
division = Division()
if start == end:
division.max_value = nums[start]
division.min_value = nums[st... | the_stack_v2_python_sparse | leetcode/553.py | pingrunhuang/CodeChallenge | train | 0 | |
d65eebc3f1048bf5a6a5ef456aed644d44efba4a | [
"self.value = value\nself.suit = suit\nself.set_name()",
"NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}\nif self.value in NAMES:\n self.name = NAMES[self.value]",
"if self.name is not None:\n return '{} of {}'.format(self.name, self.suit)\nreturn '{} of {}'.format(self.value, self.suit)",
"if ... | <|body_start_0|>
self.value = value
self.suit = suit
self.set_name()
<|end_body_0|>
<|body_start_1|>
NAMES = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
if self.value in NAMES:
self.name = NAMES[self.value]
<|end_body_1|>
<|body_start_2|>
if self.name is... | Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string | PlayingCard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard... | stack_v2_sparse_classes_36k_train_007020 | 2,418 | no_license | [
{
"docstring": "Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value -- the card's value, an integer suit -- the card's suit, a string",
"name": "__init__",
"signature": "def __init__(self, value, suit)"
},
{
"docstring": "Method -- set_na... | 4 | stack_v2_sparse_classes_30k_train_013879 | Implement the Python class `PlayingCard` described below.
Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string
Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance o... | Implement the Python class `PlayingCard` described below.
Class description:
Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string
Method signatures and docstrings:
- def __init__(self, value, suit): Constructor -- creates a new instance o... | b9281f5f959e0268b75baa2c2b1262712da3780f | <|skeleton|>
class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayingCard:
"""Class -- PlayingCard Represents a playing card. Attributes: value -- the card's value, an integer. suit -- the card's suit, a string"""
def __init__(self, value, suit):
"""Constructor -- creates a new instance of PlayingCard Parameters: self -- the current PlayingCard object value... | the_stack_v2_python_sparse | in_class_excercise/Lecture 10/cardgame/playingcard.py | arcPenguinj/CS5001-Intensive-Foundations-of-CS | train | 0 |
71759044cfb810e1a55ad78eeafaa586689091d2 | [
"if not self._should_resubscribe(other):\n assert other\n self.unsubscribe_callback = other.unsubscribe_callback\n return\nif other is not None and other.unsubscribe_callback is not None:\n other.unsubscribe_callback()\n debug_info.remove_subscription(self.hass, other.message_callback, str(other.topi... | <|body_start_0|>
if not self._should_resubscribe(other):
assert other
self.unsubscribe_callback = other.unsubscribe_callback
return
if other is not None and other.unsubscribe_callback is not None:
other.unsubscribe_callback()
debug_info.remove_... | Class to hold data about an active entity topic subscription. | EntitySubscription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntitySubscription:
"""Class to hold data about an active entity topic subscription."""
def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None:
"""Re-subscribe to the new topic if necessary."""
<|body_0|>
async def subscribe(sel... | stack_v2_sparse_classes_36k_train_007021 | 4,730 | permissive | [
{
"docstring": "Re-subscribe to the new topic if necessary.",
"name": "resubscribe_if_necessary",
"signature": "def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None"
},
{
"docstring": "Subscribe to a topic.",
"name": "subscribe",
"signature": ... | 3 | null | Implement the Python class `EntitySubscription` described below.
Class description:
Class to hold data about an active entity topic subscription.
Method signatures and docstrings:
- def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None: Re-subscribe to the new topic if nece... | Implement the Python class `EntitySubscription` described below.
Class description:
Class to hold data about an active entity topic subscription.
Method signatures and docstrings:
- def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None: Re-subscribe to the new topic if nece... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EntitySubscription:
"""Class to hold data about an active entity topic subscription."""
def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None:
"""Re-subscribe to the new topic if necessary."""
<|body_0|>
async def subscribe(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntitySubscription:
"""Class to hold data about an active entity topic subscription."""
def resubscribe_if_necessary(self, hass: HomeAssistant, other: EntitySubscription | None) -> None:
"""Re-subscribe to the new topic if necessary."""
if not self._should_resubscribe(other):
... | the_stack_v2_python_sparse | homeassistant/components/mqtt/subscription.py | home-assistant/core | train | 35,501 |
d590146fbcb62c73398a31b2b245a136c7fedf25 | [
"device = input.device\nctx.P_send = P_send\nctx.P_recv = P_recv\nctx.preserve_batch = preserve_batch\nctx.input_tensor_structure = input_tensor_structure\nctx.output_tensor_structure = output_tensor_structure\nctx.device = device\nif preserve_batch:\n output = zero_volume_tensor(input.shape[0], device=device)\n... | <|body_start_0|>
device = input.device
ctx.P_send = P_send
ctx.P_recv = P_recv
ctx.preserve_batch = preserve_batch
ctx.input_tensor_structure = input_tensor_structure
ctx.output_tensor_structure = output_tensor_structure
ctx.device = device
if preserve_bat... | MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation uses MPI for data movement, accessed through the ``mpi4py`` MPI wrappers. Warning --... | BroadcastFunction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadcastFunction:
"""MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation uses MPI for data movement, accessed th... | stack_v2_sparse_classes_36k_train_007022 | 9,401 | permissive | [
{
"docstring": "Forward function of distributed broadcast layer. This method implements the forward broadcast operation using the ``MPI_Ibcast`` function. Any given worker may participate in two MPI broadcasts, one on the ``P_send`` partition and one on the ``P_recv`` partition. The communication pattern and fu... | 2 | stack_v2_sparse_classes_30k_train_013407 | Implement the Python class `BroadcastFunction` described below.
Class description:
MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation ... | Implement the Python class `BroadcastFunction` described below.
Class description:
MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation ... | a641638bf448cbad3e0a3ec09a1a0bcb7b7432c3 | <|skeleton|>
class BroadcastFunction:
"""MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation uses MPI for data movement, accessed th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BroadcastFunction:
"""MPI-based functional implementation of a distributed broadcast layer. Implements the required `forward()` and adjoint (`backward()`) operations for a distributed Broadcast layer using the PyTorch autograd interface. This implementation uses MPI for data movement, accessed through the ``m... | the_stack_v2_python_sparse | src/distdl/backends/mpi/functional/broadcast.py | distdl/distdl | train | 25 |
ee6e2933def01f9a1d3cfb61c6140e3bd8385917 | [
"progress = ProgressBar(application_graph.n_outgoing_edge_partitions, 'Generating connection holders for reporting connection data.')\ndata_holders = dict()\nfor partition in progress.over(application_graph.outgoing_edge_partitions):\n for edge in partition.edges:\n if isinstance(edge, ProjectionApplicati... | <|body_start_0|>
progress = ProgressBar(application_graph.n_outgoing_edge_partitions, 'Generating connection holders for reporting connection data.')
data_holders = dict()
for partition in progress.over(application_graph.outgoing_edge_partitions):
for edge in partition.edges:
... | Sets up connection holders for reports to use. | SpYNNakerConnectionHolderGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpYNNakerConnectionHolderGenerator:
"""Sets up connection holders for reports to use."""
def __call__(self, application_graph):
""":param application_graph: application graph :type application_graph: ~pacman.model.graphs.application.ApplicationGraph :return: the set of connection hol... | stack_v2_sparse_classes_36k_train_007023 | 2,648 | permissive | [
{
"docstring": ":param application_graph: application graph :type application_graph: ~pacman.model.graphs.application.ApplicationGraph :return: the set of connection holders for after data specification generation :rtype: dict(tuple(ProjectionApplicationEdge, SynapseInformation), ConnectionHolder)",
"name":... | 2 | null | Implement the Python class `SpYNNakerConnectionHolderGenerator` described below.
Class description:
Sets up connection holders for reports to use.
Method signatures and docstrings:
- def __call__(self, application_graph): :param application_graph: application graph :type application_graph: ~pacman.model.graphs.applic... | Implement the Python class `SpYNNakerConnectionHolderGenerator` described below.
Class description:
Sets up connection holders for reports to use.
Method signatures and docstrings:
- def __call__(self, application_graph): :param application_graph: application graph :type application_graph: ~pacman.model.graphs.applic... | 891cfb3046f66185fd8df52d270380fa94c32eab | <|skeleton|>
class SpYNNakerConnectionHolderGenerator:
"""Sets up connection holders for reports to use."""
def __call__(self, application_graph):
""":param application_graph: application graph :type application_graph: ~pacman.model.graphs.application.ApplicationGraph :return: the set of connection hol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpYNNakerConnectionHolderGenerator:
"""Sets up connection holders for reports to use."""
def __call__(self, application_graph):
""":param application_graph: application graph :type application_graph: ~pacman.model.graphs.application.ApplicationGraph :return: the set of connection holders for afte... | the_stack_v2_python_sparse | spynnaker/pyNN/extra_algorithms/spynnaker_connection_holder_generations.py | SpiNNakerManchester/sPyNNaker | train | 101 |
2dba7ede63cbf51a867ad6f5923b6dcce4c5c905 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RelatedContact()",
"from .contact_relationship import ContactRelationship\nfrom .contact_relationship import ContactRelationship\nfields: Dict[str, Callable[[Any], None]] = {'accessConsent': lambda n: setattr(self, 'access_consent', n.... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RelatedContact()
<|end_body_0|>
<|body_start_1|>
from .contact_relationship import ContactRelationship
from .contact_relationship import ContactRelationship
fields: Dict[str, Cal... | RelatedContact | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelatedContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k_train_007024 | 3,694 | 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: RelatedContact",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_020398 | Implement the Python class `RelatedContact` described below.
Class description:
Implement the RelatedContact class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `RelatedContact` described below.
Class description:
Implement the RelatedContact class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RelatedContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelatedContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact:
"""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: RelatedCon... | the_stack_v2_python_sparse | msgraph/generated/models/related_contact.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a7665d44593fad24898df515a1c470e7822976e0 | [
"dl = mode.cache.getData(self)\nif not dl:\n dl = self.compile(mode=mode)\ndl()\nreturn 1",
"dl = displaylist.DisplayList()\ndl.start()\ntry:\n self.do()\n holder = mode.cache.holder(self, dl)\n return dl\nfinally:\n dl.end()",
"if self.textureMode:\n mode = GLE_TEXTURE_ENABLE\n format = se... | <|body_start_0|>
dl = mode.cache.getData(self)
if not dl:
dl = self.compile(mode=mode)
dl()
return 1
<|end_body_0|>
<|body_start_1|>
dl = displaylist.DisplayList()
dl.start()
try:
self.do()
holder = mode.cache.holder(self, dl)
... | Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model view coordinates "ver"/"norm" -- vertex/normal mode "flat"/"cyl"/"sphere" ... | GLEGeom | [
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GLEGeom:
"""Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model view coordinates "ver"/"norm" -- vertex... | stack_v2_sparse_classes_36k_train_007025 | 8,495 | permissive | [
{
"docstring": "Render the geometry",
"name": "render",
"signature": "def render(self, visible=1, lit=1, textured=1, transparent=0, mode=None)"
},
{
"docstring": "Compile the geometry as a display-list",
"name": "compile",
"signature": "def compile(self, mode=None)"
},
{
"docstri... | 3 | null | Implement the Python class `GLEGeom` described below.
Class description:
Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model ... | Implement the Python class `GLEGeom` described below.
Class description:
Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model ... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class GLEGeom:
"""Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model view coordinates "ver"/"norm" -- vertex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GLEGeom:
"""Base class for GLE geometry types Provides the common operations and data seen in the GLE geometry types. Attributes: textureMode -- specification of texture-coordinate generation mode to be passed to GLE, include: "mod" -- if present, use model view coordinates "ver"/"norm" -- vertex/normal mode ... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/extrusions.py | alexus37/AugmentedRealityChess | train | 1 |
4362540d34c6dfc1480a51932857e3e00e03055a | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_direction = choice([-1, 1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([-1, 1])\n y_distance = choice([0, 1, 2, 3, 4])\n ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_direction = choice([-1, 1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction *... | A class to generate random walks. | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in the walk."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007026 | 2,233 | no_license | [
{
"docstring": "Initialize attributes of a walk.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Calculate all the points in the walk.",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016709 | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def fill_walk(self): Calculate all the points in the walk. | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def fill_walk(self): Calculate all the points in the walk.
<|skeleton|>
class RandomWalk:
"""A ... | 4b8310e55bfbebefaea238ea13569aa821eb5ade | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def fill_walk(self):
"""Calculate all the points in the walk."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in the walk.""... | the_stack_v2_python_sparse | random_walk.py | anhnguyendepocen/Math-Modeling-Econ-Finance-Python | train | 0 |
769f986c82f77dbf7d20c4b179ecdffb46db68e4 | [
"num_smooth = left_gauss_linear(num)\nden_smooth = left_gauss_linear(den)\nden_smooth = np.clip(den_smooth, 0, None)\nnum_smooth = np.clip(num_smooth, 0, den_smooth)\nreturn (num_smooth, den_smooth)",
"if isinstance(den, (pd.DataFrame, pd.Series)):\n den = den.values\nif isinstance(num, (pd.DataFrame, pd.Serie... | <|body_start_0|>
num_smooth = left_gauss_linear(num)
den_smooth = left_gauss_linear(den)
den_smooth = np.clip(den_smooth, 0, None)
num_smooth = np.clip(num_smooth, 0, den_smooth)
return (num_smooth, den_smooth)
<|end_body_0|>
<|body_start_1|>
if isinstance(den, (pd.DataF... | Class to fit a hospitalizations indicator using CLI counts from claims-based data. | ClaimsHospIndicator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClaimsHospIndicator:
"""Class to fit a hospitalizations indicator using CLI counts from claims-based data."""
def gauss_smooth(num, den):
"""Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of denominator counts Returns: tuple: (array of smoothed nu... | stack_v2_sparse_classes_36k_train_007027 | 5,159 | permissive | [
{
"docstring": "Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of denominator counts Returns: tuple: (array of smoothed num, array of smoothed den)",
"name": "gauss_smooth",
"signature": "def gauss_smooth(num, den)"
},
{
"docstring": "Adjust for small denomin... | 3 | null | Implement the Python class `ClaimsHospIndicator` described below.
Class description:
Class to fit a hospitalizations indicator using CLI counts from claims-based data.
Method signatures and docstrings:
- def gauss_smooth(num, den): Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of... | Implement the Python class `ClaimsHospIndicator` described below.
Class description:
Class to fit a hospitalizations indicator using CLI counts from claims-based data.
Method signatures and docstrings:
- def gauss_smooth(num, den): Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of... | 0c0ca18f38892c850565edf8bed9d2acaf234354 | <|skeleton|>
class ClaimsHospIndicator:
"""Class to fit a hospitalizations indicator using CLI counts from claims-based data."""
def gauss_smooth(num, den):
"""Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of denominator counts Returns: tuple: (array of smoothed nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClaimsHospIndicator:
"""Class to fit a hospitalizations indicator using CLI counts from claims-based data."""
def gauss_smooth(num, den):
"""Smooth using the left_gauss_linear. Args: num: array of numerator counts den: array of denominator counts Returns: tuple: (array of smoothed num, array of s... | the_stack_v2_python_sparse | claims_hosp/delphi_claims_hosp/indicator.py | alexcoda/covidcast-indicators | train | 0 |
ab28329bfd7daadf808d5e3e8adcb44b821ae29a | [
"groundtruths = load_groundtruth(groundtruth_path, object_path)\nself.example_groundtruths = reverse_object_order(groundtruths)\nself.check_entity = check_entity\nself.iou_threshold = iou_threshold",
"if prediction.image_id != groundtruth.image_id:\n return False\nif self.check_entity and prediction.entity != ... | <|body_start_0|>
groundtruths = load_groundtruth(groundtruth_path, object_path)
self.example_groundtruths = reverse_object_order(groundtruths)
self.check_entity = check_entity
self.iou_threshold = iou_threshold
<|end_body_0|>
<|body_start_1|>
if prediction.image_id != groundtrut... | Evaluator for computing vrd metrics. | VRDEvaluator | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_... | stack_v2_sparse_classes_36k_train_007028 | 16,875 | permissive | [
{
"docstring": "Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_entity: if True, check the object entity when determining whether an object is detected. iou_threshold: the threshold for correctly detected objects.",
"name"... | 5 | null | Implement the Python class `VRDEvaluator` described below.
Class description:
Evaluator for computing vrd metrics.
Method signatures and docstrings:
- def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5): Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground tr... | Implement the Python class `VRDEvaluator` described below.
Class description:
Evaluator for computing vrd metrics.
Method signatures and docstrings:
- def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5): Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground tr... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VRDEvaluator:
"""Evaluator for computing vrd metrics."""
def __init__(self, groundtruth_path, object_path, check_entity=False, iou_threshold=0.5):
"""Instantiates vrd evaluator. Args: groundtruth_path: path to the vrd ground truth. object_path: path to the object ground truth. check_entity: if Tr... | the_stack_v2_python_sparse | visual_relationship/evaluation/evaluate_vrd_lib.py | Jimmy-INL/google-research | train | 1 |
7b17739a8ef79c19e0e2e4e0a5f8b5ee02f5b313 | [
"mes = {'message': 'success'}\nrelations = list()\nfor rule in rules:\n rule['user_id'] = user_id\n rule['group_id'] = group_id\n relations.append(rule)\nwith db.atomic() as transaction:\n try:\n cls.insert_many(rows=relations)\n except Exception as e:\n logger.exception(e)\n pri... | <|body_start_0|>
mes = {'message': 'success'}
relations = list()
for rule in rules:
rule['user_id'] = user_id
rule['group_id'] = group_id
relations.append(rule)
with db.atomic() as transaction:
try:
cls.insert_many(rows=rela... | 记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息 | RuleAndGroupTemplateRelation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuleAndGroupTemplateRelation:
"""记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息"""
def add_relations(cls, user_id: int, rules: list, group_id: int) -> dict:
"""向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id: :param rules: {"rule_id": rule_id, "rule_name": rule_na... | stack_v2_sparse_classes_36k_train_007029 | 25,579 | no_license | [
{
"docstring": "向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id: :param rules: {\"rule_id\": rule_id, \"rule_name\": rule_name, \"api_url\": api_url, \"value\": permission_value} :param group_id: :return:",
"name": "add_relations",
"signature": "def add_relations(cls, user_id: int, rules: list, gr... | 3 | stack_v2_sparse_classes_30k_train_013413 | Implement the Python class `RuleAndGroupTemplateRelation` described below.
Class description:
记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息
Method signatures and docstrings:
- def add_relations(cls, user_id: int, rules: list, group_id: int) -> dict: 向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id... | Implement the Python class `RuleAndGroupTemplateRelation` described below.
Class description:
记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息
Method signatures and docstrings:
- def add_relations(cls, user_id: int, rules: list, group_id: int) -> dict: 向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id... | 3a2bdfd1598bfcdfe56386ec0c46fcede772cbfe | <|skeleton|>
class RuleAndGroupTemplateRelation:
"""记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息"""
def add_relations(cls, user_id: int, rules: list, group_id: int) -> dict:
"""向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id: :param rules: {"rule_id": rule_id, "rule_name": rule_na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RuleAndGroupTemplateRelation:
"""记录权限组模板和权限模板(RawRule)之间关系的表. 系统/酒店管理员在创建角色的时候,实际上都是从这个表拷贝的信息"""
def add_relations(cls, user_id: int, rules: list, group_id: int) -> dict:
"""向权限组模板增加一/多条规则, 这是系统管理员在调整权限组模板时所做的操作. :param user_id: :param rules: {"rule_id": rule_id, "rule_name": rule_name, "api_url"... | the_stack_v2_python_sparse | NewISpider/authorization_package/permission_module.py | SYYDSN/py_projects | train | 0 |
53f0b0b77badfb576f1292878697258b4a42a62b | [
"super().__init__()\nself.eps = eps\nself.register_buffer('weight', torch.ones(nChan))\nself.bias = nn.Parameter(torch.zeros(nChan))",
"z = torch.pow(x, 2)\nz = torch.div(x, torch.sqrt(torch.sum(z, dim=1, keepdim=True) + self.eps))\nif self.weight is not None:\n w = self.weight.unsqueeze(0)\n w = w.unsqueez... | <|body_start_0|>
super().__init__()
self.eps = eps
self.register_buffer('weight', torch.ones(nChan))
self.bias = nn.Parameter(torch.zeros(nChan))
<|end_body_0|>
<|body_start_1|>
z = torch.pow(x, 2)
z = torch.div(x, torch.sqrt(torch.sum(z, dim=1, keepdim=True) + self.eps)... | normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for the affine transformation bias: bias for the affine transformation | TvNorm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TvNorm:
"""normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for the affine transformation bias: bias f... | stack_v2_sparse_classes_36k_train_007030 | 1,881 | permissive | [
{
"docstring": ":param nChan: number of channels for the data you expect to normalize :param eps: small float so no division by 0",
"name": "__init__",
"signature": "def __init__(self, nChan, eps=0.0001)"
},
{
"docstring": ":param x: inputs tensor, second dim is channels example dims: (num image... | 2 | stack_v2_sparse_classes_30k_train_008044 | Implement the Python class `TvNorm` described below.
Class description:
normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for... | Implement the Python class `TvNorm` described below.
Class description:
normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for... | 52acc9fbc1a2640c6ac8922fa18105279ccaea97 | <|skeleton|>
class TvNorm:
"""normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for the affine transformation bias: bias f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TvNorm:
"""normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e., MATLAB notation: z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x Attributes: eps: small float so no division by 0 weight: scaling weight for the affine transformation bias: bias for the affine... | the_stack_v2_python_sparse | modules/TvNorm.py | EmoryMLIP/DynamicBlocks | train | 12 |
1ae57e7e591c9904a329f2288344e8f92f799bd5 | [
"legal_type = value[:re.search('\\\\d', value).start()]\nif legal_type not in BusinessType or not value[value.find(legal_type) + len(legal_type):].isdigit():\n return False\nreturn True",
"if not (business_type in BusinessType and (sequence_val := Business.get_next_value_from_sequence(business_type))):\n re... | <|body_start_0|>
legal_type = value[:re.search('\\d', value).start()]
if legal_type not in BusinessType or not value[value.find(legal_type) + len(legal_type):].isdigit():
return False
return True
<|end_body_0|>
<|body_start_1|>
if not (business_type in BusinessType and (sequ... | The business identifier. | BusinessIdentifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessIdentifier:
"""The business identifier."""
def validate_format(value: str) -> bool:
"""Validate the business identifier."""
<|body_0|>
def next_identifier(business_type: BusinessType) -> Optional[str]:
"""Get the next identifier."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_007031 | 2,482 | permissive | [
{
"docstring": "Validate the business identifier.",
"name": "validate_format",
"signature": "def validate_format(value: str) -> bool"
},
{
"docstring": "Get the next identifier.",
"name": "next_identifier",
"signature": "def next_identifier(business_type: BusinessType) -> Optional[str]"
... | 2 | null | Implement the Python class `BusinessIdentifier` described below.
Class description:
The business identifier.
Method signatures and docstrings:
- def validate_format(value: str) -> bool: Validate the business identifier.
- def next_identifier(business_type: BusinessType) -> Optional[str]: Get the next identifier. | Implement the Python class `BusinessIdentifier` described below.
Class description:
The business identifier.
Method signatures and docstrings:
- def validate_format(value: str) -> bool: Validate the business identifier.
- def next_identifier(business_type: BusinessType) -> Optional[str]: Get the next identifier.
<|s... | d90f11a7b14411b02c07fe97d2c1fc31cd4a9b32 | <|skeleton|>
class BusinessIdentifier:
"""The business identifier."""
def validate_format(value: str) -> bool:
"""Validate the business identifier."""
<|body_0|>
def next_identifier(business_type: BusinessType) -> Optional[str]:
"""Get the next identifier."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessIdentifier:
"""The business identifier."""
def validate_format(value: str) -> bool:
"""Validate the business identifier."""
legal_type = value[:re.search('\\d', value).start()]
if legal_type not in BusinessType or not value[value.find(legal_type) + len(legal_type):].isdigi... | the_stack_v2_python_sparse | legal-api/src/legal_api/core/business.py | bcgov/lear | train | 13 |
8720ec9c64c995aaabc54db0c0d4ead0ac61a467 | [
"if isinstance(key, int):\n return CGAType(key)\nif key not in CGAType._member_map_:\n return extend_enum(CGAType, key, default)\nreturn CGAType[key]",
"if not (isinstance(value, int) and 0 <= value <= 340282366920938463463374607431768211455):\n raise ValueError('%r is not a valid %s' % (value, cls.__nam... | <|body_start_0|>
if isinstance(key, int):
return CGAType(key)
if key not in CGAType._member_map_:
return extend_enum(CGAType, key, default)
return CGAType[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 3402823669209384634633... | [CGAType] CGA Extension Type Tags | CGAType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CGAType:
"""[CGAType] CGA Extension Type Tags"""
def get(key: 'int | str', default: 'int'=-1) -> 'CGAType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value... | stack_v2_sparse_classes_36k_train_007032 | 2,568 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'CGAType'"
},
{
"docstring": "Lookup function used when value is not found. Arg... | 2 | null | Implement the Python class `CGAType` described below.
Class description:
[CGAType] CGA Extension Type Tags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'CGAType': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pri... | Implement the Python class `CGAType` described below.
Class description:
[CGAType] CGA Extension Type Tags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'CGAType': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta pri... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class CGAType:
"""[CGAType] CGA Extension Type Tags"""
def get(key: 'int | str', default: 'int'=-1) -> 'CGAType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CGAType:
"""[CGAType] CGA Extension Type Tags"""
def get(key: 'int | str', default: 'int'=-1) -> 'CGAType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return CGAType(k... | the_stack_v2_python_sparse | pcapkit/const/mh/cga_type.py | JarryShaw/PyPCAPKit | train | 204 |
9131dd94f7147d2ae5c0456635c85662bb7b7b73 | [
"self._domain = domain\nself._title = title\nself._description_placeholder = description_placeholder\nself._allow_multiple = allow_multiple",
"if not self._allow_multiple and self._async_current_entries():\n return self.async_abort(reason='single_instance_allowed')\nif user_input is None:\n return self.asyn... | <|body_start_0|>
self._domain = domain
self._title = title
self._description_placeholder = description_placeholder
self._allow_multiple = allow_multiple
<|end_body_0|>
<|body_start_1|>
if not self._allow_multiple and self._async_current_entries():
return self.async_a... | Handle a webhook config flow. | WebhookFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebhookFlowHandler:
"""Handle a webhook config flow."""
def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None:
"""Initialize the discovery config flow."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, ... | stack_v2_sparse_classes_36k_train_007033 | 9,319 | permissive | [
{
"docstring": "Initialize the discovery config flow.",
"name": "__init__",
"signature": "def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None"
},
{
"docstring": "Handle a user initiated set up flow to create a webhook.",
"name": "async_ste... | 2 | stack_v2_sparse_classes_30k_train_001892 | Implement the Python class `WebhookFlowHandler` described below.
Class description:
Handle a webhook config flow.
Method signatures and docstrings:
- def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None: Initialize the discovery config flow.
- async def async_step_u... | Implement the Python class `WebhookFlowHandler` described below.
Class description:
Handle a webhook config flow.
Method signatures and docstrings:
- def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None: Initialize the discovery config flow.
- async def async_step_u... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class WebhookFlowHandler:
"""Handle a webhook config flow."""
def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None:
"""Initialize the discovery config flow."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebhookFlowHandler:
"""Handle a webhook config flow."""
def __init__(self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool) -> None:
"""Initialize the discovery config flow."""
self._domain = domain
self._title = title
self._description_placeho... | the_stack_v2_python_sparse | homeassistant/helpers/config_entry_flow.py | home-assistant/core | train | 35,501 |
ee86f6ee8c9f008e0cb32cda0caba77dd4d4d44c | [
"self.ps_list = list()\nself.load_rules = load_rules\nself.snapshot_dict = snapshot_dict\nself.parsers_dict = parsers_dict",
"cur_ps_list = get_pid_list()\nif self.ps_list != cur_ps_list:\n ps_killed = at_first_only(self.ps_list, cur_ps_list)\n ps_new = at_first_only(cur_ps_list, self.ps_list)\n self.ps_... | <|body_start_0|>
self.ps_list = list()
self.load_rules = load_rules
self.snapshot_dict = snapshot_dict
self.parsers_dict = parsers_dict
<|end_body_0|>
<|body_start_1|>
cur_ps_list = get_pid_list()
if self.ps_list != cur_ps_list:
ps_killed = at_first_only(self... | Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict. | PsListMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param ... | stack_v2_sparse_classes_36k_train_007034 | 8,176 | no_license | [
{
"docstring": "Constructor. :param load_rules: An already initialized LoadRules object :param snapshot_dict: A dict of {pid : snapshot object}, with one entry {'*system*' : system snapshot} :param parsers_dict: A dict of all available parsers {'parser_name': ParserObject}",
"name": "__init__",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_004970 | Implement the Python class `PsListMonitor` described below.
Class description:
Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict.
Method signatures and docstrings:
- def __init__(self, load_rules: LoadConfig, snaps... | Implement the Python class `PsListMonitor` described below.
Class description:
Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict.
Method signatures and docstrings:
- def __init__(self, load_rules: LoadConfig, snaps... | d0cb02e418edae4c1bacc44fe840701ea0e8bf71 | <|skeleton|>
class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param load_rules: A... | the_stack_v2_python_sparse | main.py | yarinschiller/hamato-yoshi | train | 2 |
1ca6d265f9df277ab75cf687fe583185585a7b04 | [
"super(StoreCartLines, self).__init__(*args, **kwargs)\nself.endpoint = 'ecommerce/stores'\nself.store_id = None\nself.cart_id = None\nself.line_id = None",
"self.store_id = store_id\nself.cart_id = cart_id\nif 'id' not in data:\n raise KeyError('The cart line must have an id')\nif 'product_id' not in data:\n ... | <|body_start_0|>
super(StoreCartLines, self).__init__(*args, **kwargs)
self.endpoint = 'ecommerce/stores'
self.store_id = None
self.cart_id = None
self.line_id = None
<|end_body_0|>
<|body_start_1|>
self.store_id = store_id
self.cart_id = cart_id
if 'id' ... | Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart. | StoreCartLines | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreCartLines:
"""Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, store_id, cart_id,... | stack_v2_sparse_classes_36k_train_007035 | 5,203 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add a new line item to an existing cart. :param store_id: The store id. :type store_id: :py:class:`str` :param cart_id: The id for the cart. :type cart_id: :py:clas... | 6 | null | Implement the Python class `StoreCartLines` described below.
Class description:
Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def... | Implement the Python class `StoreCartLines` described below.
Class description:
Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class StoreCartLines:
"""Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def create(self, store_id, cart_id,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoreCartLines:
"""Each Cart contains one or more Cart Lines, which represent a specific Product Variant that a Customer has added to their shopping cart."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(StoreCartLines, self).__init__(*args, **kwargs)
se... | the_stack_v2_python_sparse | mailchimp3/entities/storecartlines.py | VingtCinq/python-mailchimp | train | 190 |
faec672d29478bb13f3994805bc0df2f5dac5543 | [
"super().__init__()\nself.criterion = nn.MSELoss()\nself.activation = activation\nif input_type == 'maml':\n assert len(layers) == 1, 'Input type is maml. Incompatible with multiple OSO layers.'\n assert layers[0] == 1, f'Input type is maml. Incompatible with {layers[0]} input nodes'\ninfo_size = TYPE_TO_SIZE... | <|body_start_0|>
super().__init__()
self.criterion = nn.MSELoss()
self.activation = activation
if input_type == 'maml':
assert len(layers) == 1, 'Input type is maml. Incompatible with multiple OSO layers.'
assert layers[0] == 1, f'Input type is maml. Incompatible ... | Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear Output layer activation : act_fn Activation function to use in all hidden laye... | MetaLearner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaLearner:
"""Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear Output layer activation : act_fn Activa... | stack_v2_sparse_classes_36k_train_007036 | 9,224 | no_license | [
{
"docstring": "Initialize the network Initialize all layers of the network: - 4 input nodes - 20 nodes in layer 1 - 20 nodes in layer 2 - 1 node in output layer Set all biases to zero Arguments ---------- input_type : str Specifies the input of the OSO network (raw_grads, raw_loss_grads, proc_loss_grads, maml)... | 2 | stack_v2_sparse_classes_30k_train_013867 | Implement the Python class `MetaLearner` described below.
Class description:
Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear ... | Implement the Python class `MetaLearner` described below.
Class description:
Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear ... | 5ffa6cdfe7a5f6cd6e33efc6420cf204d2be906d | <|skeleton|>
class MetaLearner:
"""Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear Output layer activation : act_fn Activa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaLearner:
"""Meta-learner class. This is the meta network that proposes updates for given processed loss and gradient values. ... Attributes ---------- w1 : nn.Linear First dense layer of the neural network w2 : nn.Linear Second dense layer w3: nn.Linear Output layer activation : act_fn Activation function... | the_stack_v2_python_sparse | algorithms/modules/shell.py | janvanrijn/transfer-meta-feature-representations | train | 0 |
b5385b2ef2087e4acc15c570280c6bdc0dfc5f01 | [
"super(generator, self).__init__()\nself.dim_in = dim_in\nself.dim_out = dim_out\nself.img_size = img_size\nself.fc = nn.Sequential(nn.Linear(self.dim_in, 1024), nn.BatchNorm1d(1024), nn.ReLU(), nn.Linear(1024, 128 * (self.img_size // 4) * (self.img_size // 4)), nn.BatchNorm1d(128 * (self.img_size // 4) * (self.img... | <|body_start_0|>
super(generator, self).__init__()
self.dim_in = dim_in
self.dim_out = dim_out
self.img_size = img_size
self.fc = nn.Sequential(nn.Linear(self.dim_in, 1024), nn.BatchNorm1d(1024), nn.ReLU(), nn.Linear(1024, 128 * (self.img_size // 4) * (self.img_size // 4)), nn.Ba... | generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class generator:
def __init__(self, dim_in, dim_out, img_size):
"""Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension"""
<|body_0|>
def forward(self, x):
"""Args: x : (tensor) input tensor"""
... | stack_v2_sparse_classes_36k_train_007037 | 9,065 | no_license | [
{
"docstring": "Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension",
"name": "__init__",
"signature": "def __init__(self, dim_in, dim_out, img_size)"
},
{
"docstring": "Args: x : (tensor) input tensor",
"name": "for... | 2 | stack_v2_sparse_classes_30k_train_012848 | Implement the Python class `generator` described below.
Class description:
Implement the generator class.
Method signatures and docstrings:
- def __init__(self, dim_in, dim_out, img_size): Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension
-... | Implement the Python class `generator` described below.
Class description:
Implement the generator class.
Method signatures and docstrings:
- def __init__(self, dim_in, dim_out, img_size): Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension
-... | 0e057f087296ef6e8236d83598673fb3562bfa2d | <|skeleton|>
class generator:
def __init__(self, dim_in, dim_out, img_size):
"""Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension"""
<|body_0|>
def forward(self, x):
"""Args: x : (tensor) input tensor"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class generator:
def __init__(self, dim_in, dim_out, img_size):
"""Args: dim_in : (int) number of imput channels dim_out : (int) number of output channels img_size : (int) output image dimension"""
super(generator, self).__init__()
self.dim_in = dim_in
self.dim_out = dim_out
... | the_stack_v2_python_sparse | src/model/DRAGAN.py | VCLMW-Pose/MW-Pose | train | 4 | |
f1318d63bfead778c3c56f1c91ec9a95e7f8ef01 | [
"self.log = logging.getLogger()\nself.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)\nself.cols = cols\nself.rows = rows\nself.coordinates = [common.Coordinate(xy[0], xy[1]) for xy in list(product(range(self.rows), range(self.cols)))]\nself.player = None\nself.gamer = N... | <|body_start_0|>
self.log = logging.getLogger()
self.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)
self.cols = cols
self.rows = rows
self.coordinates = [common.Coordinate(xy[0], xy[1]) for xy in list(product(range(self.rows), range(s... | Behaviors class for ai player. | Behavior | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
<|body_0|>
def set_controllers(self, ai_):
"""Set controllers player and ai."""
<|body_1|>
def scan(self):
"""Scan battle field an... | stack_v2_sparse_classes_36k_train_007038 | 3,897 | no_license | [
{
"docstring": "Initialize behavior class.",
"name": "__init__",
"signature": "def __init__(self, cols, rows)"
},
{
"docstring": "Set controllers player and ai.",
"name": "set_controllers",
"signature": "def set_controllers(self, ai_)"
},
{
"docstring": "Scan battle field and ret... | 6 | stack_v2_sparse_classes_30k_train_011292 | Implement the Python class `Behavior` described below.
Class description:
Behaviors class for ai player.
Method signatures and docstrings:
- def __init__(self, cols, rows): Initialize behavior class.
- def set_controllers(self, ai_): Set controllers player and ai.
- def scan(self): Scan battle field and return genera... | Implement the Python class `Behavior` described below.
Class description:
Behaviors class for ai player.
Method signatures and docstrings:
- def __init__(self, cols, rows): Initialize behavior class.
- def set_controllers(self, ai_): Set controllers player and ai.
- def scan(self): Scan battle field and return genera... | 4368f82ee0bcfed9230f8e5af9bf6f89ad173675 | <|skeleton|>
class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
<|body_0|>
def set_controllers(self, ai_):
"""Set controllers player and ai."""
<|body_1|>
def scan(self):
"""Scan battle field an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Behavior:
"""Behaviors class for ai player."""
def __init__(self, cols, rows):
"""Initialize behavior class."""
self.log = logging.getLogger()
self.log.info(__name__ + ': ' + 'def ' + self.__init__.__name__ + '(): ' + self.__init__.__doc__)
self.cols = cols
self.ro... | the_stack_v2_python_sparse | controllers/behaviors.py | DollaR84/forts | train | 0 |
d35203e58402430788deb9c5905e15c3a603bd1b | [
"super().__init__()\nself.name = name\nself.type = type\nself.description = description",
"result = {}\nresult['type'] = self.type\nif self.description is not None:\n result['description'] = self.description\nreturn result"
] | <|body_start_0|>
super().__init__()
self.name = name
self.type = type
self.description = description
<|end_body_0|>
<|body_start_1|>
result = {}
result['type'] = self.type
if self.description is not None:
result['description'] = self.description
... | Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents. | SecurityScheme | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityScheme:
"""Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents."""
def __init__(self, name, type, *, description=None, **kwargs):
"""Initialize the security scheme. :param name: ... | stack_v2_sparse_classes_36k_train_007039 | 3,415 | permissive | [
{
"docstring": "Initialize the security scheme. :param name: The name of the security scheme. :param type: The type of security scheme.",
"name": "__init__",
"signature": "def __init__(self, name, type, *, description=None, **kwargs)"
},
{
"docstring": "JSON representation of the security scheme... | 2 | stack_v2_sparse_classes_30k_train_018867 | Implement the Python class `SecurityScheme` described below.
Class description:
Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents.
Method signatures and docstrings:
- def __init__(self, name, type, *, description=None,... | Implement the Python class `SecurityScheme` described below.
Class description:
Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents.
Method signatures and docstrings:
- def __init__(self, name, type, *, description=None,... | 19e8d396aa9f3b6df28f773d06846d2bb58d1674 | <|skeleton|>
class SecurityScheme:
"""Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents."""
def __init__(self, name, type, *, description=None, **kwargs):
"""Initialize the security scheme. :param name: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecurityScheme:
"""Base class for security schemes. A security scheme is required if security requirements and security schemes should be published in OpenAPI documents."""
def __init__(self, name, type, *, description=None, **kwargs):
"""Initialize the security scheme. :param name: The name of t... | the_stack_v2_python_sparse | src/roax/security.py | lliu8080/roax | train | 0 |
59ed44b3400534bd42e93de074e2aed52fbf383a | [
"self.cluster_info = cluster_info\nself.collection_info = collection_info\nself.database_info = database_info\nself.name = name\nself.mtype = mtype\nself.uuid = uuid",
"if dictionary is None:\n return None\ncluster_info = cohesity_management_sdk.models.mongo_db_cluster.MongoDBCluster.from_dictionary(dictionary... | <|body_start_0|>
self.cluster_info = cluster_info
self.collection_info = collection_info
self.database_info = database_info
self.name = name
self.mtype = mtype
self.uuid = uuid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_info (MongoDBCollection): Information about a mongodb collection, only valid for an entity o... | MongoDBProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoDBProtectionSource:
"""Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_info (MongoDBCollection): Information abo... | stack_v2_sparse_classes_36k_train_007040 | 3,661 | permissive | [
{
"docstring": "Constructor for the MongoDBProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, cluster_info=None, collection_info=None, database_info=None, name=None, mtype=None, uuid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | stack_v2_sparse_classes_30k_train_014855 | Implement the Python class `MongoDBProtectionSource` described below.
Class description:
Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_in... | Implement the Python class `MongoDBProtectionSource` described below.
Class description:
Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_in... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MongoDBProtectionSource:
"""Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_info (MongoDBCollection): Information abo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoDBProtectionSource:
"""Implementation of the 'MongoDBProtectionSource' model. Specifies an Object representing MongoDB. Attributes: cluster_info (MongoDBCluster): Information of a mongodb cluster, only valid for an entity of type kCluster. collection_info (MongoDBCollection): Information about a mongodb ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mongo_db_protection_source.py | cohesity/management-sdk-python | train | 24 |
2c59ba4714b692da191713d7e37ecb104720c5f9 | [
"data = {'result': 'success', 'settings': settings.get_settings_response()}\nresponse = JSONResponse(content=data)\nreturn response",
"response = JSONResponse({'error': \"Not implemented. Please use WebSocket 'welcome' message for session settings instead.\"})\nresponse.status_code = status.HTTP_501_NOT_IMPLEMENT... | <|body_start_0|>
data = {'result': 'success', 'settings': settings.get_settings_response()}
response = JSONResponse(content=data)
return response
<|end_body_0|>
<|body_start_1|>
response = JSONResponse({'error': "Not implemented. Please use WebSocket 'welcome' message for session settin... | HTTP endpoint handler | HttpApiEndpoint | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpApiEndpoint:
"""HTTP endpoint handler"""
def handle_settings_req_get(self):
"""Handle settings GET request"""
<|body_0|>
def handle_settings_req_post(self, req: SettingsRequest, response: Response):
"""Handle settings POST request"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_007041 | 1,018 | permissive | [
{
"docstring": "Handle settings GET request",
"name": "handle_settings_req_get",
"signature": "def handle_settings_req_get(self)"
},
{
"docstring": "Handle settings POST request",
"name": "handle_settings_req_post",
"signature": "def handle_settings_req_post(self, req: SettingsRequest, r... | 2 | stack_v2_sparse_classes_30k_train_006384 | Implement the Python class `HttpApiEndpoint` described below.
Class description:
HTTP endpoint handler
Method signatures and docstrings:
- def handle_settings_req_get(self): Handle settings GET request
- def handle_settings_req_post(self, req: SettingsRequest, response: Response): Handle settings POST request | Implement the Python class `HttpApiEndpoint` described below.
Class description:
HTTP endpoint handler
Method signatures and docstrings:
- def handle_settings_req_get(self): Handle settings GET request
- def handle_settings_req_post(self, req: SettingsRequest, response: Response): Handle settings POST request
<|skel... | 11991dc8d2220fef19e9a5ed10acbb3e6311bca8 | <|skeleton|>
class HttpApiEndpoint:
"""HTTP endpoint handler"""
def handle_settings_req_get(self):
"""Handle settings GET request"""
<|body_0|>
def handle_settings_req_post(self, req: SettingsRequest, response: Response):
"""Handle settings POST request"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpApiEndpoint:
"""HTTP endpoint handler"""
def handle_settings_req_get(self):
"""Handle settings GET request"""
data = {'result': 'success', 'settings': settings.get_settings_response()}
response = JSONResponse(content=data)
return response
def handle_settings_req_p... | the_stack_v2_python_sparse | src/http_api.py | SEPIA-Framework/sepia-stt-server | train | 98 |
eb86410a9ad9d249d855afe9fae8a16d57c45f3b | [
"rls = rules.fromfile(StringIO.StringIO(testfile), '<t>')\nhi = makehi()\nres = rls.eval(hi)\nself.assertEqual(formatrmatch(res), 'b@4 c@8 e@10 f@11 h@14 GLOBAL@-1')\nself.assertEqual(hi.getclasses(), ['b', 'c', 'e', 'f', 'h'])",
"rls = rules.fromfile(StringIO.StringIO('a: NOT ALL\\n'), '<t>')\nhi = makehi()\nsel... | <|body_start_0|>
rls = rules.fromfile(StringIO.StringIO(testfile), '<t>')
hi = makehi()
res = rls.eval(hi)
self.assertEqual(formatrmatch(res), 'b@4 c@8 e@10 f@11 h@14 GLOBAL@-1')
self.assertEqual(hi.getclasses(), ['b', 'c', 'e', 'f', 'h'])
<|end_body_0|>
<|body_start_1|>
... | testRulesEval | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testRulesEval:
def testRulesEval(self):
"""Test that a set of known rules matches properly."""
<|body_0|>
def testOnlySuccessGlobal(self):
"""Test that the synthetic rule GLOBAL is only added at the end of successful matches."""
<|body_1|>
def testGetCna... | stack_v2_sparse_classes_36k_train_007042 | 4,666 | no_license | [
{
"docstring": "Test that a set of known rules matches properly.",
"name": "testRulesEval",
"signature": "def testRulesEval(self)"
},
{
"docstring": "Test that the synthetic rule GLOBAL is only added at the end of successful matches.",
"name": "testOnlySuccessGlobal",
"signature": "def t... | 3 | stack_v2_sparse_classes_30k_val_000411 | Implement the Python class `testRulesEval` described below.
Class description:
Implement the testRulesEval class.
Method signatures and docstrings:
- def testRulesEval(self): Test that a set of known rules matches properly.
- def testOnlySuccessGlobal(self): Test that the synthetic rule GLOBAL is only added at the en... | Implement the Python class `testRulesEval` described below.
Class description:
Implement the testRulesEval class.
Method signatures and docstrings:
- def testRulesEval(self): Test that a set of known rules matches properly.
- def testOnlySuccessGlobal(self): Test that the synthetic rule GLOBAL is only added at the en... | 41341606e831a42ba36f8e64640e98f098bf0489 | <|skeleton|>
class testRulesEval:
def testRulesEval(self):
"""Test that a set of known rules matches properly."""
<|body_0|>
def testOnlySuccessGlobal(self):
"""Test that the synthetic rule GLOBAL is only added at the end of successful matches."""
<|body_1|>
def testGetCna... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class testRulesEval:
def testRulesEval(self):
"""Test that a set of known rules matches properly."""
rls = rules.fromfile(StringIO.StringIO(testfile), '<t>')
hi = makehi()
res = rls.eval(hi)
self.assertEqual(formatrmatch(res), 'b@4 c@8 e@10 f@11 h@14 GLOBAL@-1')
self.... | the_stack_v2_python_sparse | test_rules.py | siebenmann/portnanny | train | 2 | |
ddaf80b053ab8b00e67cc2abe83ec26cf89db2ff | [
"self.dirpath = dirpath\nself.tee_std = None\nself.tee_err = None\nself.output = None",
"self.output = open(os.path.join(self.dirpath, 'output.log'), 'w')\nself.tee_std = sys.stdout if isinstance(sys.stdout, Tee) else Tee(sys.stdout)\nself.tee_err = sys.stderr if isinstance(sys.stderr, Tee) else Tee(sys.stderr)\n... | <|body_start_0|>
self.dirpath = dirpath
self.tee_std = None
self.tee_err = None
self.output = None
<|end_body_0|>
<|body_start_1|>
self.output = open(os.path.join(self.dirpath, 'output.log'), 'w')
self.tee_std = sys.stdout if isinstance(sys.stdout, Tee) else Tee(sys.stdo... | log hander | LogHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogHandler:
"""log hander"""
def __init__(self, dirpath):
"""@para dirpath: the output dir for log file"""
<|body_0|>
def start(self):
"""start catch output to log file"""
<|body_1|>
def end(self):
"""close log file"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_007043 | 2,417 | permissive | [
{
"docstring": "@para dirpath: the output dir for log file",
"name": "__init__",
"signature": "def __init__(self, dirpath)"
},
{
"docstring": "start catch output to log file",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "close log file",
"name": "end",
... | 3 | null | Implement the Python class `LogHandler` described below.
Class description:
log hander
Method signatures and docstrings:
- def __init__(self, dirpath): @para dirpath: the output dir for log file
- def start(self): start catch output to log file
- def end(self): close log file | Implement the Python class `LogHandler` described below.
Class description:
log hander
Method signatures and docstrings:
- def __init__(self, dirpath): @para dirpath: the output dir for log file
- def start(self): start catch output to log file
- def end(self): close log file
<|skeleton|>
class LogHandler:
"""lo... | 786a4de29c30b47f885d8ad9cb2d110a08919ebd | <|skeleton|>
class LogHandler:
"""log hander"""
def __init__(self, dirpath):
"""@para dirpath: the output dir for log file"""
<|body_0|>
def start(self):
"""start catch output to log file"""
<|body_1|>
def end(self):
"""close log file"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogHandler:
"""log hander"""
def __init__(self, dirpath):
"""@para dirpath: the output dir for log file"""
self.dirpath = dirpath
self.tee_std = None
self.tee_err = None
self.output = None
def start(self):
"""start catch output to log file"""
s... | the_stack_v2_python_sparse | meta-iotqa/lib/baserunner/util/log.py | intel/intel-iot-refkit | train | 38 |
d01e4f7e3b3ee39208237293aaf6869aefbce9e5 | [
"node1 = ('a', [None])\nsource = [node1]\nnodes = [node1]\nself.assertEqual(make_dafsa.top_sort(source), nodes)",
"node4 = ('d', [None])\nnode3 = ('c', [node4])\nnode2 = ('b', [node4])\nnode1 = ('a', [node2, node3])\nsource = [node1]\nnodes = make_dafsa.top_sort(source)\nself.assertLess(nodes.index(node1), nodes.... | <|body_start_0|>
node1 = ('a', [None])
source = [node1]
nodes = [node1]
self.assertEqual(make_dafsa.top_sort(source), nodes)
<|end_body_0|>
<|body_start_1|>
node4 = ('d', [None])
node3 = ('c', [node4])
node2 = ('b', [node4])
node1 = ('a', [node2, node3])
... | TopSortTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopSortTest:
def testNode(self):
"""Tests a DAFSA with one node can be sorted."""
<|body_0|>
def testDiamond(self):
"""Tests nodes in a diamond can be sorted."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
node1 = ('a', [None])
source = [no... | stack_v2_sparse_classes_36k_train_007044 | 20,781 | permissive | [
{
"docstring": "Tests a DAFSA with one node can be sorted.",
"name": "testNode",
"signature": "def testNode(self)"
},
{
"docstring": "Tests nodes in a diamond can be sorted.",
"name": "testDiamond",
"signature": "def testDiamond(self)"
}
] | 2 | null | Implement the Python class `TopSortTest` described below.
Class description:
Implement the TopSortTest class.
Method signatures and docstrings:
- def testNode(self): Tests a DAFSA with one node can be sorted.
- def testDiamond(self): Tests nodes in a diamond can be sorted. | Implement the Python class `TopSortTest` described below.
Class description:
Implement the TopSortTest class.
Method signatures and docstrings:
- def testNode(self): Tests a DAFSA with one node can be sorted.
- def testDiamond(self): Tests nodes in a diamond can be sorted.
<|skeleton|>
class TopSortTest:
def te... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class TopSortTest:
def testNode(self):
"""Tests a DAFSA with one node can be sorted."""
<|body_0|>
def testDiamond(self):
"""Tests nodes in a diamond can be sorted."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopSortTest:
def testNode(self):
"""Tests a DAFSA with one node can be sorted."""
node1 = ('a', [None])
source = [node1]
nodes = [node1]
self.assertEqual(make_dafsa.top_sort(source), nodes)
def testDiamond(self):
"""Tests nodes in a diamond can be sorted.""... | the_stack_v2_python_sparse | tools/media_engagement_preload/make_dafsa_unittest.py | chromium/chromium | train | 17,408 | |
a4a14ec4408c3472e58da168f66493df0c50676c | [
"if value > 2 ** 31:\n value = value - 2 ** 32\npayload = struct.pack('<BBi', 60, reg, value)\nreply = self.send_and_wait_reply(payload, cmd_id)\nif reply[0] != 129:\n raise RuntimeError('Unexpected reply code')\nreturn",
"payload = struct.pack('<BB', 61, reg)\nreply = self.send_and_wait_reply(payload, cmd_... | <|body_start_0|>
if value > 2 ** 31:
value = value - 2 ** 32
payload = struct.pack('<BBi', 60, reg, value)
reply = self.send_and_wait_reply(payload, cmd_id)
if reply[0] != 129:
raise RuntimeError('Unexpected reply code')
return
<|end_body_0|>
<|body_start... | S3GPort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3GPort:
def S3G_OUTPUT(self, reg, value, cmd_id=None):
"""Set output to value"""
<|body_0|>
def S3G_INPUT(self, reg, cmd_id=None):
"""Get value of input @return value"""
<|body_1|>
def S3G_STB(self, value, cmd_id=None):
"""Send strobe"""
... | stack_v2_sparse_classes_36k_train_007045 | 3,229 | no_license | [
{
"docstring": "Set output to value",
"name": "S3G_OUTPUT",
"signature": "def S3G_OUTPUT(self, reg, value, cmd_id=None)"
},
{
"docstring": "Get value of input @return value",
"name": "S3G_INPUT",
"signature": "def S3G_INPUT(self, reg, cmd_id=None)"
},
{
"docstring": "Send strobe"... | 6 | stack_v2_sparse_classes_30k_train_014219 | Implement the Python class `S3GPort` described below.
Class description:
Implement the S3GPort class.
Method signatures and docstrings:
- def S3G_OUTPUT(self, reg, value, cmd_id=None): Set output to value
- def S3G_INPUT(self, reg, cmd_id=None): Get value of input @return value
- def S3G_STB(self, value, cmd_id=None)... | Implement the Python class `S3GPort` described below.
Class description:
Implement the S3GPort class.
Method signatures and docstrings:
- def S3G_OUTPUT(self, reg, value, cmd_id=None): Set output to value
- def S3G_INPUT(self, reg, cmd_id=None): Get value of input @return value
- def S3G_STB(self, value, cmd_id=None)... | 1f77cf0ced7399531b370720c1fc4bab5a0dda12 | <|skeleton|>
class S3GPort:
def S3G_OUTPUT(self, reg, value, cmd_id=None):
"""Set output to value"""
<|body_0|>
def S3G_INPUT(self, reg, cmd_id=None):
"""Get value of input @return value"""
<|body_1|>
def S3G_STB(self, value, cmd_id=None):
"""Send strobe"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3GPort:
def S3G_OUTPUT(self, reg, value, cmd_id=None):
"""Set output to value"""
if value > 2 ** 31:
value = value - 2 ** 32
payload = struct.pack('<BBi', 60, reg, value)
reply = self.send_and_wait_reply(payload, cmd_id)
if reply[0] != 129:
rais... | the_stack_v2_python_sparse | host_soft/valurap2/valurap2/commands.py | sevikkk/valurap | train | 0 | |
7e211fd2c0414dcfea889002ba45d2d8c6c78b07 | [
"ret_data = []\nfunction_query = FunctionGenerator.extend()\nname = self.get_argument('name', None)\nif name is not None:\n function_query = function_query.filter(FunctionGenerator.name == name)\nfunction_query = function_query.order_by(FunctionGenerator.add_time.desc())\nfunctions = await self.application.objec... | <|body_start_0|>
ret_data = []
function_query = FunctionGenerator.extend()
name = self.get_argument('name', None)
if name is not None:
function_query = function_query.filter(FunctionGenerator.name == name)
function_query = function_query.order_by(FunctionGenerator.add... | FunctionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionHandler:
async def get(self, *args, **kwargs):
"""获取内置函数列表"""
<|body_0|>
async def post(self, *args, **kwargs):
"""增加内置函数数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret_data = []
function_query = FunctionGenerator.extend()
... | stack_v2_sparse_classes_36k_train_007046 | 17,374 | permissive | [
{
"docstring": "获取内置函数列表",
"name": "get",
"signature": "async def get(self, *args, **kwargs)"
},
{
"docstring": "增加内置函数数据",
"name": "post",
"signature": "async def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000569 | Implement the Python class `FunctionHandler` described below.
Class description:
Implement the FunctionHandler class.
Method signatures and docstrings:
- async def get(self, *args, **kwargs): 获取内置函数列表
- async def post(self, *args, **kwargs): 增加内置函数数据 | Implement the Python class `FunctionHandler` described below.
Class description:
Implement the FunctionHandler class.
Method signatures and docstrings:
- async def get(self, *args, **kwargs): 获取内置函数列表
- async def post(self, *args, **kwargs): 增加内置函数数据
<|skeleton|>
class FunctionHandler:
async def get(self, *args... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class FunctionHandler:
async def get(self, *args, **kwargs):
"""获取内置函数列表"""
<|body_0|>
async def post(self, *args, **kwargs):
"""增加内置函数数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionHandler:
async def get(self, *args, **kwargs):
"""获取内置函数列表"""
ret_data = []
function_query = FunctionGenerator.extend()
name = self.get_argument('name', None)
if name is not None:
function_query = function_query.filter(FunctionGenerator.name == name)... | the_stack_v2_python_sparse | apps/project/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
bcf1b9c13fa954c345b9ae9778b1cea8e402d049 | [
"super(MobiusMatvec, self).__init__()\nself.min_norm = min_norm\nself.norm_k = Norm(axis=-1, keep_dims=True)\nself.artanh = Artanh()\nself.norm_k = Norm(axis=-1, keep_dims=True)\nself.clamp_min = ClampMin()\nself.transpose = Transpose()\nself.clamp_tanh = ClampTanh()",
"sqrt_c = c ** 0.5\nx_norm = self.clamp_min(... | <|body_start_0|>
super(MobiusMatvec, self).__init__()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.artanh = Artanh()
self.norm_k = Norm(axis=-1, keep_dims=True)
self.clamp_min = ClampMin()
self.transpose = Transpose()
self.clam... | mobius matvec class | MobiusMatvec | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobiusMatvec:
"""mobius matvec class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, m, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(MobiusMatvec, self).__init__()
self... | stack_v2_sparse_classes_36k_train_007047 | 8,596 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, min_norm)"
},
{
"docstring": "class construction",
"name": "construct",
"signature": "def construct(self, m, x, c)"
}
] | 2 | null | Implement the Python class `MobiusMatvec` described below.
Class description:
mobius matvec class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, m, x, c): class construction | Implement the Python class `MobiusMatvec` described below.
Class description:
mobius matvec class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, m, x, c): class construction
<|skeleton|>
class MobiusMatvec:
"""mobius matvec class"""
def __init__(self, min_no... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MobiusMatvec:
"""mobius matvec class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, m, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobiusMatvec:
"""mobius matvec class"""
def __init__(self, min_norm):
"""init fun"""
super(MobiusMatvec, self).__init__()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.artanh = Artanh()
self.norm_k = Norm(axis=-1, keep_dims=True)... | the_stack_v2_python_sparse | research/nlp/hypertext/src/poincare.py | mindspore-ai/models | train | 301 |
262b53384d9712e7e1fee2502c0f1f7ff7cabf62 | [
"res, q = ([], [root])\nif not root:\n return []\nwhile q:\n res.append([curr.val for curr in q])\n q = [child for curr in q for child in (curr.left, curr.right) if child]\nreturn res",
"def levelHelper(node, lvl):\n if not node:\n return\n if not res or len(res) < lvl:\n res.append([... | <|body_start_0|>
res, q = ([], [root])
if not root:
return []
while q:
res.append([curr.val for curr in q])
q = [child for curr in q for child in (curr.left, curr.right) if child]
return res
<|end_body_0|>
<|body_start_1|>
def levelHelper(node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
"""recursive solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res, q = ([], [root])
if not root:
... | stack_v2_sparse_classes_36k_train_007048 | 800 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": "recursive solution",
"name": "levelOrder2",
"signature": "def levelOrder2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000970 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): recursive solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): recursive solution
<|skeleton|>
class Solution:
def levelOrder(self,... | 4d2b4e322f92de71c7d13c9a2289a422242da38f | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
"""recursive solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
res, q = ([], [root])
if not root:
return []
while q:
res.append([curr.val for curr in q])
q = [child for curr in q for child in (curr.left, curr.right) ... | the_stack_v2_python_sparse | leetcode/tree/102_binary_tree_level_order_traversal.py | Lance117/Etudes | train | 0 | |
8eca9004b8cb8ebbf846064d9063fb1a18c325e9 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.dominating_set = set()\nself.cardinality = 0\nself.source = None",
"used = set()\nif source is not None:\n self.source = source\n self.dominating_set.add(source)\n used.add(source)\n used.update(self.grap... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.dominating_set = set()
self.cardinality = 0
self.source = None
<|end_body_0|>
<|body_start_1|>
used = set()
if source is not None:
s... | Find a (unordered sequential) dominating set in O(V+E) time. | UnorderedSequentialDominatingSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_007049 | 977 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000300 | Implement the Python class `UnorderedSequentialDominatingSet` described below.
Class description:
Find a (unordered sequential) dominating set in O(V+E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `UnorderedSequentialDominatingSet` described below.
Class description:
Find a (unordered sequential) dominating set in O(V+E) time.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnorderedSequentialDominatingSet:
"""Find a (unordered sequential) dominating set in O(V+E) time."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.dominat... | the_stack_v2_python_sparse | graphtheory/dominatingsets/dsetus.py | kgashok/graphs-dict | train | 0 |
1e9cd14c126d3471fd52137100977ed7cb0854cb | [
"func_name = sys._getframe().f_code.co_name\nres = self.get_result(func_name)\nexpect_result = self.get_expect_result(func_name)\nactivityInfo_list = res[0].json()['data']\nactual_result = res[0].json()['errmsg']\nself.assertIn(actual_result, expect_result)\nself.assertIsNotNone(activityInfo_list)\ngl.set_value('ac... | <|body_start_0|>
func_name = sys._getframe().f_code.co_name
res = self.get_result(func_name)
expect_result = self.get_expect_result(func_name)
activityInfo_list = res[0].json()['data']
actual_result = res[0].json()['errmsg']
self.assertIn(actual_result, expect_result)
... | OperationActivityConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
<|body_0|>
def test_urine_v2_activityInfo_update(self):
"""更新运营活动配置信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
func_name = sys._getfra... | stack_v2_sparse_classes_36k_train_007050 | 1,847 | no_license | [
{
"docstring": "运营活动配置列表 :return:",
"name": "test_urine_v2_activityInfo_list",
"signature": "def test_urine_v2_activityInfo_list(self)"
},
{
"docstring": "更新运营活动配置信息 :return:",
"name": "test_urine_v2_activityInfo_update",
"signature": "def test_urine_v2_activityInfo_update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004882 | Implement the Python class `OperationActivityConfiguration` described below.
Class description:
Implement the OperationActivityConfiguration class.
Method signatures and docstrings:
- def test_urine_v2_activityInfo_list(self): 运营活动配置列表 :return:
- def test_urine_v2_activityInfo_update(self): 更新运营活动配置信息 :return: | Implement the Python class `OperationActivityConfiguration` described below.
Class description:
Implement the OperationActivityConfiguration class.
Method signatures and docstrings:
- def test_urine_v2_activityInfo_list(self): 运营活动配置列表 :return:
- def test_urine_v2_activityInfo_update(self): 更新运营活动配置信息 :return:
<|ske... | 6837a07ff200b610e7ba799a52543493848b6026 | <|skeleton|>
class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
<|body_0|>
def test_urine_v2_activityInfo_update(self):
"""更新运营活动配置信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
func_name = sys._getframe().f_code.co_name
res = self.get_result(func_name)
expect_result = self.get_expect_result(func_name)
activityInfo_list = res[0].json()['data']
... | the_stack_v2_python_sparse | run/operation_management/test_operation_activity_configuration.py | liwei123a/APITestFrame | train | 0 | |
3005926d3d3dd19c2a398e44fbd6d17401ea7737 | [
"re = Trader(userLogin).addTrader(send_data['traderName'], send_data['parkName'], send_data['account'], send_data['couponName'])\nresult = re\nself.save_data('account', send_data['account'])\nAssertions().assert_in_text(result, expect['addTraderMessage'])",
"re = Trader(userLogin).addSell(send_data['parkName'], s... | <|body_start_0|>
re = Trader(userLogin).addTrader(send_data['traderName'], send_data['parkName'], send_data['account'], send_data['couponName'])
result = re
self.save_data('account', send_data['account'])
Assertions().assert_in_text(result, expect['addTraderMessage'])
<|end_body_0|>
<|b... | 商家售卖-在商家管理页面售卖券 | TestTraderSell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTraderSell:
"""商家售卖-在商家管理页面售卖券"""
def test_addTrader(self, userLogin, send_data, expect):
"""新增商户"""
<|body_0|>
def test_traderSell(self, userLogin, send_data, expect):
"""商家售卖"""
<|body_1|>
def test_grantCouponToCar(self, weiXinLogin, send_data,... | stack_v2_sparse_classes_36k_train_007051 | 2,412 | no_license | [
{
"docstring": "新增商户",
"name": "test_addTrader",
"signature": "def test_addTrader(self, userLogin, send_data, expect)"
},
{
"docstring": "商家售卖",
"name": "test_traderSell",
"signature": "def test_traderSell(self, userLogin, send_data, expect)"
},
{
"docstring": "商家下发优惠劵",
"nam... | 5 | null | Implement the Python class `TestTraderSell` described below.
Class description:
商家售卖-在商家管理页面售卖券
Method signatures and docstrings:
- def test_addTrader(self, userLogin, send_data, expect): 新增商户
- def test_traderSell(self, userLogin, send_data, expect): 商家售卖
- def test_grantCouponToCar(self, weiXinLogin, send_data, exp... | Implement the Python class `TestTraderSell` described below.
Class description:
商家售卖-在商家管理页面售卖券
Method signatures and docstrings:
- def test_addTrader(self, userLogin, send_data, expect): 新增商户
- def test_traderSell(self, userLogin, send_data, expect): 商家售卖
- def test_grantCouponToCar(self, weiXinLogin, send_data, exp... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestTraderSell:
"""商家售卖-在商家管理页面售卖券"""
def test_addTrader(self, userLogin, send_data, expect):
"""新增商户"""
<|body_0|>
def test_traderSell(self, userLogin, send_data, expect):
"""商家售卖"""
<|body_1|>
def test_grantCouponToCar(self, weiXinLogin, send_data,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTraderSell:
"""商家售卖-在商家管理页面售卖券"""
def test_addTrader(self, userLogin, send_data, expect):
"""新增商户"""
re = Trader(userLogin).addTrader(send_data['traderName'], send_data['parkName'], send_data['account'], send_data['couponName'])
result = re
self.save_data('account', se... | the_stack_v2_python_sparse | test_suite/parkingManage/businessCoupon/test_traderSell.py | oyebino/pomp_api | train | 1 |
9ac095ce6475e48891ee21421a8551c8a64ec23d | [
"sensor = None\nif config['type'].lower() == 'gpio':\n sensor = NanpyGPIOSensor(self.mudpi, config)\nelif config['type'].lower() == 'dht':\n sensor = NanpyDHTSensor(self.mudpi, config)\nelif config['type'].lower() == 'dallas_temperature':\n pass\nif sensor:\n node = self.extension.nodes[config['node']]\... | <|body_start_0|>
sensor = None
if config['type'].lower() == 'gpio':
sensor = NanpyGPIOSensor(self.mudpi, config)
elif config['type'].lower() == 'dht':
sensor = NanpyDHTSensor(self.mudpi, config)
elif config['type'].lower() == 'dallas_temperature':
pass... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy sensor components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy sensor config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sensor = None
if config['type'].low... | stack_v2_sparse_classes_36k_train_007052 | 8,457 | permissive | [
{
"docstring": "Load Nanpy sensor components from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the Nanpy sensor config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006229 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy sensor components from configs
- def validate(self, config): Validate the Nanpy sensor config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy sensor components from configs
- def validate(self, config): Validate the Nanpy sensor config
<|skeleton|>
class Interface:
def load(se... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy sensor components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy sensor config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface:
def load(self, config):
"""Load Nanpy sensor components from configs"""
sensor = None
if config['type'].lower() == 'gpio':
sensor = NanpyGPIOSensor(self.mudpi, config)
elif config['type'].lower() == 'dht':
sensor = NanpyDHTSensor(self.mudpi, c... | the_stack_v2_python_sparse | mudpi/extensions/nanpy/sensor.py | mistasp0ck/mudpi-core | train | 0 | |
0720185da9c6c2d329924c06129f3d9b830bc79e | [
"parent_pk = kwargs.pop('parent_pk')\nfilters = super(SubResourceView, cls).build_filters(query_dict, **kwargs)\nfilters[cls.parent_attr] = parent_pk\nreturn filters",
"context = super(SubResourceView, self).get_list_context(request, objs, **kwargs)\ncontext[self.parent_attr] = self.parent_model.objects.get(pk=kw... | <|body_start_0|>
parent_pk = kwargs.pop('parent_pk')
filters = super(SubResourceView, cls).build_filters(query_dict, **kwargs)
filters[cls.parent_attr] = parent_pk
return filters
<|end_body_0|>
<|body_start_1|>
context = super(SubResourceView, self).get_list_context(request, obj... | Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the model, the templates, the edit form and the permissions. | SubResourceView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubResourceView:
"""Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the model, the templates, the edit form and the... | stack_v2_sparse_classes_36k_train_007053 | 17,671 | no_license | [
{
"docstring": "Override to filter by parent as well.",
"name": "build_filters",
"signature": "def build_filters(cls, query_dict, **kwargs)"
},
{
"docstring": "Override to include parent instance.",
"name": "get_list_context",
"signature": "def get_list_context(self, request, objs, **kwa... | 4 | null | Implement the Python class `SubResourceView` described below.
Class description:
Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the mode... | Implement the Python class `SubResourceView` described below.
Class description:
Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the mode... | 4dcf0e6a37e8753ae9d69d663c0c280fcca0a26c | <|skeleton|>
class SubResourceView:
"""Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the model, the templates, the edit form and the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubResourceView:
"""Base class for resource views that provide the full set of CRUD operations for a model's collection (list) and instance (detail) as a subresource of another object. In most cases, you won't need to modify any methods, only assign the model, the templates, the edit form and the permissions.... | the_stack_v2_python_sparse | apps/common/views/base.py | ESCL/pjtracker | train | 1 |
64741b469b3d67d1939f52548f44af329b3b8ad6 | [
"model_dir = os.path.join(home, 'experimental', 'fast-seg-label')\nexp = os.path.join(model_dir, 'polyrnn_scalabel', 'Experiments', 'tool.json')\nnet = os.path.join(model_dir, 'model_weights', 'ggnn_epoch5_step14000.pth')\nself.tool = Tool(exp, net)",
"inputs = []\nfor img, bbox in zip(imgs, bboxes):\n instanc... | <|body_start_0|>
model_dir = os.path.join(home, 'experimental', 'fast-seg-label')
exp = os.path.join(model_dir, 'polyrnn_scalabel', 'Experiments', 'tool.json')
net = os.path.join(model_dir, 'model_weights', 'ggnn_epoch5_step14000.pth')
self.tool = Tool(exp, net)
<|end_body_0|>
<|body_st... | Class to interface with polyrnn model. | PolyrnnAdapter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolyrnnAdapter:
"""Class to interface with polyrnn model."""
def __init__(self, home: str) -> None:
"""Initialize."""
<|body_0|>
def convert_rect_to_poly(self, imgs: List[NDArrayU8], bboxes: List[List[float]]) -> List[List[List[float]]]:
"""Convert rectangles to ... | stack_v2_sparse_classes_36k_train_007054 | 1,507 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, home: str) -> None"
},
{
"docstring": "Convert rectangles to polygons.",
"name": "convert_rect_to_poly",
"signature": "def convert_rect_to_poly(self, imgs: List[NDArrayU8], bboxes: List[List[float]]) -> Li... | 2 | null | Implement the Python class `PolyrnnAdapter` described below.
Class description:
Class to interface with polyrnn model.
Method signatures and docstrings:
- def __init__(self, home: str) -> None: Initialize.
- def convert_rect_to_poly(self, imgs: List[NDArrayU8], bboxes: List[List[float]]) -> List[List[List[float]]]: C... | Implement the Python class `PolyrnnAdapter` described below.
Class description:
Class to interface with polyrnn model.
Method signatures and docstrings:
- def __init__(self, home: str) -> None: Initialize.
- def convert_rect_to_poly(self, imgs: List[NDArrayU8], bboxes: List[List[float]]) -> List[List[List[float]]]: C... | 96ad0fffe06a3c9bdd83453c8ec9b70cbbbde641 | <|skeleton|>
class PolyrnnAdapter:
"""Class to interface with polyrnn model."""
def __init__(self, home: str) -> None:
"""Initialize."""
<|body_0|>
def convert_rect_to_poly(self, imgs: List[NDArrayU8], bboxes: List[List[float]]) -> List[List[List[float]]]:
"""Convert rectangles to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolyrnnAdapter:
"""Class to interface with polyrnn model."""
def __init__(self, home: str) -> None:
"""Initialize."""
model_dir = os.path.join(home, 'experimental', 'fast-seg-label')
exp = os.path.join(model_dir, 'polyrnn_scalabel', 'Experiments', 'tool.json')
net = os.pat... | the_stack_v2_python_sparse | scalabel/bot/polyrnn_adapter.py | scalabel/scalabel | train | 530 |
78ff6b848e1a5e08057f166e22ea8b605f045956 | [
"self.client_node = SlaveNode(debug=debug)\nself.client_node.initialize()\nself.client_node.wait_for_initialize()\nself.debug = debug\nself.images = None",
"self.optimizer = optimizer(debug=True)\nwhile True:\n task_data = self.client_node.wait_for_task()\n if not self.images:\n self.images = self.op... | <|body_start_0|>
self.client_node = SlaveNode(debug=debug)
self.client_node.initialize()
self.client_node.wait_for_initialize()
self.debug = debug
self.images = None
<|end_body_0|>
<|body_start_1|>
self.optimizer = optimizer(debug=True)
while True:
ta... | Provides the logic for a worker class that dynamically optimizes a scenario | OptimizerWorker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
<|body_0|>
def run(self, optimizer):
"""Run the worker with a specific optimizer. :param optimizer: The... | stack_v2_sparse_classes_36k_train_007055 | 1,167 | permissive | [
{
"docstring": "Initialize the worker",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Run the worker with a specific optimizer. :param optimizer: The optimizer to use during optimization",
"name": "run",
"signature": "def run(self, optimizer)"
}
... | 2 | null | Implement the Python class `OptimizerWorker` described below.
Class description:
Provides the logic for a worker class that dynamically optimizes a scenario
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize the worker
- def run(self, optimizer): Run the worker with a specific optimizer. ... | Implement the Python class `OptimizerWorker` described below.
Class description:
Provides the logic for a worker class that dynamically optimizes a scenario
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize the worker
- def run(self, optimizer): Run the worker with a specific optimizer. ... | fc31dd8de624f4a71c2c4b1bfe47a18f0b5d2f84 | <|skeleton|>
class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
<|body_0|>
def run(self, optimizer):
"""Run the worker with a specific optimizer. :param optimizer: The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizerWorker:
"""Provides the logic for a worker class that dynamically optimizes a scenario"""
def __init__(self, debug=False):
"""Initialize the worker"""
self.client_node = SlaveNode(debug=debug)
self.client_node.initialize()
self.client_node.wait_for_initialize()
... | the_stack_v2_python_sparse | SUASImageParser/optimizers/worker.py | peterhusisian/SUAS-Competition | train | 0 |
335aff783eebda66163e3899c8dc5adea5ddc7a6 | [
"self.n = len(nums)\nself.c = [0] * (self.n + 1)\nself.f = nums\nfor i in range(self.n):\n k = i + 1\n while k < self.n + 1:\n self.c[k] += self.f[i]\n k += k & -k",
"diff = val - self.f[i]\nself.f[i] = val\nk = i + 1\nwhile k < self.n + 1:\n self.c[k] += diff\n k += k & -k",
"res = 0\... | <|body_start_0|>
self.n = len(nums)
self.c = [0] * (self.n + 1)
self.f = nums
for i in range(self.n):
k = i + 1
while k < self.n + 1:
self.c[k] += self.f[i]
k += k & -k
<|end_body_0|>
<|body_start_1|>
diff = val - self.f[i]... | NumArray | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k_train_007056 | 1,972 | permissive | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: int",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum o... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | 6dfa0a4df9ec07b2c746a13c8257780880ea04af | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.n = len(nums)
self.c = [0] * (self.n + 1)
self.f = nums
for i in range(self.n):
k = i + 1
while k < self.n + 1:
self.c[k] +=... | the_stack_v2_python_sparse | 0307.Range Sum Query - Mutable/solution.py | zhlinh/leetcode | train | 0 | |
33af63cfde207083a95bc8c6cb47340419280a95 | [
"banned_set = set(banned)\nwords = [w.lower() for w in re.split('[^\\\\w]+', paragraph) if w]\nwords = [w for w in words if w not in banned_set]\ncount = defaultdict(int)\nfor w in words:\n count[w] += 1\ncommon_word = None\nmax_count = 0\nfor w, c in count.items():\n if c > max_count:\n max_count = c\... | <|body_start_0|>
banned_set = set(banned)
words = [w.lower() for w in re.split('[^\\w]+', paragraph) if w]
words = [w for w in words if w not in banned_set]
count = defaultdict(int)
for w in words:
count[w] += 1
common_word = None
max_count = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str:
"""Regex and dictionary."""
<|body_0|>
def mostCommonWord_v2(self, paragraph: str, banned: List[str]) -> str:
"""Regex and max (with key)"""
<|body_1|>
def mostCommonWord_v3... | stack_v2_sparse_classes_36k_train_007057 | 2,866 | no_license | [
{
"docstring": "Regex and dictionary.",
"name": "mostCommonWord_v1",
"signature": "def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str"
},
{
"docstring": "Regex and max (with key)",
"name": "mostCommonWord_v2",
"signature": "def mostCommonWord_v2(self, paragraph: str, b... | 3 | stack_v2_sparse_classes_30k_train_004001 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str: Regex and dictionary.
- def mostCommonWord_v2(self, paragraph: str, banned: List[str]) -> str: Regex and ma... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str: Regex and dictionary.
- def mostCommonWord_v2(self, paragraph: str, banned: List[str]) -> str: Regex and ma... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str:
"""Regex and dictionary."""
<|body_0|>
def mostCommonWord_v2(self, paragraph: str, banned: List[str]) -> str:
"""Regex and max (with key)"""
<|body_1|>
def mostCommonWord_v3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mostCommonWord_v1(self, paragraph: str, banned: List[str]) -> str:
"""Regex and dictionary."""
banned_set = set(banned)
words = [w.lower() for w in re.split('[^\\w]+', paragraph) if w]
words = [w for w in words if w not in banned_set]
count = defaultdict(i... | the_stack_v2_python_sparse | python3/string_array/most_common_word.py | victorchu/algorithms | train | 0 | |
f0855fb12019de0f281b3fe1a687ded6c3146875 | [
"if DinoEnvirophat.__instance is None:\n DinoEnvirophat.__instance = object.__new__(cls)\n DinoEnvirophat.__data = [None] * ENV_HAT_SIZE\n try:\n leds.off()\n except:\n DinoLog.logMsg('ERROR - Envirophat fail to turn off on-board led.')\nreturn DinoEnvirophat.__instance",
"temp = self.__... | <|body_start_0|>
if DinoEnvirophat.__instance is None:
DinoEnvirophat.__instance = object.__new__(cls)
DinoEnvirophat.__data = [None] * ENV_HAT_SIZE
try:
leds.off()
except:
DinoLog.logMsg('ERROR - Envirophat fail to turn off on-boar... | Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LSM303D) 5) Magnetometer (LSM303D) The API for the Envirophat had many additional f... | DinoEnvirophat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinoEnvirophat:
"""Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LSM303D) 5) Magnetometer (LSM303D) The AP... | stack_v2_sparse_classes_36k_train_007058 | 4,912 | no_license | [
{
"docstring": "Create a singleton instance of the DinoEnvirophat class.",
"name": "__new__",
"signature": "def __new__(cls)"
},
{
"docstring": "Read all sensors in the envirophat and return them in a touple. Returns ------- list List of raw telemetry readings from Envirophat organized using the... | 6 | stack_v2_sparse_classes_30k_train_007194 | Implement the Python class `DinoEnvirophat` described below.
Class description:
Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LS... | Implement the Python class `DinoEnvirophat` described below.
Class description:
Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LS... | 304c28cbd855713c09900669cdbf2ba15fcfb6b4 | <|skeleton|>
class DinoEnvirophat:
"""Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LSM303D) 5) Magnetometer (LSM303D) The AP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DinoEnvirophat:
"""Class DinoEnvirophat - Interface with EnviropHat. The envirophat communicates with the pi0 using I2C to read a the following sensors: 1) Light Sensor (TCS3472) 2) Temperature Sensor (BMP280) 3) Pressure Sensor (BMP280) 4) Accelerometer (LSM303D) 5) Magnetometer (LSM303D) The API for the Env... | the_stack_v2_python_sparse | pi0/DinoEnvirophat.py | dschor5/DINO | train | 1 |
d68ea325770bda5be2574f327aa0e7e226c2da28 | [
"self._xl_path = xl_path\nself._op = xlrd.open_workbook(self._xl_path)\nself.apiname_col = int()\nself.method_col = int()\nself.description_col = int()\nself.input_col = int()\nself.expected_output_col = int()\nself.params = list()\nself.values = list()",
"if os.path.splitext(self._xl_path)[-1][1:] != 'xls':\n ... | <|body_start_0|>
self._xl_path = xl_path
self._op = xlrd.open_workbook(self._xl_path)
self.apiname_col = int()
self.method_col = int()
self.description_col = int()
self.input_col = int()
self.expected_output_col = int()
self.params = list()
self.va... | ExcelClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelClass:
def __init__(self, xl_path):
"""excel表格完整路径 :param xl_path: :return:"""
<|body_0|>
def sheet_read(self, sheetname):
"""sheet名 :param sheetname: :return:"""
<|body_1|>
def xl_part(self, sheetname):
"""sheet名 :param sheetname: :return:"... | stack_v2_sparse_classes_36k_train_007059 | 4,273 | no_license | [
{
"docstring": "excel表格完整路径 :param xl_path: :return:",
"name": "__init__",
"signature": "def __init__(self, xl_path)"
},
{
"docstring": "sheet名 :param sheetname: :return:",
"name": "sheet_read",
"signature": "def sheet_read(self, sheetname)"
},
{
"docstring": "sheet名 :param sheet... | 5 | stack_v2_sparse_classes_30k_train_005315 | Implement the Python class `ExcelClass` described below.
Class description:
Implement the ExcelClass class.
Method signatures and docstrings:
- def __init__(self, xl_path): excel表格完整路径 :param xl_path: :return:
- def sheet_read(self, sheetname): sheet名 :param sheetname: :return:
- def xl_part(self, sheetname): sheet名 ... | Implement the Python class `ExcelClass` described below.
Class description:
Implement the ExcelClass class.
Method signatures and docstrings:
- def __init__(self, xl_path): excel表格完整路径 :param xl_path: :return:
- def sheet_read(self, sheetname): sheet名 :param sheetname: :return:
- def xl_part(self, sheetname): sheet名 ... | d63fefdcd434f9be21c6ff2a29c352fd181a32eb | <|skeleton|>
class ExcelClass:
def __init__(self, xl_path):
"""excel表格完整路径 :param xl_path: :return:"""
<|body_0|>
def sheet_read(self, sheetname):
"""sheet名 :param sheetname: :return:"""
<|body_1|>
def xl_part(self, sheetname):
"""sheet名 :param sheetname: :return:"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcelClass:
def __init__(self, xl_path):
"""excel表格完整路径 :param xl_path: :return:"""
self._xl_path = xl_path
self._op = xlrd.open_workbook(self._xl_path)
self.apiname_col = int()
self.method_col = int()
self.description_col = int()
self.input_col = int()
... | the_stack_v2_python_sparse | python/excel/excel.py | panhenggui/python | train | 0 | |
d0ee64a91e7e9fd5c126afeef26dd6352f7f34c7 | [
"if fname:\n if not fname.endswith('.npz'):\n fname = fname + '.npz'\n self._npz = load(fname)\nelse:\n self._npz = None\nself._fname = fname\nself._archived = {}\nself._new = {}",
"if self._npz is None:\n raise AttributeError(name)\nelse:\n try:\n value = self._npz[name]\n ... | <|body_start_0|>
if fname:
if not fname.endswith('.npz'):
fname = fname + '.npz'
self._npz = load(fname)
else:
self._npz = None
self._fname = fname
self._archived = {}
self._new = {}
<|end_body_0|>
<|body_start_1|>
... | A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the ArrayStore is explicitly saved. | ArrayStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayStore:
"""A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the ArrayStore is explicitly saved."""
def... | stack_v2_sparse_classes_36k_train_007060 | 14,154 | no_license | [
{
"docstring": "Prepare to load arrays from storage if a file name is provided; otherwise support saving of arrays assigned as attributes.",
"name": "__init__",
"signature": "def __init__(self, fname=None)"
},
{
"docstring": "Catch references to array attributes that have not yet been loaded fro... | 5 | stack_v2_sparse_classes_30k_train_000217 | Implement the Python class `ArrayStore` described below.
Class description:
A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the Arra... | Implement the Python class `ArrayStore` described below.
Class description:
A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the Arra... | 215de4e93b5cf79a1e9f380047b4db92bfeaf45c | <|skeleton|>
class ArrayStore:
"""A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the ArrayStore is explicitly saved."""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArrayStore:
"""A container class that provides lazy persistance of array instance attributes via NumPy's .npz archives. This is doubly lazy: arrays are not read into the namespace until actually requested, and they are not saved to the archive until the ArrayStore is explicitly saved."""
def __init__(sel... | the_stack_v2_python_sparse | package/inference/utils/ioutils.py | tloredo/inference | train | 3 |
857837e58561133e353303b45d72312fd1f9a497 | [
"if os.name == 'nt':\n pass\nelse:\n self.fd = sys.stdin.fileno()\n self.new_term = termios.tcgetattr(self.fd)\n self.old_term = termios.tcgetattr(self.fd)\n self.new_term[3] = self.new_term[3] & ~termios.ICANON & ~termios.ECHO\n termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)\n at... | <|body_start_0|>
if os.name == 'nt':
pass
else:
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgetattr(self.fd)
self.new_term[3] = self.new_term[3] & ~termios.ICANON & ~termios.ECHO
... | KBHit | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KBHit:
def __init__(self):
"""Creates a KBHit object that you can call to do various keyboard things."""
<|body_0|>
def set_normal_term(self):
"""Resets to normal terminal. On Windows this is a no-op."""
<|body_1|>
def getch(self):
"""Returns a k... | stack_v2_sparse_classes_36k_train_007061 | 4,095 | permissive | [
{
"docstring": "Creates a KBHit object that you can call to do various keyboard things.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Resets to normal terminal. On Windows this is a no-op.",
"name": "set_normal_term",
"signature": "def set_normal_term(self)"
... | 5 | stack_v2_sparse_classes_30k_train_017525 | Implement the Python class `KBHit` described below.
Class description:
Implement the KBHit class.
Method signatures and docstrings:
- def __init__(self): Creates a KBHit object that you can call to do various keyboard things.
- def set_normal_term(self): Resets to normal terminal. On Windows this is a no-op.
- def ge... | Implement the Python class `KBHit` described below.
Class description:
Implement the KBHit class.
Method signatures and docstrings:
- def __init__(self): Creates a KBHit object that you can call to do various keyboard things.
- def set_normal_term(self): Resets to normal terminal. On Windows this is a no-op.
- def ge... | 9253740baf46ebf4eacbce6bf3369150c5fb8ee0 | <|skeleton|>
class KBHit:
def __init__(self):
"""Creates a KBHit object that you can call to do various keyboard things."""
<|body_0|>
def set_normal_term(self):
"""Resets to normal terminal. On Windows this is a no-op."""
<|body_1|>
def getch(self):
"""Returns a k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KBHit:
def __init__(self):
"""Creates a KBHit object that you can call to do various keyboard things."""
if os.name == 'nt':
pass
else:
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgeta... | the_stack_v2_python_sparse | pyocd/utility/kbhit.py | pyocd/pyOCD | train | 507 | |
a2d5ba4a37c7f1b6b066eaa2b252e070df19ea64 | [
"super().__init__()\nself.q_proj = nn.Linear(q_dim, h_dim)\nself.s_proj = nn.Linear(s_dim, h_dim)\nself.linear = nn.Linear(h_dim, 1)\nself.out = nn.Linear(s_dim, out_dim)",
"q_proj = self.q_proj(q).unsqueeze(2)\ns_proj = self.s_proj(s).unsqueeze(1)\nout = torch.tanh(q_proj + s_proj)\nattn_score = self.linear(out)... | <|body_start_0|>
super().__init__()
self.q_proj = nn.Linear(q_dim, h_dim)
self.s_proj = nn.Linear(s_dim, h_dim)
self.linear = nn.Linear(h_dim, 1)
self.out = nn.Linear(s_dim, out_dim)
<|end_body_0|>
<|body_start_1|>
q_proj = self.q_proj(q).unsqueeze(2)
s_proj = se... | Bahdanau attention score = v*tanh(W1*q + W2*s) | AdditiveAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditiveAttention:
"""Bahdanau attention score = v*tanh(W1*q + W2*s)"""
def __init__(self, q_dim, s_dim, h_dim, out_dim):
"""params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim"""
<|body_0|>
def forward(self, q, s, mask):
"""q... | stack_v2_sparse_classes_36k_train_007062 | 4,057 | no_license | [
{
"docstring": "params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim",
"name": "__init__",
"signature": "def __init__(self, q_dim, s_dim, h_dim, out_dim)"
},
{
"docstring": "q: [B, q_len, q_dim] s: [B, s_len, s_dim] mask: [B, 1, s_len]",
"name": "forward",... | 2 | stack_v2_sparse_classes_30k_train_008020 | Implement the Python class `AdditiveAttention` described below.
Class description:
Bahdanau attention score = v*tanh(W1*q + W2*s)
Method signatures and docstrings:
- def __init__(self, q_dim, s_dim, h_dim, out_dim): params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim
- def forward... | Implement the Python class `AdditiveAttention` described below.
Class description:
Bahdanau attention score = v*tanh(W1*q + W2*s)
Method signatures and docstrings:
- def __init__(self, q_dim, s_dim, h_dim, out_dim): params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim
- def forward... | 54dcd23112d452b856e4f8000cf697d352cfec05 | <|skeleton|>
class AdditiveAttention:
"""Bahdanau attention score = v*tanh(W1*q + W2*s)"""
def __init__(self, q_dim, s_dim, h_dim, out_dim):
"""params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim"""
<|body_0|>
def forward(self, q, s, mask):
"""q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdditiveAttention:
"""Bahdanau attention score = v*tanh(W1*q + W2*s)"""
def __init__(self, q_dim, s_dim, h_dim, out_dim):
"""params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim"""
super().__init__()
self.q_proj = nn.Linear(q_dim, h_dim)
... | the_stack_v2_python_sparse | models/rnn/attention.py | khanrc/pt.seq2seq | train | 3 |
9cbde2cb25e3241c90614901380bc0e1df16957b | [
"super().__init__()\nimport sklearn\nimport sklearn.naive_bayes\nself.model = sklearn.naive_bayes.BernoulliNB",
"specs = super(BernoulliNB, cls).getInputSpecification()\nspecs.description = \"The \\\\textit{BernoulliNB} classifier implements the naive Bayes training and\\n classification a... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.naive_bayes
self.model = sklearn.naive_bayes.BernoulliNB
<|end_body_0|>
<|body_start_1|>
specs = super(BernoulliNB, cls).getInputSpecification()
specs.description = "The \\textit{BernoulliNB} classifier im... | BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier | BernoulliNB | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BernoulliNB:
"""BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Metho... | stack_v2_sparse_classes_36k_train_007063 | 5,978 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | null | Implement the Python class `BernoulliNB` described below.
Class description:
BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpec... | Implement the Python class `BernoulliNB` described below.
Class description:
BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpec... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class BernoulliNB:
"""BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BernoulliNB:
"""BernoulliNB Classifier Gaussian Naive Bayes (GaussianNB) classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.naive_bayes
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/NaiveBayes/BernoulliNBClassifier.py | idaholab/raven | train | 201 |
da9bb410435d894fa4d5dfe710a387976b1c1818 | [
"self.profile = profile\nsuper(ProfileForm, self).__init__(*args, **kwargs)\nself.fields['first_name'].initial = profile.user.first_name\nself.fields['last_name'].initial = profile.user.last_name\nself.fields['email'].initial = profile.user.email\nself.fields['email'].gender = profile.gender",
"users = User.objec... | <|body_start_0|>
self.profile = profile
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['first_name'].initial = profile.user.first_name
self.fields['last_name'].initial = profile.user.last_name
self.fields['email'].initial = profile.user.email
self.fields['... | The ProfileForm provides a form used to update the user's informations | ProfileForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileForm:
"""The ProfileForm provides a form used to update the user's informations"""
def __init__(self, profile, *args, **kwargs):
"""Initializes a new instance of the ChangePasswordForm class."""
<|body_0|>
def clean_email(self):
"""Validate that the suppli... | stack_v2_sparse_classes_36k_train_007064 | 5,957 | no_license | [
{
"docstring": "Initializes a new instance of the ChangePasswordForm class.",
"name": "__init__",
"signature": "def __init__(self, profile, *args, **kwargs)"
},
{
"docstring": "Validate that the supplied email address is unique for the site.",
"name": "clean_email",
"signature": "def cle... | 3 | stack_v2_sparse_classes_30k_train_008469 | Implement the Python class `ProfileForm` described below.
Class description:
The ProfileForm provides a form used to update the user's informations
Method signatures and docstrings:
- def __init__(self, profile, *args, **kwargs): Initializes a new instance of the ChangePasswordForm class.
- def clean_email(self): Val... | Implement the Python class `ProfileForm` described below.
Class description:
The ProfileForm provides a form used to update the user's informations
Method signatures and docstrings:
- def __init__(self, profile, *args, **kwargs): Initializes a new instance of the ChangePasswordForm class.
- def clean_email(self): Val... | b0702a8f7f60de6db9de7f712108e68d66f07f61 | <|skeleton|>
class ProfileForm:
"""The ProfileForm provides a form used to update the user's informations"""
def __init__(self, profile, *args, **kwargs):
"""Initializes a new instance of the ChangePasswordForm class."""
<|body_0|>
def clean_email(self):
"""Validate that the suppli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileForm:
"""The ProfileForm provides a form used to update the user's informations"""
def __init__(self, profile, *args, **kwargs):
"""Initializes a new instance of the ChangePasswordForm class."""
self.profile = profile
super(ProfileForm, self).__init__(*args, **kwargs)
... | the_stack_v2_python_sparse | getdeal/apps/profiles/forms.py | PankeshGupta/getdeal | train | 0 |
9e5948c2647fc5a730f4f62790b1270651cc9851 | [
"self._check_permission(Permissions.tags_add)\ndata = await self.get_json()\nrequest_model = RequestTag(**data)\ntag = await TagsQueries.create_or_update_tag(request_model)\nreturn ResponseTag.from_orm(tag)",
"self._check_permission(Permissions.tags_view)\ntags = await Tag.all()\nreturn ResponseTags(tags)"
] | <|body_start_0|>
self._check_permission(Permissions.tags_add)
data = await self.get_json()
request_model = RequestTag(**data)
tag = await TagsQueries.create_or_update_tag(request_model)
return ResponseTag.from_orm(tag)
<|end_body_0|>
<|body_start_1|>
self._check_permissi... | TagsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsView:
async def post(self):
"""--- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/ResponseTag' '400': descrip... | stack_v2_sparse_classes_36k_train_007065 | 2,520 | no_license | [
{
"docstring": "--- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/ResponseTag' '400': description: Bad request content: application/json... | 2 | stack_v2_sparse_classes_30k_train_004184 | Implement the Python class `TagsView` described below.
Class description:
Implement the TagsView class.
Method signatures and docstrings:
- async def post(self): --- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': descripti... | Implement the Python class `TagsView` described below.
Class description:
Implement the TagsView class.
Method signatures and docstrings:
- async def post(self): --- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': descripti... | d4abeb5b87ab00c4b371d501f3d117feb5e4d72c | <|skeleton|>
class TagsView:
async def post(self):
"""--- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/ResponseTag' '400': descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsView:
async def post(self):
"""--- description: Create tag tags: - tags requestBody: content: application/json: schema: $ref: '#/components/schemas/RequestTag' responses: '200': description: ok content: application/json: schema: $ref: '#/components/schemas/ResponseTag' '400': description: Bad requ... | the_stack_v2_python_sparse | app/services/web/views/tags.py | Ravillatypov/asterisk-integration-api | train | 2 | |
4c49150e44a65c975db5dce11eb31f21578b8dba | [
"length = len(nums)\nmemo = [-1] * length\n\ndef helper(i):\n if i < 0:\n return 0\n if memo[i] != -1:\n return memo[i]\n rob = nums[i] + helper(i - 2)\n dont_rob = helper(i - 1)\n best = max(rob, dont_rob)\n memo[i] = best\n return best\nreturn helper(length - 1)",
"length = le... | <|body_start_0|>
length = len(nums)
memo = [-1] * length
def helper(i):
if i < 0:
return 0
if memo[i] != -1:
return memo[i]
rob = nums[i] + helper(i - 2)
dont_rob = helper(i - 1)
best = max(rob, dont_rob... | Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
"... | stack_v2_sparse_classes_36k_train_007066 | 3,898 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",... | 3 | stack_v2_sparse_classes_30k_train_015174 | Implement the Python class `Solution` described below.
Class description:
Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber.... | Implement the Python class `Solution` described below.
Class description:
Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber.... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
""":type nums:... | the_stack_v2_python_sparse | 198-house_robber.py | stevestar888/leetcode-problems | train | 2 |
211e74285c92d6c731fea774cb7f83a564920a4a | [
"try:\n request_line = (yield from parse_line(read_line))\nexcept EOFError as exc:\n raise EOFError('connection closed while reading HTTP request line') from exc\ntry:\n method, raw_path, version = request_line.split(b' ', 2)\nexcept ValueError:\n raise ValueError(f'invalid HTTP request line: {d(request... | <|body_start_0|>
try:
request_line = (yield from parse_line(read_line))
except EOFError as exc:
raise EOFError('connection closed while reading HTTP request line') from exc
try:
method, raw_path, version = request_line.split(b' ', 2)
except ValueError:... | WebSocket handshake request. :param path: path and optional query :param headers: | Request | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't ... | stack_v2_sparse_classes_36k_train_007067 | 10,688 | permissive | [
{
"docstring": "Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't URL-decoded or validated in any way. ``path`` and ``headers`` are expected to contain only ASCII characters. Other characters are represented with surrogate escapes. :func:`parse_request` doesn't attempt to read the req... | 2 | stack_v2_sparse_classes_30k_train_006245 | Implement the Python class `Request` described below.
Class description:
WebSocket handshake request. :param path: path and optional query :param headers:
Method signatures and docstrings:
- def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']: Parse an HTTP/1.1 GE... | Implement the Python class `Request` described below.
Class description:
WebSocket handshake request. :param path: path and optional query :param headers:
Method signatures and docstrings:
- def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']: Parse an HTTP/1.1 GE... | 6b8d8cf9622eadef47bd10690c1bf1e7fd892bfd | <|skeleton|>
class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Request:
"""WebSocket handshake request. :param path: path and optional query :param headers:"""
def parse(cls, read_line: Callable[[], Generator[None, None, bytes]]) -> Generator[None, None, 'Request']:
"""Parse an HTTP/1.1 GET request and return ``(path, headers)``. ``path`` isn't URL-decoded o... | the_stack_v2_python_sparse | env/lib/python3.8/site-packages/websockets/http11.py | EtienneBrJ/Portfolio | train | 1 |
c2f5c2275fefe544786ff5cb8c5e467a62467ed8 | [
"meta = super(ApprovedEventSerializer, self).get_meta(obj)\nmeta['remaining_votes'] = self.get_remaining_votes(obj)\nreturn meta",
"request = self.context['request']\nif not obj.is_approved:\n return 0\nif not is_ended_event(obj):\n return 0\nif not IsMemberOfCommunity().has_object_permission(request, None,... | <|body_start_0|>
meta = super(ApprovedEventSerializer, self).get_meta(obj)
meta['remaining_votes'] = self.get_remaining_votes(obj)
return meta
<|end_body_0|>
<|body_start_1|>
request = self.context['request']
if not obj.is_approved:
return 0
if not is_ended_e... | Approved event serializer | ApprovedEventSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApprovedEventSerializer:
"""Approved event serializer"""
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_0|>
def get_remaining_votes(self, obj):
"""Retrieve remaining votes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
meta = super(Ap... | stack_v2_sparse_classes_36k_train_007068 | 25,313 | permissive | [
{
"docstring": "Retrieve meta data",
"name": "get_meta",
"signature": "def get_meta(self, obj)"
},
{
"docstring": "Retrieve remaining votes",
"name": "get_remaining_votes",
"signature": "def get_remaining_votes(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006423 | Implement the Python class `ApprovedEventSerializer` described below.
Class description:
Approved event serializer
Method signatures and docstrings:
- def get_meta(self, obj): Retrieve meta data
- def get_remaining_votes(self, obj): Retrieve remaining votes | Implement the Python class `ApprovedEventSerializer` described below.
Class description:
Approved event serializer
Method signatures and docstrings:
- def get_meta(self, obj): Retrieve meta data
- def get_remaining_votes(self, obj): Retrieve remaining votes
<|skeleton|>
class ApprovedEventSerializer:
"""Approved... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class ApprovedEventSerializer:
"""Approved event serializer"""
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_0|>
def get_remaining_votes(self, obj):
"""Retrieve remaining votes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApprovedEventSerializer:
"""Approved event serializer"""
def get_meta(self, obj):
"""Retrieve meta data"""
meta = super(ApprovedEventSerializer, self).get_meta(obj)
meta['remaining_votes'] = self.get_remaining_votes(obj)
return meta
def get_remaining_votes(self, obj):... | the_stack_v2_python_sparse | community/serializers.py | 810Teams/clubs-and-events-backend | train | 3 |
36f5b55d5301cd52996fec02c28f3a27c9c7e97b | [
"instance = self.get_object()\nvalid_refresh = ['all', 'info', 'schema']\nrefresh = bleach.clean(kwargs.get('refresh', 'info'))\nif instance is not None:\n if refresh not in valid_refresh:\n refresh = 'info'\nreturn Response({'refresh': refresh})",
"actuator = self.get_object()\nif not request.user.is_s... | <|body_start_0|>
instance = self.get_object()
valid_refresh = ['all', 'info', 'schema']
refresh = bleach.clean(kwargs.get('refresh', 'info'))
if instance is not None:
if refresh not in valid_refresh:
refresh = 'info'
return Response({'refresh': refresh... | API endpoint that allows Actuators to be viewed or edited. | ActuatorViewSet | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActuatorViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def refresh(self, request, *args, **kwargs):
"""API endpoint that allows Actuator data to be refreshed"""
<|body_0|>
def profile(self, request, *args, **kwargs):
"""API endpoint tha... | stack_v2_sparse_classes_36k_train_007069 | 3,007 | permissive | [
{
"docstring": "API endpoint that allows Actuator data to be refreshed",
"name": "refresh",
"signature": "def refresh(self, request, *args, **kwargs)"
},
{
"docstring": "API endpoint that allows for Actuator profile retrieval",
"name": "profile",
"signature": "def profile(self, request, ... | 3 | stack_v2_sparse_classes_30k_train_005371 | Implement the Python class `ActuatorViewSet` described below.
Class description:
API endpoint that allows Actuators to be viewed or edited.
Method signatures and docstrings:
- def refresh(self, request, *args, **kwargs): API endpoint that allows Actuator data to be refreshed
- def profile(self, request, *args, **kwar... | Implement the Python class `ActuatorViewSet` described below.
Class description:
API endpoint that allows Actuators to be viewed or edited.
Method signatures and docstrings:
- def refresh(self, request, *args, **kwargs): API endpoint that allows Actuator data to be refreshed
- def profile(self, request, *args, **kwar... | 9227d38cb53204b45641ac55aefd6a13d2aad563 | <|skeleton|>
class ActuatorViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def refresh(self, request, *args, **kwargs):
"""API endpoint that allows Actuator data to be refreshed"""
<|body_0|>
def profile(self, request, *args, **kwargs):
"""API endpoint tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActuatorViewSet:
"""API endpoint that allows Actuators to be viewed or edited."""
def refresh(self, request, *args, **kwargs):
"""API endpoint that allows Actuator data to be refreshed"""
instance = self.get_object()
valid_refresh = ['all', 'info', 'schema']
refresh = blea... | the_stack_v2_python_sparse | orchestrator/core/orc_server/actuator/views/viewsets.py | sumodgeorge/openc2-oif-orchestrator | train | 0 |
adf72916a0f8dd10be0381de0aeb7948abcaf351 | [
"super(CustomUpdater, self).__init__(iterator, optimizer)\nself.model = model\nself.grad_clip = grad_clip\nself.device = device\nself.clip_grad_norm = torch.nn.utils.clip_grad_norm_\nself.accum_grad = accum_grad\nself.forward_count = 0",
"train_iter = self.get_iterator('main')\noptimizer = self.get_optimizer('mai... | <|body_start_0|>
super(CustomUpdater, self).__init__(iterator, optimizer)
self.model = model
self.grad_clip = grad_clip
self.device = device
self.clip_grad_norm = torch.nn.utils.clip_grad_norm_
self.accum_grad = accum_grad
self.forward_count = 0
<|end_body_0|>
<|... | Custom updater. | CustomUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset... | stack_v2_sparse_classes_36k_train_007070 | 26,532 | permissive | [
{
"docstring": "Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset.Iterator): Iterator for training. optimizer (torch.optim.Optimizer) : Pytorch optimizer instance. device (torch.device): The device ... | 3 | null | Implement the Python class `CustomUpdater` described below.
Class description:
Custom updater.
Method signatures and docstrings:
- def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1): Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip... | Implement the Python class `CustomUpdater` described below.
Class description:
Custom updater.
Method signatures and docstrings:
- def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1): Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset.Iterator): I... | the_stack_v2_python_sparse | espnet/tts/pytorch_backend/tts.py | espnet/espnet | train | 7,242 |
e4785eced9c44310e1febad27b88dbd7c0a8f24d | [
"super().__init__(product_code, description, market_price, rental_price)\nself.material = material\nself.size = size\nself.output_dict = {}",
"self.output_dict['product_code'] = self.product_code\nself.output_dict['description'] = self.description\nself.output_dict['market_price'] = self.market_price\nself.output... | <|body_start_0|>
super().__init__(product_code, description, market_price, rental_price)
self.material = material
self.size = size
self.output_dict = {}
<|end_body_0|>
<|body_start_1|>
self.output_dict['product_code'] = self.product_code
self.output_dict['description'] =... | creating a child class of Inventory | Furniture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Furniture:
"""creating a child class of Inventory"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
""""can I get ... | stack_v2_sparse_classes_36k_train_007071 | 1,492 | no_license | [
{
"docstring": "Creates common instance variables from the parent class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, material, size)"
},
{
"docstring": "\"can I get rid of the replicated ones from the original class?",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_020912 | Implement the Python class `Furniture` described below.
Class description:
creating a child class of Inventory
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, material, size): Creates common instance variables from the parent class
- def return_as_dictiona... | Implement the Python class `Furniture` described below.
Class description:
creating a child class of Inventory
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, material, size): Creates common instance variables from the parent class
- def return_as_dictiona... | 46d6282518f02029a556e94e607612a47daf675a | <|skeleton|>
class Furniture:
"""creating a child class of Inventory"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""Creates common instance variables from the parent class"""
<|body_0|>
def return_as_dictionary(self):
""""can I get ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Furniture:
"""creating a child class of Inventory"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""Creates common instance variables from the parent class"""
super().__init__(product_code, description, market_price, rental_price)
sel... | the_stack_v2_python_sparse | students/Justin_Jameson/lesson01/assignment/inventory_management/furniture_class.py | Washirican/Python220A_2019 | train | 2 |
a8b1b2407a8ea9007f799f561db86765965876de | [
"self.driver.get(url)\nself.driver.max_window()\nself.driver.find_element(locator.HeaderLocator.taoche_new).click()\nself.driver.pause(3)\nself.driver.switch_to_window()\nnew_is_dispayed = self.driver.is_display(locator.HeaderLocator.new_img)\nself.driver.pause(3)\ntt_check.assertTrue(new_is_dispayed, '新车页品牌是否显示:%s... | <|body_start_0|>
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.taoche_new).click()
self.driver.pause(3)
self.driver.switch_to_window()
new_is_dispayed = self.driver.is_display(locator.HeaderLocator.new_img)
self.drive... | newcar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class newcar:
def test_TCnew(self):
"""测试首页新车楼层-淘车新车跳转,@author:xulanzhong"""
<|body_0|>
def test_calculater(self):
"""测试首页新车楼层-购车计算器跳转,@author:xulanzhong"""
<|body_1|>
def test_fenqi(self):
"""测试首页新车楼层-分期购车-跳转,@author:xulanzhong"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_007072 | 3,931 | no_license | [
{
"docstring": "测试首页新车楼层-淘车新车跳转,@author:xulanzhong",
"name": "test_TCnew",
"signature": "def test_TCnew(self)"
},
{
"docstring": "测试首页新车楼层-购车计算器跳转,@author:xulanzhong",
"name": "test_calculater",
"signature": "def test_calculater(self)"
},
{
"docstring": "测试首页新车楼层-分期购车-跳转,@author:... | 5 | stack_v2_sparse_classes_30k_train_005272 | Implement the Python class `newcar` described below.
Class description:
Implement the newcar class.
Method signatures and docstrings:
- def test_TCnew(self): 测试首页新车楼层-淘车新车跳转,@author:xulanzhong
- def test_calculater(self): 测试首页新车楼层-购车计算器跳转,@author:xulanzhong
- def test_fenqi(self): 测试首页新车楼层-分期购车-跳转,@author:xulanzhong
... | Implement the Python class `newcar` described below.
Class description:
Implement the newcar class.
Method signatures and docstrings:
- def test_TCnew(self): 测试首页新车楼层-淘车新车跳转,@author:xulanzhong
- def test_calculater(self): 测试首页新车楼层-购车计算器跳转,@author:xulanzhong
- def test_fenqi(self): 测试首页新车楼层-分期购车-跳转,@author:xulanzhong
... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class newcar:
def test_TCnew(self):
"""测试首页新车楼层-淘车新车跳转,@author:xulanzhong"""
<|body_0|>
def test_calculater(self):
"""测试首页新车楼层-购车计算器跳转,@author:xulanzhong"""
<|body_1|>
def test_fenqi(self):
"""测试首页新车楼层-分期购车-跳转,@author:xulanzhong"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class newcar:
def test_TCnew(self):
"""测试首页新车楼层-淘车新车跳转,@author:xulanzhong"""
self.driver.get(url)
self.driver.max_window()
self.driver.find_element(locator.HeaderLocator.taoche_new).click()
self.driver.pause(3)
self.driver.switch_to_window()
new_is_dispayed = ... | the_stack_v2_python_sparse | mc/taochePC/test_crawler/test_homepage/test_newcar.py | boeai/mc | train | 0 | |
f2bd910ae4dc16a74c1f11c8aa676739361e4b1d | [
"if root:\n return str(root.val) + ' ' + self.serialize(root.left) + ' ' + self.serialize(root.right)\nelse:\n return '#'",
"q = data.split()\n\ndef dfs(q):\n if not q:\n return None\n val = q.pop(0)\n if val == '#':\n return None\n else:\n node = TreeNode(val)\n node... | <|body_start_0|>
if root:
return str(root.val) + ' ' + self.serialize(root.left) + ' ' + self.serialize(root.right)
else:
return '#'
<|end_body_0|>
<|body_start_1|>
q = data.split()
def dfs(q):
if not q:
return None
val = ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_007073 | 2,028 | 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_004284 | 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:... | 9d9e0c08992ef7dbd9ac517821faa9de17f49b0e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root:
return str(root.val) + ' ' + self.serialize(root.left) + ' ' + self.serialize(root.right)
else:
return '#'
def deserialize(self, data):
... | the_stack_v2_python_sparse | 297-serialize-and-deserialize-binary-tree.py | floydchenchen/leetcode | train | 0 | |
a4716ce88926a4f8d352512cf644c42dcba2dcaa | [
"self.requests = RedisList('ipreq')\nself.redis = redis\nself.cache = user_cache",
"if not self.too_many_requests() and user_ip and (not ipaddress.ip_address(str(user_ip)).is_private):\n ip_string = str(user_ip)\n if self.cache.is_cached(ip_string):\n ip_data = self.cache.get(ip_string)\n lon ... | <|body_start_0|>
self.requests = RedisList('ipreq')
self.redis = redis
self.cache = user_cache
<|end_body_0|>
<|body_start_1|>
if not self.too_many_requests() and user_ip and (not ipaddress.ip_address(str(user_ip)).is_private):
ip_string = str(user_ip)
if self.ca... | GeolocationClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeolocationClient:
def __init__(self, redis, user_cache):
"""Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager"""
<|body_0|>
def locate_using_ip(self, user_ip):
"""Approximate latitude and longitude of user ... | stack_v2_sparse_classes_36k_train_007074 | 5,174 | no_license | [
{
"docstring": "Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager",
"name": "__init__",
"signature": "def __init__(self, redis, user_cache)"
},
{
"docstring": "Approximate latitude and longitude of user by using IP address and making ca... | 3 | stack_v2_sparse_classes_30k_train_004423 | Implement the Python class `GeolocationClient` described below.
Class description:
Implement the GeolocationClient class.
Method signatures and docstrings:
- def __init__(self, redis, user_cache): Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager
- def locat... | Implement the Python class `GeolocationClient` described below.
Class description:
Implement the GeolocationClient class.
Method signatures and docstrings:
- def __init__(self, redis, user_cache): Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager
- def locat... | 224241a4d3ecb3f64a6dac86feb2a4b85a12d615 | <|skeleton|>
class GeolocationClient:
def __init__(self, redis, user_cache):
"""Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager"""
<|body_0|>
def locate_using_ip(self, user_ip):
"""Approximate latitude and longitude of user ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeolocationClient:
def __init__(self, redis, user_cache):
"""Makes request to geolocation api to approximate user location based on ip address. :param redis: RedisManager"""
self.requests = RedisList('ipreq')
self.redis = redis
self.cache = user_cache
def locate_using_ip(s... | the_stack_v2_python_sparse | GradeTip/schools/location.py | joshlopez97/grade-tip | train | 0 | |
89cfb9d562b368b89c997323433f0e99088b2139 | [
"if context is None:\n context = {}\ndefault_fields = set()\nmapped_fields = {v: k for k, v in view.field_map.items() if isinstance(v, str)}\nmodel_fields = {f.name for f in queryset.model._meta.get_fields()}\nfor field in view.values:\n fk_ref = field.split('__')[0]\n if field in model_fields or field in ... | <|body_start_0|>
if context is None:
context = {}
default_fields = set()
mapped_fields = {v: k for k, v in view.field_map.items() if isinstance(v, str)}
model_fields = {f.name for f in queryset.model._meta.get_fields()}
for field in view.values:
fk_ref = f... | ValuesViewsetOrderingFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValuesViewsetOrderingFilter:
def get_default_valid_fields(self, queryset, view, context=None):
"""The original implementation of this makes the assumption that the DRF serializer for the class encodes all the serialization behaviour for the viewset: https://github.com/encode/django-rest-... | stack_v2_sparse_classes_36k_train_007075 | 14,991 | permissive | [
{
"docstring": "The original implementation of this makes the assumption that the DRF serializer for the class encodes all the serialization behaviour for the viewset: https://github.com/encode/django-rest-framework/blob/version-3.12.2/rest_framework/filters.py#L208 With the ValuesViewset, this is no longer the... | 2 | null | Implement the Python class `ValuesViewsetOrderingFilter` described below.
Class description:
Implement the ValuesViewsetOrderingFilter class.
Method signatures and docstrings:
- def get_default_valid_fields(self, queryset, view, context=None): The original implementation of this makes the assumption that the DRF seri... | Implement the Python class `ValuesViewsetOrderingFilter` described below.
Class description:
Implement the ValuesViewsetOrderingFilter class.
Method signatures and docstrings:
- def get_default_valid_fields(self, queryset, view, context=None): The original implementation of this makes the assumption that the DRF seri... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class ValuesViewsetOrderingFilter:
def get_default_valid_fields(self, queryset, view, context=None):
"""The original implementation of this makes the assumption that the DRF serializer for the class encodes all the serialization behaviour for the viewset: https://github.com/encode/django-rest-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValuesViewsetOrderingFilter:
def get_default_valid_fields(self, queryset, view, context=None):
"""The original implementation of this makes the assumption that the DRF serializer for the class encodes all the serialization behaviour for the viewset: https://github.com/encode/django-rest-framework/blob... | the_stack_v2_python_sparse | kolibri/core/api.py | learningequality/kolibri | train | 689 | |
0ac6044b2c4c86291768f2c820e5037f47242f2f | [
"if inputFile.sample != None:\n outDir = inputFile.sample.outputDir\nelse:\n outDir = inputFile.pool.outputDir\nif inputFile.fileName.endswith('.tar.gz'):\n return self._extractTarGz(inputFile, outDir)\nelif inputFile.fileName.endswith('.gz'):\n return self._extractGz(inputFile, outDir)\nelse:\n rais... | <|body_start_0|>
if inputFile.sample != None:
outDir = inputFile.sample.outputDir
else:
outDir = inputFile.pool.outputDir
if inputFile.fileName.endswith('.tar.gz'):
return self._extractTarGz(inputFile, outDir)
elif inputFile.fileName.endswith('.gz'):
... | The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi | Decompressor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decompressor:
"""The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi"""
def extract(self, inputFile):
"""This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is ... | stack_v2_sparse_classes_36k_train_007076 | 2,548 | no_license | [
{
"docstring": "This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is called :param inputFile: The compressed .gz or . tar.gz file which has to be extracted :type inputFile: instance of a child object of the :py:class:`File.File` object :returns... | 3 | stack_v2_sparse_classes_30k_train_005300 | Implement the Python class `Decompressor` described below.
Class description:
The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi
Method signatures and docstrings:
- def extract(self, inputFile): This function calls extractGz if the file .gz compressed, if thi... | Implement the Python class `Decompressor` described below.
Class description:
The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi
Method signatures and docstrings:
- def extract(self, inputFile): This function calls extractGz if the file .gz compressed, if thi... | 53315eca821785aa02218e903b60921ecf18246b | <|skeleton|>
class Decompressor:
"""The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi"""
def extract(self, inputFile):
"""This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decompressor:
"""The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi"""
def extract(self, inputFile):
"""This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is called :param... | the_stack_v2_python_sparse | pythonCodebase/src/programs/Decompressor.py | JJacobi13/VLPB | train | 0 |
53197e62429d31dcbdf0ba5c9631006d4b4a4351 | [
"self.dlist = DList()\nself.memo = {}\nself.c = capacity",
"if key not in self.memo:\n return -1\nelse:\n node = self.memo[key]\n _, v = node.val\n self.dlist.move_front(node)\n return v",
"if key in self.memo:\n node = self.memo[key]\n node.val = (key, value)\n self.dlist.move_front(nod... | <|body_start_0|>
self.dlist = DList()
self.memo = {}
self.c = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.memo:
return -1
else:
node = self.memo[key]
_, v = node.val
self.dlist.move_front(node)
return v
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_007077 | 3,851 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.dlist = DList()
self.memo = {}
self.c = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.memo:
return -1
else:
node = self... | the_stack_v2_python_sparse | python/leetcode/design/146_LRU_cache.py | Levintsky/topcoder | train | 0 | |
65a76d43a704f9997a10fd449e81db4a18dc6ff4 | [
"client = get_object_or_404(Client, id=client_id)\nform = OrderForm()\nreturn render(request, 'order/add-order.html', {'form': form, 'func': 'Add', 'client': client})",
"form = OrderForm(request.POST)\nclient = get_object_or_404(Client, id=client_id)\nif form.is_valid():\n new_order = form.save(commit=False)\n... | <|body_start_0|>
client = get_object_or_404(Client, id=client_id)
form = OrderForm()
return render(request, 'order/add-order.html', {'form': form, 'func': 'Add', 'client': client})
<|end_body_0|>
<|body_start_1|>
form = OrderForm(request.POST)
client = get_object_or_404(Client, ... | Class based view for adding new order. | OrderAddView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderAddView:
"""Class based view for adding new order."""
def get(self, request, client_id):
"""Return add new order form."""
<|body_0|>
def post(self, request, client_id):
"""Save order and redirect to order list."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_007078 | 3,127 | no_license | [
{
"docstring": "Return add new order form.",
"name": "get",
"signature": "def get(self, request, client_id)"
},
{
"docstring": "Save order and redirect to order list.",
"name": "post",
"signature": "def post(self, request, client_id)"
}
] | 2 | null | Implement the Python class `OrderAddView` described below.
Class description:
Class based view for adding new order.
Method signatures and docstrings:
- def get(self, request, client_id): Return add new order form.
- def post(self, request, client_id): Save order and redirect to order list. | Implement the Python class `OrderAddView` described below.
Class description:
Class based view for adding new order.
Method signatures and docstrings:
- def get(self, request, client_id): Return add new order form.
- def post(self, request, client_id): Save order and redirect to order list.
<|skeleton|>
class OrderA... | 93c3106ab90fb9aed85658f93f51686ba4734091 | <|skeleton|>
class OrderAddView:
"""Class based view for adding new order."""
def get(self, request, client_id):
"""Return add new order form."""
<|body_0|>
def post(self, request, client_id):
"""Save order and redirect to order list."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderAddView:
"""Class based view for adding new order."""
def get(self, request, client_id):
"""Return add new order form."""
client = get_object_or_404(Client, id=client_id)
form = OrderForm()
return render(request, 'order/add-order.html', {'form': form, 'func': 'Add', '... | the_stack_v2_python_sparse | order/views/order_views.py | saadali5997/tms | train | 0 |
b089d601996f79b6e22704815a0ae8a17e15d640 | [
"super().__init__(name='reward_predictor')\nself.model_size = model_size\nself.mlp = MLP(model_size=model_size, output_layer_size=None)\nself.reward_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound)\ndl_type = tf.keras.mixed_precision.global_policy().compute_dty... | <|body_start_0|>
super().__init__(name='reward_predictor')
self.model_size = model_size
self.mlp = MLP(model_size=model_size, output_layer_size=None)
self.reward_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound)
dl_type = tf.k... | Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in. | RewardPredictor | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound:... | stack_v2_sparse_classes_36k_train_007079 | 4,202 | permissive | [
{
"docstring": "Initializes a RewardPredictor instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Determines the exact size of the underlying MLP. num_buckets: The number of buckets to create. Note that the number of possible symlog'd outcomes from the used distribution is `num_buc... | 2 | null | Implement the Python class `RewardPredictor` described below.
Class description:
Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in.
Method signatures and docstrings:
- def __init__(self, *, model_size: Optional[str... | Implement the Python class `RewardPredictor` described below.
Class description:
Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in.
Method signatures and docstrings:
- def __init__(self, *, model_size: Optional[str... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RewardPredictor:
"""Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. Predicted rewards are used to produce "dream data" to learn the policy in."""
def __init__(self, *, model_size: Optional[str]='XS', num_buckets: int=255, lower_bound: float=-20.0, upper_bound: float=20.0):... | the_stack_v2_python_sparse | rllib/algorithms/dreamerv3/tf/models/components/reward_predictor.py | ray-project/ray | train | 29,482 |
ea2fc162be38bd281a622618449e4b947f5f9e13 | [
"super(BumpsController, self).__init__(cost_func)\nself._param_names = self.problem.param_names\nself._func_wrapper = None\nself._fit_problem = None\nself._bumps_result = None\nself.algorithm_check = {'all': ['amoeba', 'lm-bumps', 'newton', 'de', 'mp'], 'ls': ['lm-bumps', 'mp'], 'deriv_free': ['amoeba', 'de'], 'gen... | <|body_start_0|>
super(BumpsController, self).__init__(cost_func)
self._param_names = self.problem.param_names
self._func_wrapper = None
self._fit_problem = None
self._bumps_result = None
self.algorithm_check = {'all': ['amoeba', 'lm-bumps', 'newton', 'de', 'mp'], 'ls': [... | Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function. | BumpsController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BumpsController:
"""Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function."""
def __init__(self, cost_func):
"""Extract param names for function setup :param cost_func: Cost function object selected from options. :... | stack_v2_sparse_classes_36k_train_007080 | 3,798 | permissive | [
{
"docstring": "Extract param names for function setup :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_cost_func.CostFunc`",
"name": "__init__",
"signature": "def __init__(self, cost_func)"
},
{
"docstring": "Bump... | 5 | stack_v2_sparse_classes_30k_train_004479 | Implement the Python class `BumpsController` described below.
Class description:
Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function.
Method signatures and docstrings:
- def __init__(self, cost_func): Extract param names for function setup :param... | Implement the Python class `BumpsController` described below.
Class description:
Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function.
Method signatures and docstrings:
- def __init__(self, cost_func): Extract param names for function setup :param... | edae46c0361568bc537de2425d603e7b271eabe7 | <|skeleton|>
class BumpsController:
"""Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function."""
def __init__(self, cost_func):
"""Extract param names for function setup :param cost_func: Cost function object selected from options. :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BumpsController:
"""Controller for the Bumps fitting software. Sasview requires a model to fit. Setup creates a model with the correct function."""
def __init__(self, cost_func):
"""Extract param names for function setup :param cost_func: Cost function object selected from options. :type cost_fun... | the_stack_v2_python_sparse | fitbenchmarking/controllers/bumps_controller.py | dsotiropoulos/fitbenchmarking | train | 0 |
6896717402fddf38a9dbd01d27d34f00bf909ec2 | [
"from sagas.nlu.inspectors import query_duckling\nresp = query_duckling(text, lang)\nprint(pretty_json(resp))\nif resp['result'] == 'success':\n print('-' * 25)\n print([d['dim'] for d in resp['data']])",
"from dateparser.search import search_dates\nfrom dateparser import parse\nsearch_r = search_dates(text... | <|body_start_0|>
from sagas.nlu.inspectors import query_duckling
resp = query_duckling(text, lang)
print(pretty_json(resp))
if resp['result'] == 'success':
print('-' * 25)
print([d['dim'] for d in resp['data']])
<|end_body_0|>
<|body_start_1|>
from datepa... | ExtractorCli | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是... | stack_v2_sparse_classes_36k_train_007081 | 4,289 | permissive | [
{
"docstring": "$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling \"3 mins\" en $ python -m sagas.nlu.extractor_cli duckling \"last week\" en $ python -m sagas.nlu.extractor_cli duckling \"明天是九月九日\" zh $ python -m sagas.nlu.extractor_cli duckling 'あ... | 4 | null | Implement the Python class `ExtractorCli` described below.
Class description:
Implement the ExtractorCli class.
Method signatures and docstrings:
- def duckling(self, text, lang='en'): $ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python... | Implement the Python class `ExtractorCli` described below.
Class description:
Implement the ExtractorCli class.
Method signatures and docstrings:
- def duckling(self, text, lang='en'): $ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python... | 9958d18ee5e75cf9794f546c904097dc1ff4f3a0 | <|skeleton|>
class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是九月九日" zh $ pyt... | the_stack_v2_python_sparse | sagas/nlu/extractor_cli.py | samlet/stack | train | 3 | |
4634506925d36b6e900e9db6887cda8232712270 | [
"self._api_url = url\nself._session = requests.Session()\nself._session.headers['x-api-key'] = api_key\nself._session.verify = verify\nif not url:\n raise ValueError('IronNet URL must be set')\nif not api_key:\n raise ValueError('IronNet API key must be set')",
"resp: Response = self._session.get(self._api_... | <|body_start_0|>
self._api_url = url
self._session = requests.Session()
self._session.headers['x-api-key'] = api_key
self._session.verify = verify
if not url:
raise ValueError('IronNet URL must be set')
if not api_key:
raise ValueError('IronNet API... | IronNet client | IronNetClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
<|body_0|>
def query(self) -> Iterator[IronNetItem]:
... | stack_v2_sparse_classes_36k_train_007082 | 1,867 | permissive | [
{
"docstring": "Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections",
"name": "__init__",
"signature": "def __init__(self, url: str, api_key: str, verify: bool=True)"
},
{
"docstring": "Process the feed URL and return any indicators. :return... | 2 | stack_v2_sparse_classes_30k_val_000461 | Implement the Python class `IronNetClient` described below.
Class description:
IronNet client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str, verify: bool=True): Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections
- def query(self) ... | Implement the Python class `IronNetClient` described below.
Class description:
IronNet client
Method signatures and docstrings:
- def __init__(self, url: str, api_key: str, verify: bool=True): Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections
- def query(self) ... | d00a0243946ded25b5d06bdefd9b40015dea9b80 | <|skeleton|>
class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
<|body_0|>
def query(self) -> Iterator[IronNetItem]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IronNetClient:
"""IronNet client"""
def __init__(self, url: str, api_key: str, verify: bool=True):
"""Constructor. :param url: IronNet url :param api_key: IronNet API key :param verify: Verify SSL connections"""
self._api_url = url
self._session = requests.Session()
self._... | the_stack_v2_python_sparse | external-import/ironnet/src/ironnet/client.py | OpenCTI-Platform/connectors | train | 254 |
022ba7cc7cba22a35155c45c190a9dbc474f2db1 | [
"self.physics_controller = physics_controller\nbumper_width = 3.25 * units.inch\nself.drivetrain = tankmodel.TankModel.theory(motor_cfgs.MOTOR_CFG_CIM, 110 * units.lbs, 10.71, 2, 22 * units.inch, 23 * units.inch + bumper_width * 2, 32 * units.inch + bumper_width * 2, 6 * units.inch)",
"l_motor = hal_data['CAN'][1... | <|body_start_0|>
self.physics_controller = physics_controller
bumper_width = 3.25 * units.inch
self.drivetrain = tankmodel.TankModel.theory(motor_cfgs.MOTOR_CFG_CIM, 110 * units.lbs, 10.71, 2, 22 * units.inch, 23 * units.inch + bumper_width * 2, 32 * units.inch + bumper_width * 2, 6 * units.inch... | PhysicsEngine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhysicsEngine:
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to"""
<|body_0|>
def update_sim(self, hal_data, now, tm_diff):
"""Called when the simulation parameters... | stack_v2_sparse_classes_36k_train_007083 | 2,435 | no_license | [
{
"docstring": ":param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to",
"name": "__init__",
"signature": "def __init__(self, physics_controller)"
},
{
"docstring": "Called when the simulation parameters for the program need to be updated. :p... | 2 | null | Implement the Python class `PhysicsEngine` described below.
Class description:
Implement the PhysicsEngine class.
Method signatures and docstrings:
- def __init__(self, physics_controller): :param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to
- def update_sim(se... | Implement the Python class `PhysicsEngine` described below.
Class description:
Implement the PhysicsEngine class.
Method signatures and docstrings:
- def __init__(self, physics_controller): :param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to
- def update_sim(se... | ea9a960acddfbd045301feed846d49d669d13599 | <|skeleton|>
class PhysicsEngine:
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to"""
<|body_0|>
def update_sim(self, hal_data, now, tm_diff):
"""Called when the simulation parameters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhysicsEngine:
def __init__(self, physics_controller):
""":param physics_controller: `pyfrc.physics.core.PhysicsInterface` object to communicate simulation effects to"""
self.physics_controller = physics_controller
bumper_width = 3.25 * units.inch
self.drivetrain = tankmodel.Ta... | the_stack_v2_python_sparse | 2018FRCPython/physics.py | McDowellRobotics63/FRC.63.2020 | train | 2 | |
a24fd9e3332d60a70c72263725aa8fc42f9bb77c | [
"queue = deque()\nif root:\n queue.append(root)\ns = []\nwhile len(queue) > 0:\n node = queue.popleft()\n if node is None:\n s.append('null')\n else:\n s.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\nreturn ','.join(s)",
"ss = data.split(',')\n... | <|body_start_0|>
queue = deque()
if root:
queue.append(root)
s = []
while len(queue) > 0:
node = queue.popleft()
if node is None:
s.append('null')
else:
s.append(str(node.val))
queue.append(no... | Codec_BFS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec_BFS:
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|>
<|b... | stack_v2_sparse_classes_36k_train_007084 | 5,078 | 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_020229 | Implement the Python class `Codec_BFS` described below.
Class description:
Implement the Codec_BFS 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... | Implement the Python class `Codec_BFS` described below.
Class description:
Implement the Codec_BFS 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... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Codec_BFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec_BFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = deque()
if root:
queue.append(root)
s = []
while len(queue) > 0:
node = queue.popleft()
if node is None:
... | the_stack_v2_python_sparse | code297SerializeAndDeserializeBinaryTree.py | cybelewang/leetcode-python | train | 0 | |
9c7aeaa34b6357478e34a30801698e9006531ed5 | [
"outputs = self._outputs().get()\ninputs = self.inputs.get()\nfor output in outputs:\n outputs[output] = os.path.abspath(os.path.basename(inputs[output]))\nreturn outputs",
"inputs = self.inputs.get()\nfor matter in ('gm', 'wm'):\n proba_name = '{0}_proba'.format(matter)\n proba_file = inputs[proba_name]... | <|body_start_0|>
outputs = self._outputs().get()
inputs = self.inputs.get()
for output in outputs:
outputs[output] = os.path.abspath(os.path.basename(inputs[output]))
return outputs
<|end_body_0|>
<|body_start_1|>
inputs = self.inputs.get()
for matter in ('gm... | Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps. | LOGISMOSBPreprocessing | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LOGISMOSBPreprocessing:
"""Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps."""
def _list_outputs(self):
"""This function... :return:"""
<|body_0|>
def _run_interface(self, runtime):
"""This function... :param runtime... | stack_v2_sparse_classes_36k_train_007085 | 13,234 | permissive | [
{
"docstring": "This function... :return:",
"name": "_list_outputs",
"signature": "def _list_outputs(self)"
},
{
"docstring": "This function... :param runtime: :return:",
"name": "_run_interface",
"signature": "def _run_interface(self, runtime)"
}
] | 2 | null | Implement the Python class `LOGISMOSBPreprocessing` described below.
Class description:
Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps.
Method signatures and docstrings:
- def _list_outputs(self): This function... :return:
- def _run_interface(self, runtime): This funct... | Implement the Python class `LOGISMOSBPreprocessing` described below.
Class description:
Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps.
Method signatures and docstrings:
- def _list_outputs(self): This function... :return:
- def _run_interface(self, runtime): This funct... | 64bb590918a188b660225e44ae54c1072f3a8056 | <|skeleton|>
class LOGISMOSBPreprocessing:
"""Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps."""
def _list_outputs(self):
"""This function... :return:"""
<|body_0|>
def _run_interface(self, runtime):
"""This function... :param runtime... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LOGISMOSBPreprocessing:
"""Interface for playing with the inputs so that LOGISMOS-B is optimized for the probability maps."""
def _list_outputs(self):
"""This function... :return:"""
outputs = self._outputs().get()
inputs = self.inputs.get()
for output in outputs:
... | the_stack_v2_python_sparse | AutoWorkup/logismosb/maclearn/nipype_interfaces.py | BRAINSia/BRAINSTools | train | 101 |
c9d2be9989c72db3539883496b12dd56c8e7a2dd | [
"input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\njson_params = input_json['APIParams']\njson_params['profile_id'] = input_j... | <|body_start_0|>
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))
json_params = input_json['APIParams']
... | This covers the API for filtering all support centre tickets raised by the user | PostLoginFilterMyTicketsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostLoginFilterMyTicketsAPI:
"""This covers the API for filtering all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to filtering all support centre tickets raised by the user"""
<|body_0|>
def post_login_filter_my_tickets_json(sel... | stack_v2_sparse_classes_36k_train_007086 | 3,184 | no_license | [
{
"docstring": "Post Function to filtering all support centre tickets raised by the user",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "This function fetches all the support centre tickets raised by logged in user :param request: { 'profile_id': 1, 'search_query':'te... | 2 | null | Implement the Python class `PostLoginFilterMyTicketsAPI` described below.
Class description:
This covers the API for filtering all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to filtering all support centre tickets raised by the user
- def post_... | Implement the Python class `PostLoginFilterMyTicketsAPI` described below.
Class description:
This covers the API for filtering all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to filtering all support centre tickets raised by the user
- def post_... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class PostLoginFilterMyTicketsAPI:
"""This covers the API for filtering all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to filtering all support centre tickets raised by the user"""
<|body_0|>
def post_login_filter_my_tickets_json(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostLoginFilterMyTicketsAPI:
"""This covers the API for filtering all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to filtering all support centre tickets raised by the user"""
input_json = request.data
output_json = dict(zip(['Availabilit... | the_stack_v2_python_sparse | Generic/common/supportcentre/api/post_login_filter_my_tickets/views_post_login_filter_my_tickets.py | archiemb303/common_backend_django | train | 0 |
d343a1d275fd62e0abc26da3325a2cdbceee8792 | [
"kwargs.setdefault('label', ms.password_field.label)\nkwargs.setdefault('class_', 'mr-2')\nkwargs.setdefault('v_model', '')\nkwargs['type'] = 'password'\nkwargs.setdefault('append_icon', 'fa-solid fa-eye-slash')\nsuper().__init__(**kwargs)\nself.on_event('click:append', self._toggle_pwd)",
"if self.type == 'text'... | <|body_start_0|>
kwargs.setdefault('label', ms.password_field.label)
kwargs.setdefault('class_', 'mr-2')
kwargs.setdefault('v_model', '')
kwargs['type'] = 'password'
kwargs.setdefault('append_icon', 'fa-solid fa-eye-slash')
super().__init__(**kwargs)
self.on_event... | PasswordField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordField:
def __init__(self, **kwargs) -> None:
"""Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, 'type' will be overwritten."""
<|body_0|>
def _toggle_pwd(self, *args) -> None:
""... | stack_v2_sparse_classes_36k_train_007087 | 34,979 | permissive | [
{
"docstring": "Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, 'type' will be overwritten.",
"name": "__init__",
"signature": "def __init__(self, **kwargs) -> None"
},
{
"docstring": "Toggle password visibility whe... | 2 | stack_v2_sparse_classes_30k_train_018153 | Implement the Python class `PasswordField` described below.
Class description:
Implement the PasswordField class.
Method signatures and docstrings:
- def __init__(self, **kwargs) -> None: Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, '... | Implement the Python class `PasswordField` described below.
Class description:
Implement the PasswordField class.
Method signatures and docstrings:
- def __init__(self, **kwargs) -> None: Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, '... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class PasswordField:
def __init__(self, **kwargs) -> None:
"""Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, 'type' will be overwritten."""
<|body_0|>
def _toggle_pwd(self, *args) -> None:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordField:
def __init__(self, **kwargs) -> None:
"""Custom widget to input passwords in text area and toggle its visibility. Args: kwargs: any parameter from a v.TextField. If set, 'type' will be overwritten."""
kwargs.setdefault('label', ms.password_field.label)
kwargs.setdefault(... | the_stack_v2_python_sparse | sepal_ui/sepalwidgets/inputs.py | 12rambau/sepal_ui | train | 17 | |
1d6b5bd018684a01fb4b43c0c24df9a5d6507482 | [
"survey = AnonymousSurvey(question)\nself.assertEqual(question, 'What is the name of the president of the United States? ')\nanswer = 'Joe Biden'\nsurvey.store_response(answer)\nself.assertIn(answer, survey.responses)",
"survey = AnonymousSurvey(question)\nself.assertEqual(question, 'What is the name of the presi... | <|body_start_0|>
survey = AnonymousSurvey(question)
self.assertEqual(question, 'What is the name of the president of the United States? ')
answer = 'Joe Biden'
survey.store_response(answer)
self.assertIn(answer, survey.responses)
<|end_body_0|>
<|body_start_1|>
survey = ... | Tests the implementations of class Anonymous survey | TestAnonymousClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousClass:
"""Tests the implementations of class Anonymous survey"""
def test_show_question(self):
"""Testing that the question returned is equal to the one i used to initialize the class"""
<|body_0|>
def test_show_three_question(self):
"""Testing that ... | stack_v2_sparse_classes_36k_train_007088 | 1,191 | no_license | [
{
"docstring": "Testing that the question returned is equal to the one i used to initialize the class",
"name": "test_show_question",
"signature": "def test_show_question(self)"
},
{
"docstring": "Testing that the question returned is equal to the one i used to initialize the class",
"name":... | 2 | stack_v2_sparse_classes_30k_train_016240 | Implement the Python class `TestAnonymousClass` described below.
Class description:
Tests the implementations of class Anonymous survey
Method signatures and docstrings:
- def test_show_question(self): Testing that the question returned is equal to the one i used to initialize the class
- def test_show_three_question... | Implement the Python class `TestAnonymousClass` described below.
Class description:
Tests the implementations of class Anonymous survey
Method signatures and docstrings:
- def test_show_question(self): Testing that the question returned is equal to the one i used to initialize the class
- def test_show_three_question... | fcd5e5eb2b7c7fb02fc9d31eebfb78c06bbd396a | <|skeleton|>
class TestAnonymousClass:
"""Tests the implementations of class Anonymous survey"""
def test_show_question(self):
"""Testing that the question returned is equal to the one i used to initialize the class"""
<|body_0|>
def test_show_three_question(self):
"""Testing that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnonymousClass:
"""Tests the implementations of class Anonymous survey"""
def test_show_question(self):
"""Testing that the question returned is equal to the one i used to initialize the class"""
survey = AnonymousSurvey(question)
self.assertEqual(question, 'What is the name o... | the_stack_v2_python_sparse | textbook/testing3.py | Toyin96/bookish-engine | train | 0 |
4cde60505d4564395914d09667c851ff3c4de3fe | [
"super().__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enco_output = self.encoder(inputs, training, encoder_mask)\ndeco_output = se... | <|body_start_0|>
super().__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_start_1|>
... | transformer network | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the numbe... | stack_v2_sparse_classes_36k_train_007089 | 1,678 | no_license | [
{
"docstring": "N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layers input_vocab - the size of the input vocabulary target_vocab - the size of the target vocabulary max_seq_input - the m... | 2 | stack_v2_sparse_classes_30k_train_004936 | Implement the Python class `Transformer` described below.
Class description:
transformer network
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): N - the number of blocks in the encoder and decoder dm - the dimensionalit... | Implement the Python class `Transformer` described below.
Class description:
transformer network
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): N - the number of blocks in the encoder and decoder dm - the dimensionalit... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class Transformer:
"""transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the numbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""transformer network"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden u... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | Gaspela/holbertonschool-machine_learning | train | 0 |
b2f47c2d3c0fc01cdbd6b69de78dad3af3ab0cf6 | [
"password = Utils.generate_random_password()\nnew_credential = Credential.objects.create(password=make_password(password), email=email)\nnew_credential.save()\nprint(f'PASSWORD: {password}')\nreturn new_credential.id",
"Utils.validate_uuid(id_credential)\nif not Credential.objects.filter(id=id_credential).exists(... | <|body_start_0|>
password = Utils.generate_random_password()
new_credential = Credential.objects.create(password=make_password(password), email=email)
new_credential.save()
print(f'PASSWORD: {password}')
return new_credential.id
<|end_body_0|>
<|body_start_1|>
Utils.vali... | Service class for credential related operations | CredentialService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CredentialService:
"""Service class for credential related operations"""
def add_credential(email):
"""Method create a new credential :param password: State name :return: Credential created id"""
<|body_0|>
def is_valid_credential(id_credential):
"""Checks if the... | stack_v2_sparse_classes_36k_train_007090 | 3,325 | no_license | [
{
"docstring": "Method create a new credential :param password: State name :return: Credential created id",
"name": "add_credential",
"signature": "def add_credential(email)"
},
{
"docstring": "Checks if the specified credential exists :param id_credential: ID of credential to be checked",
"... | 5 | stack_v2_sparse_classes_30k_train_005471 | Implement the Python class `CredentialService` described below.
Class description:
Service class for credential related operations
Method signatures and docstrings:
- def add_credential(email): Method create a new credential :param password: State name :return: Credential created id
- def is_valid_credential(id_crede... | Implement the Python class `CredentialService` described below.
Class description:
Service class for credential related operations
Method signatures and docstrings:
- def add_credential(email): Method create a new credential :param password: State name :return: Credential created id
- def is_valid_credential(id_crede... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class CredentialService:
"""Service class for credential related operations"""
def add_credential(email):
"""Method create a new credential :param password: State name :return: Credential created id"""
<|body_0|>
def is_valid_credential(id_credential):
"""Checks if the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CredentialService:
"""Service class for credential related operations"""
def add_credential(email):
"""Method create a new credential :param password: State name :return: Credential created id"""
password = Utils.generate_random_password()
new_credential = Credential.objects.creat... | the_stack_v2_python_sparse | backend/martin_helder/services/credential_service.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
d708bfebda5f0eeebc215e02ad9642b01a272e61 | [
"T = range(len(var_costs[0]))\nindex = [np.argsort([unit_costs[t] for unit_costs in var_costs]) for t in T]\nself.sorted_costs = [[var_costs[i][t] for i in index[t]] for t in T]\nself.sorted_capacities = [[capacities[i][t] for i in index[t]] for t in T]\nself.sorted_cumulative_capacities = [np.cumsum(self.sorted_ca... | <|body_start_0|>
T = range(len(var_costs[0]))
index = [np.argsort([unit_costs[t] for unit_costs in var_costs]) for t in T]
self.sorted_costs = [[var_costs[i][t] for i in index[t]] for t in T]
self.sorted_capacities = [[capacities[i][t] for i in index[t]] for t in T]
self.sorted_c... | Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator. | SupplyCosts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplyCosts:
"""Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator."""
def __init__(self, var_costs, capacities):
"""Constructs object from variable costs and capacities. Args var_... | stack_v2_sparse_classes_36k_train_007091 | 2,840 | permissive | [
{
"docstring": "Constructs object from variable costs and capacities. Args var_costs : list/np.array two-dimensional list/array with units in first dimension and time steps in 2nd dimension capacities : list/np.array two-dimensional list/array with units in first dimension and time steps in 2nd dimension",
... | 2 | stack_v2_sparse_classes_30k_train_006441 | Implement the Python class `SupplyCosts` described below.
Class description:
Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator.
Method signatures and docstrings:
- def __init__(self, var_costs, capacities): Constr... | Implement the Python class `SupplyCosts` described below.
Class description:
Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator.
Method signatures and docstrings:
- def __init__(self, var_costs, capacities): Constr... | 80cc55ba234d416ee402d99d0d0d0eac9aff2c2f | <|skeleton|>
class SupplyCosts:
"""Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator."""
def __init__(self, var_costs, capacities):
"""Constructs object from variable costs and capacities. Args var_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupplyCosts:
"""Computes derivative from hourly variable costs and capacities. Builds up a piece-wise function that maps quantities in hour to costs of marginal generator."""
def __init__(self, var_costs, capacities):
"""Constructs object from variable costs and capacities. Args var_costs : list/... | the_stack_v2_python_sparse | FRIGG/scripts/Modules/SupplyCosts.py | tperger/linkages | train | 0 |
333c403747535a0b4034a3f3dcada7b35e643509 | [
"if k <= 1:\n return head\nreversedCount = 0\nnullHead = ListNode(None)\ntailNode, headOfRestList = (None, None)\nnode = head\nwhile node is not None:\n if reversedCount == k:\n break\n if nullHead.next is None:\n tailNode = node\n headOfRestList = node.next\n node.next = nullHead.next\... | <|body_start_0|>
if k <= 1:
return head
reversedCount = 0
nullHead = ListNode(None)
tailNode, headOfRestList = (None, None)
node = head
while node is not None:
if reversedCount == k:
break
if nullHead.next is None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode:
"""反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回滚 :return:"""
<|body_0|>
def reverseKGroup(self, head: ListNode, k: int) -> ListNode... | stack_v2_sparse_classes_36k_train_007092 | 2,662 | no_license | [
{
"docstring": "反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回滚 :return:",
"name": "reverseFirstKNode",
"signature": "def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode"
},
{
"docstring": "将链表每k个反转一次,返回最终的链表 :param h... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode: 反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode: 反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回... | c13c0380a3ae9fef201ae53d7004b9f4224f1620 | <|skeleton|>
class Solution:
def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode:
"""反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回滚 :return:"""
<|body_0|>
def reverseKGroup(self, head: ListNode, k: int) -> ListNode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseFirstKNode(self, head: ListNode, k: int, rollbackDependsOnK=False) -> ListNode:
"""反转链表的前k个节点,返回反转后的链表 :param head: 头节点 :param k: 前k个节点 :param rollbackDependsOnK: k过大时是否回滚 :return:"""
if k <= 1:
return head
reversedCount = 0
nullHead = ListNode(... | the_stack_v2_python_sparse | 2020.5/ReverseKGroup.py | IamWilliamWang/Leetcode-practice | train | 0 | |
502bbfdf7c4e846520c68edfcc10dd46bc930eb2 | [
"if time_format is None:\n time_format = _TIME_FORMAT\nif timestamp is None:\n return datetime.datetime.now().strftime(time_format)\nlocal_time = time.localtime(timestamp)\ntime_data = time.strftime(time_format, local_time)\nreturn time_data",
"if magnitude == 's':\n factor = 1\nelif magnitude == 'ms':\n... | <|body_start_0|>
if time_format is None:
time_format = _TIME_FORMAT
if timestamp is None:
return datetime.datetime.now().strftime(time_format)
local_time = time.localtime(timestamp)
time_data = time.strftime(time_format, local_time)
return time_data
<|end_... | TimeHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeHelper:
def get_time_from_timestamp(timestamp=None, time_format=None):
"""功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() 场景2:获取当前时间,时间格式为:%H:%M:%S get_time_from_timestamp(time_format="%H:%M:%S") 场景3:根据指定时间戳来获取时间,时间格式为:%Y... | stack_v2_sparse_classes_36k_train_007093 | 3,955 | no_license | [
{
"docstring": "功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() 场景2:获取当前时间,时间格式为:%H:%M:%S get_time_from_timestamp(time_format=\"%H:%M:%S\") 场景3:根据指定时间戳来获取时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp(timestamp=1569850832) :param timestamp: 待转换为... | 3 | stack_v2_sparse_classes_30k_train_000938 | Implement the Python class `TimeHelper` described below.
Class description:
Implement the TimeHelper class.
Method signatures and docstrings:
- def get_time_from_timestamp(timestamp=None, time_format=None): 功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() ... | Implement the Python class `TimeHelper` described below.
Class description:
Implement the TimeHelper class.
Method signatures and docstrings:
- def get_time_from_timestamp(timestamp=None, time_format=None): 功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() ... | 53dd0d094adf5ab3a9cd42f7354aead4f92d0326 | <|skeleton|>
class TimeHelper:
def get_time_from_timestamp(timestamp=None, time_format=None):
"""功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() 场景2:获取当前时间,时间格式为:%H:%M:%S get_time_from_timestamp(time_format="%H:%M:%S") 场景3:根据指定时间戳来获取时间,时间格式为:%Y... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeHelper:
def get_time_from_timestamp(timestamp=None, time_format=None):
"""功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() 场景2:获取当前时间,时间格式为:%H:%M:%S get_time_from_timestamp(time_format="%H:%M:%S") 场景3:根据指定时间戳来获取时间,时间格式为:%Y-%m-%d %H:%M:%... | the_stack_v2_python_sparse | DataCrawler_alarm/base/time_helper.py | you282507/api_demo | train | 0 | |
a5bfdaf0cd2d46abb1a791de36ee4941dd7e959e | [
"self.nombre = nombre\nself.grupo = grupo\nself.nota = nota\nself.práctica = práctica",
"cadena = f'Nombre: {self.nombre}.\\nGrupo: {self.grupo}.\\nNota: {self.nota}.\\n'\nif self.práctica:\n cadena += 'Practica entregada.'\nelse:\n cadena += 'Practica no entregada'\nreturn cadena"
] | <|body_start_0|>
self.nombre = nombre
self.grupo = grupo
self.nota = nota
self.práctica = práctica
<|end_body_0|>
<|body_start_1|>
cadena = f'Nombre: {self.nombre}.\nGrupo: {self.grupo}.\nNota: {self.nota}.\n'
if self.práctica:
cadena += 'Practica entregada.'... | Estudiantes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Estudiantes:
def __init__(self, nombre, grupo, nota, práctica):
"""docstring"""
<|body_0|>
def __str__(self):
"""docstring"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nombre = nombre
self.grupo = grupo
self.nota = nota
... | stack_v2_sparse_classes_36k_train_007094 | 1,639 | no_license | [
{
"docstring": "docstring",
"name": "__init__",
"signature": "def __init__(self, nombre, grupo, nota, práctica)"
},
{
"docstring": "docstring",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `Estudiantes` described below.
Class description:
Implement the Estudiantes class.
Method signatures and docstrings:
- def __init__(self, nombre, grupo, nota, práctica): docstring
- def __str__(self): docstring | Implement the Python class `Estudiantes` described below.
Class description:
Implement the Estudiantes class.
Method signatures and docstrings:
- def __init__(self, nombre, grupo, nota, práctica): docstring
- def __str__(self): docstring
<|skeleton|>
class Estudiantes:
def __init__(self, nombre, grupo, nota, pr... | 03f15100991724a49437df3ce704837812173fc5 | <|skeleton|>
class Estudiantes:
def __init__(self, nombre, grupo, nota, práctica):
"""docstring"""
<|body_0|>
def __str__(self):
"""docstring"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Estudiantes:
def __init__(self, nombre, grupo, nota, práctica):
"""docstring"""
self.nombre = nombre
self.grupo = grupo
self.nota = nota
self.práctica = práctica
def __str__(self):
"""docstring"""
cadena = f'Nombre: {self.nombre}.\nGrupo: {self.grup... | the_stack_v2_python_sparse | 7.CLASES_Y_DICCIONARIOS/395.py | FrankCasanova/Python | train | 0 | |
6493da2b3696799d3b27d5e7f5f5bf16adc50fbe | [
"data = request.body\nif not data:\n return RESPONSE_400_EMPTY_JSON\ndata = {'longitude': data.get('longitude'), 'latitude': data.get('latitude'), 'address': data.get('address'), 'name': data.get('name'), 'stop_id': data.get('stop_id')}\nif not place_data_validator(data):\n return RESPONSE_400_INVALID_DATA\np... | <|body_start_0|>
data = request.body
if not data:
return RESPONSE_400_EMPTY_JSON
data = {'longitude': data.get('longitude'), 'latitude': data.get('latitude'), 'address': data.get('address'), 'name': data.get('name'), 'stop_id': data.get('stop_id')}
if not place_data_validator... | Class that handle HTTP requests for place model. | PlaceView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaceView:
"""Class that handle HTTP requests for place model."""
def post(self, request, place_id=None):
"""Handle the request to create a new place object."""
<|body_0|>
def get(self, request, place_id=None):
"""Handle the request to retrieve a place object or ... | stack_v2_sparse_classes_36k_train_007095 | 3,912 | no_license | [
{
"docstring": "Handle the request to create a new place object.",
"name": "post",
"signature": "def post(self, request, place_id=None)"
},
{
"docstring": "Handle the request to retrieve a place object or user`s places.",
"name": "get",
"signature": "def get(self, request, place_id=None)... | 4 | null | Implement the Python class `PlaceView` described below.
Class description:
Class that handle HTTP requests for place model.
Method signatures and docstrings:
- def post(self, request, place_id=None): Handle the request to create a new place object.
- def get(self, request, place_id=None): Handle the request to retrie... | Implement the Python class `PlaceView` described below.
Class description:
Class that handle HTTP requests for place model.
Method signatures and docstrings:
- def post(self, request, place_id=None): Handle the request to create a new place object.
- def get(self, request, place_id=None): Handle the request to retrie... | c5f533bd049f6939037b14045e2aa2550aaac36a | <|skeleton|>
class PlaceView:
"""Class that handle HTTP requests for place model."""
def post(self, request, place_id=None):
"""Handle the request to create a new place object."""
<|body_0|>
def get(self, request, place_id=None):
"""Handle the request to retrieve a place object or ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaceView:
"""Class that handle HTTP requests for place model."""
def post(self, request, place_id=None):
"""Handle the request to create a new place object."""
data = request.body
if not data:
return RESPONSE_400_EMPTY_JSON
data = {'longitude': data.get('longi... | the_stack_v2_python_sparse | way_to_home/place/views.py | Lv-365python/wayToHome | train | 1 |
976402db022bf67f63dfed5157ba4f203c6a85e9 | [
"super().__init__(netatmo_room.data_handler)\nself.entity_description = description\nself._room = netatmo_room.room\nself._id = self._room.entity_id\nself._publishers.extend([{'name': HOME, 'home_id': netatmo_room.room.home.entity_id, SIGNAL_NAME: netatmo_room.signal_name}])\nself._attr_name = f'{self._room.name} {... | <|body_start_0|>
super().__init__(netatmo_room.data_handler)
self.entity_description = description
self._room = netatmo_room.room
self._id = self._room.entity_id
self._publishers.extend([{'name': HOME, 'home_id': netatmo_room.room.home.entity_id, SIGNAL_NAME: netatmo_room.signal_... | Implementation of a Netatmo room sensor. | NetatmoRoomSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetatmoRoomSensor:
"""Implementation of a Netatmo room sensor."""
def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def async_update_callback(self) -> None:
"""Update the en... | stack_v2_sparse_classes_36k_train_007096 | 25,750 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None"
},
{
"docstring": "Update the entity's state.",
"name": "async_update_callback",
"signature": "def async_update_c... | 2 | null | Implement the Python class `NetatmoRoomSensor` described below.
Class description:
Implementation of a Netatmo room sensor.
Method signatures and docstrings:
- def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor.
- def async_update_callback(self) -... | Implement the Python class `NetatmoRoomSensor` described below.
Class description:
Implementation of a Netatmo room sensor.
Method signatures and docstrings:
- def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None: Initialize the sensor.
- def async_update_callback(self) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NetatmoRoomSensor:
"""Implementation of a Netatmo room sensor."""
def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def async_update_callback(self) -> None:
"""Update the en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetatmoRoomSensor:
"""Implementation of a Netatmo room sensor."""
def __init__(self, netatmo_room: NetatmoRoom, description: NetatmoSensorEntityDescription) -> None:
"""Initialize the sensor."""
super().__init__(netatmo_room.data_handler)
self.entity_description = description
... | the_stack_v2_python_sparse | homeassistant/components/netatmo/sensor.py | home-assistant/core | train | 35,501 |
3ca72b858f0578ee43c1a5deba8e3a2095241c8d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IosHomeScreenApp()",
"from .ios_home_screen_item import IosHomeScreenItem\nfrom .ios_home_screen_item import IosHomeScreenItem\nfields: Dict[str, Callable[[Any], None]] = {'bundleID': lambda n: setattr(self, 'bundle_i_d', n.get_str_val... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IosHomeScreenApp()
<|end_body_0|>
<|body_start_1|>
from .ios_home_screen_item import IosHomeScreenItem
from .ios_home_screen_item import IosHomeScreenItem
fields: Dict[str, Calla... | Represents an icon for an app on the Home Screen | IosHomeScreenApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IosHomeScreenApp:
"""Represents an icon for an app on the Home Screen"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosHomeScreenApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to ... | stack_v2_sparse_classes_36k_train_007097 | 2,235 | 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: IosHomeScreenApp",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_003269 | Implement the Python class `IosHomeScreenApp` described below.
Class description:
Represents an icon for an app on the Home Screen
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosHomeScreenApp: Creates a new instance of the appropriate class based on... | Implement the Python class `IosHomeScreenApp` described below.
Class description:
Represents an icon for an app on the Home Screen
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosHomeScreenApp: Creates a new instance of the appropriate class based on... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IosHomeScreenApp:
"""Represents an icon for an app on the Home Screen"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosHomeScreenApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IosHomeScreenApp:
"""Represents an icon for an app on the Home Screen"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IosHomeScreenApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read t... | the_stack_v2_python_sparse | msgraph/generated/models/ios_home_screen_app.py | microsoftgraph/msgraph-sdk-python | train | 135 |
2886d1f63db3d48b43dd5f047dc144c659c102e5 | [
"assert features.is_contiguous()\nassert indices.is_contiguous()\nB, nfeatures, nsample = indices.size()\n_, C, N = features.size()\noutput = torch.cuda.FloatTensor(B, C, nfeatures, nsample)\ngroup_points_ext.forward(B, C, N, nfeatures, nsample, features, indices, output)\nctx.for_backwards = (indices, N)\nreturn o... | <|body_start_0|>
assert features.is_contiguous()
assert indices.is_contiguous()
B, nfeatures, nsample = indices.size()
_, C, N = features.size()
output = torch.cuda.FloatTensor(B, C, nfeatures, nsample)
group_points_ext.forward(B, C, N, nfeatures, nsample, features, indic... | Grouping Operation. Group feature with given index. | GroupingOperation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupingOperation:
"""Grouping Operation. Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""forward. Args: features (Tensor): (B, C, N) tensor of features to group. indices (Tensor): (B, npoint, nsample) the indicie... | stack_v2_sparse_classes_36k_train_007098 | 1,896 | permissive | [
{
"docstring": "forward. Args: features (Tensor): (B, C, N) tensor of features to group. indices (Tensor): (B, npoint, nsample) the indicies of features to group with. Returns: Tensor: (B, C, npoint, nsample) Grouped features.",
"name": "forward",
"signature": "def forward(ctx, features: torch.Tensor, i... | 2 | stack_v2_sparse_classes_30k_train_008097 | Implement the Python class `GroupingOperation` described below.
Class description:
Grouping Operation. Group feature with given index.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor: forward. Args: features (Tensor): (B, C, N) tensor of features to ... | Implement the Python class `GroupingOperation` described below.
Class description:
Grouping Operation. Group feature with given index.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor: forward. Args: features (Tensor): (B, C, N) tensor of features to ... | 9987806185a4e1619bc15ceecb8a1755e764ff68 | <|skeleton|>
class GroupingOperation:
"""Grouping Operation. Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""forward. Args: features (Tensor): (B, C, N) tensor of features to group. indices (Tensor): (B, npoint, nsample) the indicie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupingOperation:
"""Grouping Operation. Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""forward. Args: features (Tensor): (B, C, N) tensor of features to group. indices (Tensor): (B, npoint, nsample) the indicies of features... | the_stack_v2_python_sparse | gorilla3d/ops/group_points/group_points.py | SijanNeupane49/gorilla-3d | train | 0 |
823965ea79cc569e373f54f537779c46c54be49b | [
"super(TweetProcess, self).__init__()\nself.logger = getLogger(__name__)\nself.queue = que\nself.daemon = True\nself.get_auth = GetAuth()\nself.tweetable = False",
"while True:\n try:\n data = self.queue.get()\n if data is None:\n break\n self.logger.debug('[TWEET] ' + data)\n ... | <|body_start_0|>
super(TweetProcess, self).__init__()
self.logger = getLogger(__name__)
self.queue = que
self.daemon = True
self.get_auth = GetAuth()
self.tweetable = False
<|end_body_0|>
<|body_start_1|>
while True:
try:
data = self.q... | This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty. | TweetProcess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetProcess:
"""This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty."""
def __init__(self, que: Queue):
"""Args: que: queue.Queue object"""
<|body_0|>
def run(self) -> None:
"""Get data from Queue, and t... | stack_v2_sparse_classes_36k_train_007099 | 2,136 | permissive | [
{
"docstring": "Args: que: queue.Queue object",
"name": "__init__",
"signature": "def __init__(self, que: Queue)"
},
{
"docstring": "Get data from Queue, and tweet until Queue become empty",
"name": "run",
"signature": "def run(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_001948 | Implement the Python class `TweetProcess` described below.
Class description:
This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty.
Method signatures and docstrings:
- def __init__(self, que: Queue): Args: que: queue.Queue object
- def run(self) -> None: Get d... | Implement the Python class `TweetProcess` described below.
Class description:
This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty.
Method signatures and docstrings:
- def __init__(self, que: Queue): Args: que: queue.Queue object
- def run(self) -> None: Get d... | 4f696ce5198196ea79dc0d25a30cb22230342ca9 | <|skeleton|>
class TweetProcess:
"""This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty."""
def __init__(self, que: Queue):
"""Args: que: queue.Queue object"""
<|body_0|>
def run(self) -> None:
"""Get data from Queue, and t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TweetProcess:
"""This class' instance has Queue when created. Queue has tweet information. So tweet it until Queue become empty."""
def __init__(self, que: Queue):
"""Args: que: queue.Queue object"""
super(TweetProcess, self).__init__()
self.logger = getLogger(__name__)
se... | the_stack_v2_python_sparse | qkoubot/network/tweeter.py | pddg/qkouserver | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.