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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1264702016b4b0dd3f2522762fef5edf5eed3e32 | [
"\"\"\"\n Make sure you do not delete the following line. If you would like to\n use Manhattan distances instead of maze distances in order to save\n on initialization time, please take a look at\n CaptureAgent.registerInitialState in captureAgents.py.\n \"\"\"\nCaptureAgent.registerInitialState(self... | <|body_start_0|>
"""
Make sure you do not delete the following line. If you would like to
use Manhattan distances instead of maze distances in order to save
on initialization time, please take a look at
CaptureAgent.registerInitialState in captureAgents.py.
... | A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum. | DummyAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup o... | stack_v2_sparse_classes_36k_train_027300 | 44,661 | no_license | [
{
"docstring": "This method handles the initial setup of the agent to populate useful fields (such as what team we're on). A distanceCalculator instance caches the maze distances between each pair of positions, so your agents can use: self.distancer.getDistance(p1, p2) IMPORTANT: This method may run for at most... | 2 | stack_v2_sparse_classes_30k_train_007393 | Implement the Python class `DummyAgent` described below.
Class description:
A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum.
Method signatures and docstrings:
- def registerInitialState(... | Implement the Python class `DummyAgent` described below.
Class description:
A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum.
Method signatures and docstrings:
- def registerInitialState(... | 85b38e3cc0dd6857c24784ea44834f56e23107bb | <|skeleton|>
class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup of the agent t... | the_stack_v2_python_sparse | pacman-contest/myTeam-YK.py | iknow1988/pacman | train | 2 |
c904607a23e2151894c8de3492c301d812a3a7c5 | [
"super().__init__(resource, location, name)\nself._func = func\nrequest = requests.get(f'{self._resource}/{self._func}', timeout=10)\nif request.status_code != HTTPStatus.OK:\n _LOGGER.error(\"Can't find function\")\n return\ntry:\n request.json()['return_value']\nexcept KeyError:\n _LOGGER.error('No re... | <|body_start_0|>
super().__init__(resource, location, name)
self._func = func
request = requests.get(f'{self._resource}/{self._func}', timeout=10)
if request.status_code != HTTPStatus.OK:
_LOGGER.error("Can't find function")
return
try:
request... | Representation of an aREST switch. | ArestSwitchFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArestSwitchFunction:
"""Representation of an aREST switch."""
def __init__(self, resource, location, name, func):
"""Initialize the switch."""
<|body_0|>
def turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_1|>
def turn_off(self... | stack_v2_sparse_classes_36k_train_027301 | 6,972 | permissive | [
{
"docstring": "Initialize the switch.",
"name": "__init__",
"signature": "def __init__(self, resource, location, name, func)"
},
{
"docstring": "Turn the device on.",
"name": "turn_on",
"signature": "def turn_on(self, **kwargs: Any) -> None"
},
{
"docstring": "Turn the device of... | 4 | null | Implement the Python class `ArestSwitchFunction` described below.
Class description:
Representation of an aREST switch.
Method signatures and docstrings:
- def __init__(self, resource, location, name, func): Initialize the switch.
- def turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def turn_off(self, **... | Implement the Python class `ArestSwitchFunction` described below.
Class description:
Representation of an aREST switch.
Method signatures and docstrings:
- def __init__(self, resource, location, name, func): Initialize the switch.
- def turn_on(self, **kwargs: Any) -> None: Turn the device on.
- def turn_off(self, **... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ArestSwitchFunction:
"""Representation of an aREST switch."""
def __init__(self, resource, location, name, func):
"""Initialize the switch."""
<|body_0|>
def turn_on(self, **kwargs: Any) -> None:
"""Turn the device on."""
<|body_1|>
def turn_off(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArestSwitchFunction:
"""Representation of an aREST switch."""
def __init__(self, resource, location, name, func):
"""Initialize the switch."""
super().__init__(resource, location, name)
self._func = func
request = requests.get(f'{self._resource}/{self._func}', timeout=10)
... | the_stack_v2_python_sparse | homeassistant/components/arest/switch.py | home-assistant/core | train | 35,501 |
e5b35620670ff5b339947fd859034c8133b85b47 | [
"self.fields = fields\nself.appended_fields = appended_fields\nself.expandable = expandable\nsuper().__init__(fields, **kwargs)",
"if extra_context is None:\n extra_context = {}\nextra_context['appended_fields'] = [form[field] for field in self.appended_fields]\nextra_context['expandable'] = self.expandable\nr... | <|body_start_0|>
self.fields = fields
self.appended_fields = appended_fields
self.expandable = expandable
super().__init__(fields, **kwargs)
<|end_body_0|>
<|body_start_1|>
if extra_context is None:
extra_context = {}
extra_context['appended_fields'] = [form[... | Custom crispy form field that includes appended_fields in the context. | FilterFormField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterFormField:
"""Custom crispy form field that includes appended_fields in the context."""
def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs):
"""Set the given field values on the field model."""
<|body_0|>
def render(self, form, ... | stack_v2_sparse_classes_36k_train_027302 | 15,821 | permissive | [
{
"docstring": "Set the given field values on the field model.",
"name": "__init__",
"signature": "def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs)"
},
{
"docstring": "Render the main_field and appended_fields in the template and return it.",
"name": "... | 2 | null | Implement the Python class `FilterFormField` described below.
Class description:
Custom crispy form field that includes appended_fields in the context.
Method signatures and docstrings:
- def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs): Set the given field values on the field ... | Implement the Python class `FilterFormField` described below.
Class description:
Custom crispy form field that includes appended_fields in the context.
Method signatures and docstrings:
- def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs): Set the given field values on the field ... | 51177c6fb9354cd028f7099fc10d83b1051fd50d | <|skeleton|>
class FilterFormField:
"""Custom crispy form field that includes appended_fields in the context."""
def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs):
"""Set the given field values on the field model."""
<|body_0|>
def render(self, form, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterFormField:
"""Custom crispy form field that includes appended_fields in the context."""
def __init__(self, fields, appended_fields: list[str], expandable: bool=False, **kwargs):
"""Set the given field values on the field model."""
self.fields = fields
self.appended_fields = ... | the_stack_v2_python_sparse | hawc/apps/common/forms.py | shapiromatron/hawc | train | 25 |
9408a2c0c7284f718f4165f07087393dca5b8cc4 | [
"newIntervals = [(intervals[i].start, intervals[i].end, i) for i in range(len(intervals))]\nnewIntervals.sort()\nintervalDict = {}\nfor i in newIntervals:\n intervalDict[i[0]] = i\nresult = [-1] * len(intervals)\nstartIndexs = list(intervalDict.keys())\nstartIndexs.sort()\nj = 0\nfor i in intervals:\n ed = i.... | <|body_start_0|>
newIntervals = [(intervals[i].start, intervals[i].end, i) for i in range(len(intervals))]
newIntervals.sort()
intervalDict = {}
for i in newIntervals:
intervalDict[i[0]] = i
result = [-1] * len(intervals)
startIndexs = list(intervalDict.keys()... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int]"""
<|body_0|>
def findNextGreater(self, arr, target):
"""assume no duplicates in arr :param arr: :param target: :return:"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_027303 | 1,881 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[int]",
"name": "findRightInterval",
"signature": "def findRightInterval(self, intervals)"
},
{
"docstring": "assume no duplicates in arr :param arr: :param target: :return:",
"name": "findNextGreater",
"signature": "def findNex... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRightInterval(self, intervals): :type intervals: List[Interval] :rtype: List[int]
- def findNextGreater(self, arr, target): assume no duplicates in arr :param arr: :param... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRightInterval(self, intervals): :type intervals: List[Interval] :rtype: List[int]
- def findNextGreater(self, arr, target): assume no duplicates in arr :param arr: :param... | 7a1c3aba65f338f6e11afd2864dabd2b26142b6c | <|skeleton|>
class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int]"""
<|body_0|>
def findNextGreater(self, arr, target):
"""assume no duplicates in arr :param arr: :param target: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRightInterval(self, intervals):
""":type intervals: List[Interval] :rtype: List[int]"""
newIntervals = [(intervals[i].start, intervals[i].end, i) for i in range(len(intervals))]
newIntervals.sort()
intervalDict = {}
for i in newIntervals:
i... | the_stack_v2_python_sparse | exercise/leetcode/python_src/by2017_Sep/Leet436.py | SS4G/AlgorithmTraining | train | 2 | |
a18fa30dc9c14ec942f5644fa7a7da799adb86c2 | [
"del pipeline_info, component_info\ninput_config = example_gen_pb2.Input()\njson_format.Parse(exec_properties[utils.INPUT_CONFIG_KEY], input_config)\ninput_base = exec_properties[utils.INPUT_BASE_KEY]\nlogging.debug('Processing input %s.', input_base)\nfingerprint, span, version = utils.calculate_splits_fingerprint... | <|body_start_0|>
del pipeline_info, component_info
input_config = example_gen_pb2.Input()
json_format.Parse(exec_properties[utils.INPUT_CONFIG_KEY], input_config)
input_base = exec_properties[utils.INPUT_BASE_KEY]
logging.debug('Processing input %s.', input_base)
fingerpr... | Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen. | Driver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[... | stack_v2_sparse_classes_36k_train_027304 | 3,843 | permissive | [
{
"docstring": "Overrides BaseDriver.resolve_exec_properties().",
"name": "resolve_exec_properties",
"signature": "def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[Text, Any]"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_018737 | Implement the Python class `Driver` described below.
Class description:
Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen.
Method signatures and docstrings:
- def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_ty... | Implement the Python class `Driver` described below.
Class description:
Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen.
Method signatures and docstrings:
- def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_ty... | ff6917997340401570d05a4d3ebd6e8ab5760495 | <|skeleton|>
class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[Text, Any]:
... | the_stack_v2_python_sparse | tfx/components/example_gen/driver.py | 18jeffreyma/tfx | train | 3 |
ac0082e602a2e91347149e365c2b5bdcc7e35896 | [
"if delivery_method == OrderDeliveryMethod.HOME_DELIVERY and self.home_minimum_order_amount > order_amount:\n return False\nreturn True",
"if delivery_method == OrderDeliveryMethod.HOME_DELIVERY:\n if order_amount < self.home_minimum_free_amount:\n result = decimal.Decimal(0)\n else:\n resu... | <|body_start_0|>
if delivery_method == OrderDeliveryMethod.HOME_DELIVERY and self.home_minimum_order_amount > order_amount:
return False
return True
<|end_body_0|>
<|body_start_1|>
if delivery_method == OrderDeliveryMethod.HOME_DELIVERY:
if order_amount < self.home_minim... | 订单配送配置模型类 | DeliveryConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeliveryConfig:
"""订单配送配置模型类"""
def limit(self, delivery_method, order_amount):
"""订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:"""
<|body_0|>
def calculate(self, delivery_method, order_amount):
"""订单优惠计算,返回运费可以优惠的金额 :param delivery_metho... | stack_v2_sparse_classes_36k_train_027305 | 4,978 | permissive | [
{
"docstring": "订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:",
"name": "limit",
"signature": "def limit(self, delivery_method, order_amount)"
},
{
"docstring": "订单优惠计算,返回运费可以优惠的金额 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:",
"name": "calculate",... | 4 | stack_v2_sparse_classes_30k_train_002680 | Implement the Python class `DeliveryConfig` described below.
Class description:
订单配送配置模型类
Method signatures and docstrings:
- def limit(self, delivery_method, order_amount): 订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:
- def calculate(self, delivery_method, order_amount): 订单优惠计算,返回运费可以优惠的金额 ... | Implement the Python class `DeliveryConfig` described below.
Class description:
订单配送配置模型类
Method signatures and docstrings:
- def limit(self, delivery_method, order_amount): 订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:
- def calculate(self, delivery_method, order_amount): 订单优惠计算,返回运费可以优惠的金额 ... | c0a4de1a4479fe83f36108c1fdd4d68d18348b8d | <|skeleton|>
class DeliveryConfig:
"""订单配送配置模型类"""
def limit(self, delivery_method, order_amount):
"""订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:"""
<|body_0|>
def calculate(self, delivery_method, order_amount):
"""订单优惠计算,返回运费可以优惠的金额 :param delivery_metho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeliveryConfig:
"""订单配送配置模型类"""
def limit(self, delivery_method, order_amount):
"""订单配送限制 :param delivery_method: 配送方式 :param order_amount: 订单总价 :return:"""
if delivery_method == OrderDeliveryMethod.HOME_DELIVERY and self.home_minimum_order_amount > order_amount:
return False
... | the_stack_v2_python_sparse | wsc_django/wsc_django/apps/delivery/models.py | hzh595395786/wsc_django | train | 2 |
8d13e9e9517feb63f9e3f69015eab608b2de472c | [
"try:\n if self.id is None:\n return self.query.all()\n if self.id is not None and type(self.id) is int and (self.id >= 0):\n return self.query.get(self.id)\nexcept Exception as e:\n return e.__cause__.args[1]",
"try:\n db.session.add(self)\n return db.session.commit()\nexcept Excepti... | <|body_start_0|>
try:
if self.id is None:
return self.query.all()
if self.id is not None and type(self.id) is int and (self.id >= 0):
return self.query.get(self.id)
except Exception as e:
return e.__cause__.args[1]
<|end_body_0|>
<|bod... | Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hyperlink to the component] status {[in... | Component | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hy... | stack_v2_sparse_classes_36k_train_027306 | 10,042 | no_license | [
{
"docstring": "Using get all component or get a single component. [description] Keyword Arguments: id {[int]} -- [Component ID] (default: {None}) Returns: [Information about component(s)] -- [When successed] [Message] -- [When failed]",
"name": "get",
"signature": "def get(self)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_010967 | Implement the Python class `Component` described below.
Class description:
Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description o... | Implement the Python class `Component` described below.
Class description:
Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description o... | 052956e5006f7d274d19a43b061c2fe4a6456cc0 | <|skeleton|>
class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Component:
"""Using a create a component [description] Extends: db.Model Variables: __tablename__ {str} -- [table name in database] id {[int]} -- [the id of a component] name {[string(255)]} -- [the name of a component] description {[text]} -- [Description of the component] link {[text]} -- [A hyperlink to th... | the_stack_v2_python_sparse | models/components.py | BoTranVan/statuspage | train | 0 |
2b03cab14342456c315f7d33f4770c8fbd7a2767 | [
"self.log = logging.getLogger(__name__)\nself.name = name\nself.clouds = {}\nself.group_resources = group_resources\nself.group_yamls = group_yamls",
"base = automap_base()\nengine = create_engine('mysql+pymysql://' + csconfig.config.db_user + ':' + csconfig.config.db_password + '@' + csconfig.config.db_host + ':... | <|body_start_0|>
self.log = logging.getLogger(__name__)
self.name = name
self.clouds = {}
self.group_resources = group_resources
self.group_yamls = group_yamls
<|end_body_0|>
<|body_start_1|>
base = automap_base()
engine = create_engine('mysql+pymysql://' + cscon... | CloudManager class for holding a groups resources and their group yaml | CloudManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :para... | stack_v2_sparse_classes_36k_train_027307 | 2,414 | permissive | [
{
"docstring": "Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param group_yamls: the group's yaml from the database.",
"name": "__init__",
"signature": "def __init__(self, name, group_resources, group_yamls)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_006376 | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls): Create a new CloudManager. :param name: The name of the group :param group_re... | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls): Create a new CloudManager. :param name: The name of the group :param group_re... | 2d1aa488737046b6fefceb1bfaed72af2ac97758 | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param group_yamls... | the_stack_v2_python_sparse | cloudscheduler/cloudmanager.py | t-gibbons/cloudscheduler | train | 0 |
3312127a5ca9af17720696d0f5af8e7cc56b1034 | [
"res = []\n\ndef preOrder(root):\n if not root:\n res.append('#')\n else:\n res.append(str(root.val))\n preOrder(root.left)\n preOrder(root.right)\npreOrder(root)\nreturn ','.join(res)",
"def helper(l):\n if l[0] == '#':\n l.pop(0)\n return None\n root = TreeN... | <|body_start_0|>
res = []
def preOrder(root):
if not root:
res.append('#')
else:
res.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
preOrder(root)
return ','.join(res)
<|end_body_0|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def preOrder(root):
... | stack_v2_sparse_classes_36k_train_027308 | 1,827 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012840 | 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.
- def deserialize(self, data): Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string.
- def deserialize(self, data): Decodes your encoded data to tree.
<|skeleton|>
class Codec:
def serialize(self, root... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree."""
<|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."""
res = []
def preOrder(root):
if not root:
res.append('#')
else:
res.append(str(root.val))
preOrder(root.left)
preOrder(roo... | the_stack_v2_python_sparse | python/CodingInterviews_2/37_xu-lie-hua-er-cha-shu-lcof.py | Wang-Yann/LeetCodeMe | train | 0 | |
30f0bf9ea9e1102f441545bda407a19df9afa903 | [
"if os.path.isfile(file_path):\n self.file_path = file_path\nelse:\n raise OSError('file path provided does not have a file')\nif type(test_size) is float:\n self.test_size = test_size\nelse:\n self.test_size = 0.2",
"with open(self.file_path) as json_file:\n dictionary = json.load(json_file)\npath... | <|body_start_0|>
if os.path.isfile(file_path):
self.file_path = file_path
else:
raise OSError('file path provided does not have a file')
if type(test_size) is float:
self.test_size = test_size
else:
self.test_size = 0.2
<|end_body_0|>
<|bo... | Implementation of DataReader for the files containing all 278 features. | DataReader278Features | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testin... | stack_v2_sparse_classes_36k_train_027309 | 2,736 | no_license | [
{
"docstring": "Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testing.",
"name": "__init__",
"signature": "def __init__(self, file_path, test_size)"
},
{
"docstring": "Extracts 278 features from the specified f... | 2 | stack_v2_sparse_classes_30k_train_000169 | Implement the Python class `DataReader278Features` described below.
Class description:
Implementation of DataReader for the files containing all 278 features.
Method signatures and docstrings:
- def __init__(self, file_path, test_size): Init method :param file_path: file path containing a file of data. :param test_si... | Implement the Python class `DataReader278Features` described below.
Class description:
Implementation of DataReader for the files containing all 278 features.
Method signatures and docstrings:
- def __init__(self, file_path, test_size): Init method :param file_path: file path containing a file of data. :param test_si... | 9d751f6d6434fb9b418037cbaf928b0edd20a784 | <|skeleton|>
class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataReader278Features:
"""Implementation of DataReader for the files containing all 278 features."""
def __init__(self, file_path, test_size):
"""Init method :param file_path: file path containing a file of data. :param test_size (optional): fraction of the data to be used for testing."""
... | the_stack_v2_python_sparse | reco_code/datareader_278_features.py | martheveldhuis/ReCo | train | 1 |
719e8544956d8e51e84ce70a3cbc05afaf4aad40 | [
"assert real_disc == None or isinstance(real_disc, DependencyDiscriminatorSetup)\nself.real_disc = real_disc\nself.fake_disc = fake_disc",
"if self.real_disc != None:\n return lambda x: self.real_disc.D(self.real_disc.crop_func(x)) - self.fake_disc.D(self.fake_disc.crop_func(x))\nelse:\n return lambda x: -s... | <|body_start_0|>
assert real_disc == None or isinstance(real_disc, DependencyDiscriminatorSetup)
self.real_disc = real_disc
self.fake_disc = fake_disc
<|end_body_0|>
<|body_start_1|>
if self.real_disc != None:
return lambda x: self.real_disc.D(self.real_disc.crop_func(x)) - ... | DependencyDiscriminatorPair | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyDiscriminatorPair:
def __init__(self, real_disc, fake_disc: DependencyDiscriminatorSetup):
"""Binds to dependency discriminators (for p and q) together, to compute a combined output :param real_disc: p-dependency discriminator. Can be None in case none is used :param fake_disc:... | stack_v2_sparse_classes_36k_train_027310 | 6,967 | permissive | [
{
"docstring": "Binds to dependency discriminators (for p and q) together, to compute a combined output :param real_disc: p-dependency discriminator. Can be None in case none is used :param fake_disc: q-dependency discriminator",
"name": "__init__",
"signature": "def __init__(self, real_disc, fake_disc:... | 2 | stack_v2_sparse_classes_30k_train_010362 | Implement the Python class `DependencyDiscriminatorPair` described below.
Class description:
Implement the DependencyDiscriminatorPair class.
Method signatures and docstrings:
- def __init__(self, real_disc, fake_disc: DependencyDiscriminatorSetup): Binds to dependency discriminators (for p and q) together, to comput... | Implement the Python class `DependencyDiscriminatorPair` described below.
Class description:
Implement the DependencyDiscriminatorPair class.
Method signatures and docstrings:
- def __init__(self, real_disc, fake_disc: DependencyDiscriminatorSetup): Binds to dependency discriminators (for p and q) together, to comput... | 77f3ecd5e5964b7d8ab31886d7fe20fa9a4fe084 | <|skeleton|>
class DependencyDiscriminatorPair:
def __init__(self, real_disc, fake_disc: DependencyDiscriminatorSetup):
"""Binds to dependency discriminators (for p and q) together, to compute a combined output :param real_disc: p-dependency discriminator. Can be None in case none is used :param fake_disc:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DependencyDiscriminatorPair:
def __init__(self, real_disc, fake_disc: DependencyDiscriminatorSetup):
"""Binds to dependency discriminators (for p and q) together, to compute a combined output :param real_disc: p-dependency discriminator. Can be None in case none is used :param fake_disc: q-dependency ... | the_stack_v2_python_sparse | FactorGAN/training/DiscriminatorTraining.py | kalai2033/thesis_steel_type_plate_recognition | train | 1 | |
0deb4a04d861fc1870ece654676dd7fe66de58e4 | [
"super().__init__()\nmethod = method.lower()\nif method not in SCIPY_METHODS:\n raise ValueError('Method type must be a scipy.optimize method type, one of {}'.format(SCIPY_METHODS))\nself.method = method\nself.options = options\nself.fd_options = fd_options\nself.hessian_type = None",
"def fun_wrapper(x):\n ... | <|body_start_0|>
super().__init__()
method = method.lower()
if method not in SCIPY_METHODS:
raise ValueError('Method type must be a scipy.optimize method type, one of {}'.format(SCIPY_METHODS))
self.method = method
self.options = options
self.fd_options = fd_o... | Wrapper around scipy.optimize.minimize to conform to the format we require. | ScipyOptimiser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyOptimiser:
"""Wrapper around scipy.optimize.minimize to conform to the format we require."""
def __init__(self, method: str, options=None, fd_options=None):
"""Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-bfgs-b', 'tnc', 'newton-cg', 'dogleg', 'trust-ncg', 'trus... | stack_v2_sparse_classes_36k_train_027311 | 11,381 | no_license | [
{
"docstring": "Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-bfgs-b', 'tnc', 'newton-cg', 'dogleg', 'trust-ncg', 'trust-krylov' } or other scipy optimize valid flags options : fd_options :",
"name": "__init__",
"signature": "def __init__(self, method: str, options=None, fd_options=None)... | 2 | stack_v2_sparse_classes_30k_train_014708 | Implement the Python class `ScipyOptimiser` described below.
Class description:
Wrapper around scipy.optimize.minimize to conform to the format we require.
Method signatures and docstrings:
- def __init__(self, method: str, options=None, fd_options=None): Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-... | Implement the Python class `ScipyOptimiser` described below.
Class description:
Wrapper around scipy.optimize.minimize to conform to the format we require.
Method signatures and docstrings:
- def __init__(self, method: str, options=None, fd_options=None): Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-... | bcb5a6e626d14339abb6f77d32464f8a6de28e00 | <|skeleton|>
class ScipyOptimiser:
"""Wrapper around scipy.optimize.minimize to conform to the format we require."""
def __init__(self, method: str, options=None, fd_options=None):
"""Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-bfgs-b', 'tnc', 'newton-cg', 'dogleg', 'trust-ncg', 'trus... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScipyOptimiser:
"""Wrapper around scipy.optimize.minimize to conform to the format we require."""
def __init__(self, method: str, options=None, fd_options=None):
"""Parameters ---------- method : {'cg', 'bfgs', 'newton-cg', 'l-bfgs-b', 'tnc', 'newton-cg', 'dogleg', 'trust-ncg', 'trust-krylov' } o... | the_stack_v2_python_sparse | src/recursiveRouteChoice/optimisers/optimisers_file.py | chesterharvey/RecursiveRouteChoice | train | 0 |
975b7e1ceab517f360ded2b94b7fc93ad2a90d5a | [
"networks = []\nfor _ in range(no_of_stns):\n num = int(random() * max_no_of_nodes + 1)\n num = max(3, num)\n network = self.random_stn(num, max_weight, min_weight)\n networks.append(network)\n self.write_stn(network, _)\nreturn networks",
"network = STN()\nnetwork.length = no_of_nodes\nif not node... | <|body_start_0|>
networks = []
for _ in range(no_of_stns):
num = int(random() * max_no_of_nodes + 1)
num = max(3, num)
network = self.random_stn(num, max_weight, min_weight)
networks.append(network)
self.write_stn(network, _)
return net... | RandomSTN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSTN:
def random_stns(self, no_of_stns, max_no_of_nodes, max_weight=100, min_weight=-100):
"""random_stns: Generates and writes to files as many STNs as the user wants. ------------------------------------------------------------- INPUTS: no_of_stns: An integer representing the numb... | stack_v2_sparse_classes_36k_train_027312 | 6,465 | no_license | [
{
"docstring": "random_stns: Generates and writes to files as many STNs as the user wants. ------------------------------------------------------------- INPUTS: no_of_stns: An integer representing the number of STNs to be generated max_no_of_nodes: An integer representing the max no of nodes a STN generated can... | 4 | stack_v2_sparse_classes_30k_train_017446 | Implement the Python class `RandomSTN` described below.
Class description:
Implement the RandomSTN class.
Method signatures and docstrings:
- def random_stns(self, no_of_stns, max_no_of_nodes, max_weight=100, min_weight=-100): random_stns: Generates and writes to files as many STNs as the user wants. ----------------... | Implement the Python class `RandomSTN` described below.
Class description:
Implement the RandomSTN class.
Method signatures and docstrings:
- def random_stns(self, no_of_stns, max_no_of_nodes, max_weight=100, min_weight=-100): random_stns: Generates and writes to files as many STNs as the user wants. ----------------... | 596d35ecd303717292b89612501a24082f8017a2 | <|skeleton|>
class RandomSTN:
def random_stns(self, no_of_stns, max_no_of_nodes, max_weight=100, min_weight=-100):
"""random_stns: Generates and writes to files as many STNs as the user wants. ------------------------------------------------------------- INPUTS: no_of_stns: An integer representing the numb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomSTN:
def random_stns(self, no_of_stns, max_no_of_nodes, max_weight=100, min_weight=-100):
"""random_stns: Generates and writes to files as many STNs as the user wants. ------------------------------------------------------------- INPUTS: no_of_stns: An integer representing the number of STNs to ... | the_stack_v2_python_sparse | src/random_stn.py | JKBehrens/temporal-networks | train | 0 | |
75a72f3c4620e35791b30f21c7947145cf108eee | [
"super(lstm_decoder, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)\nself.linear = nn.Linear(hidden_size, input_size)",
"lstm_out, self.hidden = self.lstm(x_inp... | <|body_start_0|>
super(lstm_decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)
self.linear = nn.Linear(hidden_size, i... | Decodes hidden state output by encoder | lstm_decoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent... | stack_v2_sparse_classes_36k_train_027313 | 30,872 | permissive | [
{
"docstring": ": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent layers (i.e., 2 means there are : 2 stacked LSTMs)",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden... | 2 | stack_v2_sparse_classes_30k_train_013764 | Implement the Python class `lstm_decoder` described below.
Class description:
Decodes hidden state output by encoder
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers=1): : param input_size: the number of features in the input X : param hidden_size: the number of features in t... | Implement the Python class `lstm_decoder` described below.
Class description:
Decodes hidden state output by encoder
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers=1): : param input_size: the number of features in the input X : param hidden_size: the number of features in t... | b047384acff7b6a8399e839a9fa7053f548ff271 | <|skeleton|>
class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent layers (i.e.... | the_stack_v2_python_sparse | demo/Emotion/em_network/models/model.py | szgtvt/OpenRadar | train | 0 |
35fa73aa6434485e430eba2f1f5468356314b98d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ItemReference()",
"from .sharepoint_ids import SharepointIds\nfrom .sharepoint_ids import SharepointIds\nfields: Dict[str, Callable[[Any], None]] = {'driveId': lambda n: setattr(self, 'drive_id', n.get_str_value()), 'driveType': lambda... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ItemReference()
<|end_body_0|>
<|body_start_1|>
from .sharepoint_ids import SharepointIds
from .sharepoint_ids import SharepointIds
fields: Dict[str, Callable[[Any], None]] = {'d... | ItemReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemReference:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemReference:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_027314 | 4,807 | 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: ItemReference",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `ItemReference` described below.
Class description:
Implement the ItemReference class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemReference: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ItemReference` described below.
Class description:
Implement the ItemReference class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemReference: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ItemReference:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemReference:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemReference:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ItemReference:
"""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: ItemReferenc... | the_stack_v2_python_sparse | msgraph/generated/models/item_reference.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
72a240814eec6cb600d0741e13804b33bd0e985e | [
"self._height = 0\nself._head = SkipList._Node(None)\nself._len = 0\nfor elem in iterable:\n self.add(elem)",
"width = 5\nreps = []\ncurs = []\ncur = self._head\nwhile cur is not None:\n curs.append(cur)\n reps.append('')\n cur = cur.below\nlowest = curs[-1]\nwhile lowest is not None:\n for i in ra... | <|body_start_0|>
self._height = 0
self._head = SkipList._Node(None)
self._len = 0
for elem in iterable:
self.add(elem)
<|end_body_0|>
<|body_start_1|>
width = 5
reps = []
curs = []
cur = self._head
while cur is not None:
cu... | SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights. | SkipList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkipList:
"""SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights."""
def __init__(self, iterable=[]... | stack_v2_sparse_classes_36k_train_027315 | 4,921 | no_license | [
{
"docstring": "Create a new (empty) skip list",
"name": "__init__",
"signature": "def __init__(self, iterable=[])"
},
{
"docstring": "Returns a formatted textual representation of the list",
"name": "viz",
"signature": "def viz(self)"
},
{
"docstring": "Insert a value into the s... | 6 | stack_v2_sparse_classes_30k_train_001538 | Implement the Python class `SkipList` described below.
Class description:
SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights.... | Implement the Python class `SkipList` described below.
Class description:
SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights.... | 3cf95f6974e47f1e21bfa1ca2ad8c4d16093ab70 | <|skeleton|>
class SkipList:
"""SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights."""
def __init__(self, iterable=[]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkipList:
"""SortedSet ADT implemented using a skip list. Maintains elements in standard sorted order. Single-level nodes with next and below pointers. Uses sentinel values at the beginning of the skip list. Uses "coin tosses" to determine insertion heights."""
def __init__(self, iterable=[]):
""... | the_stack_v2_python_sparse | data_structures/skiplist.py | balta2ar/scratchpad | train | 1 |
6fa95a33461a3efdc1152bb02dc9d1bea445a45f | [
"if not root:\n return ''\nq, s = (deque([root]), [root.val])\nwhile q:\n n = q.popleft()\n if n.left:\n q.append(n.left)\n s += [n.left.val]\n else:\n s += [None]\n if n.right:\n q.append(n.right)\n s += [n.right.val]\n else:\n s += [None]\nreturn s",
"... | <|body_start_0|>
if not root:
return ''
q, s = (deque([root]), [root.val])
while q:
n = q.popleft()
if n.left:
q.append(n.left)
s += [n.left.val]
else:
s += [None]
if n.right:
... | 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_027316 | 1,636 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 36d7f9e967a62db77622e0888f61999d7f37579a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
q, s = (deque([root]), [root.val])
while q:
n = q.popleft()
if n.left:
q.append(n.left)
... | the_stack_v2_python_sparse | P0449.py | westgate458/LeetCode | train | 0 | |
e1d49ea64349dc6c627cfde00cdc92aa9e0194d0 | [
"rows = table.find_all('tr')[1:]\npolls = []\nfor row in rows:\n columns = [tag.text for tag in row.find_all('td')]\n poll, time_stamp, sample, biden, sanders, gabbard, spread = columns\n start, end = [d.split('/') for d in time_stamp.split('-')]\n start = date(year=YEAR, month=int(start[0]), day=int(st... | <|body_start_0|>
rows = table.find_all('tr')[1:]
polls = []
for row in rows:
columns = [tag.text for tag in row.find_all('td')]
poll, time_stamp, sample, biden, sanders, gabbard, spread = columns
start, end = [d.split('/') for d in time_stamp.split('-')]
... | RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table elements and returns the first one that it fin... | RealClearPolitics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table e... | stack_v2_sparse_classes_36k_train_027317 | 14,220 | no_license | [
{
"docstring": "Parses the row data from the html table. Arguments: table {Soup} -- Parses a BeautifulSoup table element and returns the text found in the td elements as Poll namedtuples. Returns: List[Poll] -- List of Poll namedtuples that were created from the table data.",
"name": "parse_rows",
"sign... | 3 | null | Implement the Python class `RealClearPolitics` described below.
Class description:
RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> s... | Implement the Python class `RealClearPolitics` described below.
Class description:
RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> s... | 9f839af4ef400786b7c28701c2241f310bb4422c | <|skeleton|>
class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RealClearPolitics:
"""RealClearPolitics object. RealClearPolitics is a custom class to parse a Web instance from the realclearpolitics website. Variables: web: Web -- The web object stores the information needed to process the data. Methods: find_table: -> str -- Parses the Web object for table elements and r... | the_stack_v2_python_sparse | 266/composition.py | StefanKaeser/pybites | train | 0 |
e41c56242a13cc8d07b059945cc126df3179ef52 | [
"self.position = position\nself.num_trials = num_trials\nself.position_value = 1000 / position",
"cumu_ret = np.zeros(self.num_trials)\ndaily_ret = np.zeros(self.num_trials)\nfor trial in range(self.num_trials):\n invest_rate = np.random.uniform(0, 1, size=self.position)\n for p in range(self.position):\n ... | <|body_start_0|>
self.position = position
self.num_trials = num_trials
self.position_value = 1000 / position
<|end_body_0|>
<|body_start_1|>
cumu_ret = np.zeros(self.num_trials)
daily_ret = np.zeros(self.num_trials)
for trial in range(self.num_trials):
invest... | classdocs | investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment:
"""classdocs"""
def __init__(self, position, num_trials):
"""Constructor"""
<|body_0|>
def simulate(self):
"""simulate the investment"""
<|body_1|>
def output_histogram(self):
"""draw histogram"""
<|body_2|>
def print... | stack_v2_sparse_classes_36k_train_027318 | 1,808 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, position, num_trials)"
},
{
"docstring": "simulate the investment",
"name": "simulate",
"signature": "def simulate(self)"
},
{
"docstring": "draw histogram",
"name": "output_histogram",
"si... | 4 | null | Implement the Python class `investment` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, position, num_trials): Constructor
- def simulate(self): simulate the investment
- def output_histogram(self): draw histogram
- def print_result(self): write the result into fil... | Implement the Python class `investment` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, position, num_trials): Constructor
- def simulate(self): simulate the investment
- def output_histogram(self): draw histogram
- def print_result(self): write the result into fil... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment:
"""classdocs"""
def __init__(self, position, num_trials):
"""Constructor"""
<|body_0|>
def simulate(self):
"""simulate the investment"""
<|body_1|>
def output_histogram(self):
"""draw histogram"""
<|body_2|>
def print... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class investment:
"""classdocs"""
def __init__(self, position, num_trials):
"""Constructor"""
self.position = position
self.num_trials = num_trials
self.position_value = 1000 / position
def simulate(self):
"""simulate the investment"""
cumu_ret = np.zeros(se... | the_stack_v2_python_sparse | ys1700/my_package/investment.py | ds-ga-1007/assignment8 | train | 1 |
b7aa8e73f6ca0ebd66b658cc77d890a7948c9b56 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ToneInfo()",
"from .tone import Tone\nfrom .tone import Tone\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', n.get_str_value()), 'sequenceId': lambda n: setattr(self, 'sequence_id', n.g... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ToneInfo()
<|end_body_0|>
<|body_start_1|>
from .tone import Tone
from .tone import Tone
fields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata... | ToneInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""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: ToneInfo... | stack_v2_sparse_classes_36k_train_027319 | 2,754 | 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: ToneInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pars... | 3 | null | Implement the Python class `ToneInfo` described below.
Class description:
Implement the ToneInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | Implement the Python class `ToneInfo` described below.
Class description:
Implement the ToneInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo: Creates a new instance of the appropriate class based on discriminator value Args: parse_no... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""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: ToneInfo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToneInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ToneInfo:
"""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: ToneInfo"""
if... | the_stack_v2_python_sparse | msgraph/generated/models/tone_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b94392c9c6547415326d80ff0923cb8ba9251783 | [
"s = ''\nfor i in strs:\n s += str(len(i)) + '#' + i\nreturn s",
"i, str = (0, [])\nwhile i < len(s):\n sharp = s.find('#', i)\n l = int(s[i:sharp])\n str.append(s[sharp + 1:sharp + l + 1])\n i = sharp + l + 1\nreturn str"
] | <|body_start_0|>
s = ''
for i in strs:
s += str(len(i)) + '#' + i
return s
<|end_body_0|>
<|body_start_1|>
i, str = (0, [])
while i < len(s):
sharp = s.find('#', i)
l = int(s[i:sharp])
str.append(s[sharp + 1:sharp + l + 1])
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_027320 | 2,992 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_016949 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 05e8f5a4e39d448eb333c813093fc7c1df4fc05e | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
s = ''
for i in strs:
s += str(len(i)) + '#' + i
return s
def decode(self, s):
"""Decodes a single string to a list of strings. :type s:... | the_stack_v2_python_sparse | leetcode_python/String/encode-and-decode-strings.py | DataEngDev/CS_basics | train | 0 | |
c33b5be39314f70677e6db819510013647a2d1be | [
"self._attr_name = name\nself.hemisphere = hemisphere\nself.type = season_tracking_type",
"self._attr_native_value = get_season(utcnow().replace(tzinfo=None), self.hemisphere, self.type)\nself._attr_icon = 'mdi:cloud'\nif self._attr_native_value:\n self._attr_icon = SEASON_ICONS[self._attr_native_value]"
] | <|body_start_0|>
self._attr_name = name
self.hemisphere = hemisphere
self.type = season_tracking_type
<|end_body_0|>
<|body_start_1|>
self._attr_native_value = get_season(utcnow().replace(tzinfo=None), self.hemisphere, self.type)
self._attr_icon = 'mdi:cloud'
if self._at... | Representation of the current season. | Season | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Season:
"""Representation of the current season."""
def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None:
"""Initialize the season."""
<|body_0|>
def update(self) -> None:
"""Update season."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_027321 | 4,050 | permissive | [
{
"docstring": "Initialize the season.",
"name": "__init__",
"signature": "def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None"
},
{
"docstring": "Update season.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_011844 | Implement the Python class `Season` described below.
Class description:
Representation of the current season.
Method signatures and docstrings:
- def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None: Initialize the season.
- def update(self) -> None: Update season. | Implement the Python class `Season` described below.
Class description:
Representation of the current season.
Method signatures and docstrings:
- def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None: Initialize the season.
- def update(self) -> None: Update season.
<|skeleton|>
class Sea... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class Season:
"""Representation of the current season."""
def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None:
"""Initialize the season."""
<|body_0|>
def update(self) -> None:
"""Update season."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Season:
"""Representation of the current season."""
def __init__(self, hemisphere: str, season_tracking_type: str, name: str) -> None:
"""Initialize the season."""
self._attr_name = name
self.hemisphere = hemisphere
self.type = season_tracking_type
def update(self) ->... | the_stack_v2_python_sparse | homeassistant/components/season/sensor.py | JeffLIrion/home-assistant | train | 5 |
604fcba8f4e0f31a6e886eb7057ad28af3513ecd | [
"self.capacity = capacity\nself.hash_map = {}\nself.frequency_map = collections.defaultdict(list)",
"hash_result = self.hash_map.get(key)\nif hash_result:\n value, frequency = hash_result\n self.hash_map[key] = (frequency + 1, value)\n self.frequency_map[frequency + 1].append(key)\n return value\nelse... | <|body_start_0|>
self.capacity = capacity
self.hash_map = {}
self.frequency_map = collections.defaultdict(list)
<|end_body_0|>
<|body_start_1|>
hash_result = self.hash_map.get(key)
if hash_result:
value, frequency = hash_result
self.hash_map[key] = (frequ... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
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_027322 | 1,703 | 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 `LFUCache` described below.
Class description:
Implement the LFUCache 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 `LFUCache` described below.
Class description:
Implement the LFUCache 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... | 057ed5c6fe19268f36a1d5051d27b07aae0b63e0 | <|skeleton|>
class LFUCache:
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 LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.hash_map = {}
self.frequency_map = collections.defaultdict(list)
def get(self, key):
""":type key: int :rtype: int"""
hash_result = self.hash_map.get(key)
... | the_stack_v2_python_sparse | 2020/2020-03/12/eugene.py | wavetogether/wave_algorithm_challenge | train | 3 | |
1597e41cbcb69b1f14689b6c93b54474a2b9f7b6 | [
"enrollment_status_map = {}\nfor enrollment in enrollments:\n course_title = enrollment.course_run.course.title\n is_verified = mmtrack.is_enrolled_mmtrack(enrollment.course_run.edx_course_key)\n enrollment_status_map[course_title] = enrollment_status_map.get(course_title) or is_verified\nserialized_enroll... | <|body_start_0|>
enrollment_status_map = {}
for enrollment in enrollments:
course_title = enrollment.course_run.course.title
is_verified = mmtrack.is_enrolled_mmtrack(enrollment.course_run.edx_course_key)
enrollment_status_map[course_title] = enrollment_status_map.get... | Provides functions for serializing a ProgramEnrollment for the ES index | UserProgramSearchSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack, enrollments):
"""Serializes a user's enrollment data for search results Args: mmtrack (MMTrack): An MMTrack object enrollments (iterable)... | stack_v2_sparse_classes_36k_train_027323 | 2,496 | no_license | [
{
"docstring": "Serializes a user's enrollment data for search results Args: mmtrack (MMTrack): An MMTrack object enrollments (iterable): An iterable of CachedEnrollments Returns: list: Serialized courses",
"name": "serialize_enrollments",
"signature": "def serialize_enrollments(cls, mmtrack, enrollment... | 2 | stack_v2_sparse_classes_30k_train_015289 | Implement the Python class `UserProgramSearchSerializer` described below.
Class description:
Provides functions for serializing a ProgramEnrollment for the ES index
Method signatures and docstrings:
- def serialize_enrollments(cls, mmtrack, enrollments): Serializes a user's enrollment data for search results Args: mm... | Implement the Python class `UserProgramSearchSerializer` described below.
Class description:
Provides functions for serializing a ProgramEnrollment for the ES index
Method signatures and docstrings:
- def serialize_enrollments(cls, mmtrack, enrollments): Serializes a user's enrollment data for search results Args: mm... | 3c166bc52dfe8d7aa04f922134f4f6deeff49eb6 | <|skeleton|>
class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack, enrollments):
"""Serializes a user's enrollment data for search results Args: mmtrack (MMTrack): An MMTrack object enrollments (iterable)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack, enrollments):
"""Serializes a user's enrollment data for search results Args: mmtrack (MMTrack): An MMTrack object enrollments (iterable): An iterable... | the_stack_v2_python_sparse | dashboard/serializers.py | avontd2868/micromasters | train | 0 |
7abfffeea14f8a0680006361234a41fe8878fb69 | [
"super().__init__(dataset, collate_fn=self.collate, **kwargs)\nself.source_pad_id = source_pad_id\nself.target_pad_id = target_pad_id\nself.batch_first = batch_first",
"src_batch, trg_batch = zip(*batch)\nsrc_lens = torch.tensor([src_seq.size()[0] for src_seq in src_batch])\ntrg_lens = torch.tensor([trg_seq.size(... | <|body_start_0|>
super().__init__(dataset, collate_fn=self.collate, **kwargs)
self.source_pad_id = source_pad_id
self.target_pad_id = target_pad_id
self.batch_first = batch_first
<|end_body_0|>
<|body_start_1|>
src_batch, trg_batch = zip(*batch)
src_lens = torch.tensor([... | Seq2SeqDataLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2SeqDataLoader:
def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs):
"""Loads the dataset for the model It can load the dataset in parallel by setting 'num_workers' param > 0 Parameters ---------- dataset : Seq2SeqDataset The parallel text dataset so... | stack_v2_sparse_classes_36k_train_027324 | 7,192 | permissive | [
{
"docstring": "Loads the dataset for the model It can load the dataset in parallel by setting 'num_workers' param > 0 Parameters ---------- dataset : Seq2SeqDataset The parallel text dataset source_pad_id : int An ID used to pad the source text for batching target_pad_id : int An ID used to pad the target text... | 2 | stack_v2_sparse_classes_30k_train_016983 | Implement the Python class `Seq2SeqDataLoader` described below.
Class description:
Implement the Seq2SeqDataLoader class.
Method signatures and docstrings:
- def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs): Loads the dataset for the model It can load the dataset in parallel by s... | Implement the Python class `Seq2SeqDataLoader` described below.
Class description:
Implement the Seq2SeqDataLoader class.
Method signatures and docstrings:
- def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs): Loads the dataset for the model It can load the dataset in parallel by s... | da9cecce49498c4f79946a631206985f99daaed3 | <|skeleton|>
class Seq2SeqDataLoader:
def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs):
"""Loads the dataset for the model It can load the dataset in parallel by setting 'num_workers' param > 0 Parameters ---------- dataset : Seq2SeqDataset The parallel text dataset so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seq2SeqDataLoader:
def __init__(self, dataset, source_pad_id, target_pad_id, batch_first=False, **kwargs):
"""Loads the dataset for the model It can load the dataset in parallel by setting 'num_workers' param > 0 Parameters ---------- dataset : Seq2SeqDataset The parallel text dataset source_pad_id : ... | the_stack_v2_python_sparse | Translator/src/dataloader/datasets.py | add54/Translator | train | 0 | |
a884069358944d4668db51cea60c58b2f26deb35 | [
"self.gateway = gateway\nself.ip_cidr = ip_cidr\nself.ips = ips\nself.netmask_bits = netmask_bits\nself.netmask_ip_4 = netmask_ip_4",
"if dictionary is None:\n return None\ngateway = dictionary.get('gateway')\nip_cidr = dictionary.get('ipCidr')\nips = dictionary.get('ips')\nnetmask_bits = dictionary.get('netma... | <|body_start_0|>
self.gateway = gateway
self.ip_cidr = ip_cidr
self.ips = ips
self.netmask_bits = netmask_bits
self.netmask_ip_4 = netmask_ip_4
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
gateway = dictionary.get('gateway')
... | Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cidr (string): Specifies either an IPv6 address or an IPv4 address. ips (list of st... | BifrostSubnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BifrostSubnet:
"""Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cidr (string): Specifies either an IPv6 ad... | stack_v2_sparse_classes_36k_train_027325 | 2,475 | permissive | [
{
"docstring": "Constructor for the BifrostSubnet class",
"name": "__init__",
"signature": "def __init__(self, gateway=None, ip_cidr=None, ips=None, netmask_bits=None, netmask_ip_4=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dict... | 2 | stack_v2_sparse_classes_30k_val_000598 | Implement the Python class `BifrostSubnet` described below.
Class description:
Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cid... | Implement the Python class `BifrostSubnet` described below.
Class description:
Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cid... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BifrostSubnet:
"""Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cidr (string): Specifies either an IPv6 ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BifrostSubnet:
"""Implementation of the 'BifrostSubnet' model. Specifies the settings of a Bifrost Subnet. Attributes: gateway (string): Specifies the Gateway of the VLAN. It can carry V4 or V6 in case of requests, and carrises V4 in case of response. ip_cidr (string): Specifies either an IPv6 address or an I... | the_stack_v2_python_sparse | cohesity_management_sdk/models/bifrost_subnet.py | cohesity/management-sdk-python | train | 24 |
6f0b4af700568c9ccd54438fe853278c6f5f5552 | [
"if value is None:\n value = ''\nelif hasattr(value, 'to_json'):\n value = json.dumps(value.to_json())\nfinal_attrs = self.build_attrs(attrs, name=name)\nreturn \"\\n <div id='tempo-{uuid}-controls' class='tempo-controls'>\\n <input id='tempo-{uuid}-create' type='button' value='Create' />\\n... | <|body_start_0|>
if value is None:
value = ''
elif hasattr(value, 'to_json'):
value = json.dumps(value.to_json())
final_attrs = self.build_attrs(attrs, name=name)
return "\n <div id='tempo-{uuid}-controls' class='tempo-controls'>\n <input id='tem... | Django-Admin widget, that represents RecurrentEventSet. | RecurrentEventSetWidget | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Retrieves da... | stack_v2_sparse_classes_36k_train_027326 | 2,683 | permissive | [
{
"docstring": "Renders HTML representation and needed JavaScript.",
"name": "render",
"signature": "def render(self, name, value, attrs=None)"
},
{
"docstring": "Retrieves data, from HTML representation.",
"name": "value_from_datadict",
"signature": "def value_from_datadict(self, data, ... | 2 | stack_v2_sparse_classes_30k_train_003988 | Implement the Python class `RecurrentEventSetWidget` described below.
Class description:
Django-Admin widget, that represents RecurrentEventSet.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Renders HTML representation and needed JavaScript.
- def value_from_datadict(self, data, files... | Implement the Python class `RecurrentEventSetWidget` described below.
Class description:
Django-Admin widget, that represents RecurrentEventSet.
Method signatures and docstrings:
- def render(self, name, value, attrs=None): Renders HTML representation and needed JavaScript.
- def value_from_datadict(self, data, files... | 36e600581059d27d36bd2b922acb9c403010ebc6 | <|skeleton|>
class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
<|body_0|>
def value_from_datadict(self, data, files, name):
"""Retrieves da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurrentEventSetWidget:
"""Django-Admin widget, that represents RecurrentEventSet."""
def render(self, name, value, attrs=None):
"""Renders HTML representation and needed JavaScript."""
if value is None:
value = ''
elif hasattr(value, 'to_json'):
value = j... | the_stack_v2_python_sparse | src/tempo/django/widgets.py | AndreiPashkin/python-tempo | train | 3 |
0e89a2684ef98653de2e0f7f4b0e4d05b0820f3e | [
"super().__init__()\nif ignore_label is not None:\n ce_kwargs['ignore_index'] = ignore_label\nself.weight_dice = weight_dice\nself.weight_ce = weight_ce\nself.ignore_label = ignore_label\nself.ce = TopKLoss(**ce_kwargs)\nself.dc = SoftDiceLoss(apply_nonlin=softmax_helper_dim1, **soft_dice_kwargs)",
"if self.ig... | <|body_start_0|>
super().__init__()
if ignore_label is not None:
ce_kwargs['ignore_index'] = ignore_label
self.weight_dice = weight_dice
self.weight_ce = weight_ce
self.ignore_label = ignore_label
self.ce = TopKLoss(**ce_kwargs)
self.dc = SoftDiceLoss(... | DC_and_topk_loss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DC_and_topk_loss:
def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None):
"""Weights for CE and Dice do not need to sum to one. You can set whatever you want. :param soft_dice_kwargs: :param ce_kwargs: :param aggregate: :param square_dice: :param w... | stack_v2_sparse_classes_36k_train_027327 | 5,988 | permissive | [
{
"docstring": "Weights for CE and Dice do not need to sum to one. You can set whatever you want. :param soft_dice_kwargs: :param ce_kwargs: :param aggregate: :param square_dice: :param weight_ce: :param weight_dice:",
"name": "__init__",
"signature": "def __init__(self, soft_dice_kwargs, ce_kwargs, wei... | 2 | null | Implement the Python class `DC_and_topk_loss` described below.
Class description:
Implement the DC_and_topk_loss class.
Method signatures and docstrings:
- def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None): Weights for CE and Dice do not need to sum to one. You can set wha... | Implement the Python class `DC_and_topk_loss` described below.
Class description:
Implement the DC_and_topk_loss class.
Method signatures and docstrings:
- def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None): Weights for CE and Dice do not need to sum to one. You can set wha... | b4e97fe38a9eb6728077678d4850c41570a1cb02 | <|skeleton|>
class DC_and_topk_loss:
def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None):
"""Weights for CE and Dice do not need to sum to one. You can set whatever you want. :param soft_dice_kwargs: :param ce_kwargs: :param aggregate: :param square_dice: :param w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DC_and_topk_loss:
def __init__(self, soft_dice_kwargs, ce_kwargs, weight_ce=1, weight_dice=1, ignore_label=None):
"""Weights for CE and Dice do not need to sum to one. You can set whatever you want. :param soft_dice_kwargs: :param ce_kwargs: :param aggregate: :param square_dice: :param weight_ce: :par... | the_stack_v2_python_sparse | nnunetv2/training/loss/compound_losses.py | MIC-DKFZ/nnUNet | train | 4,219 | |
d1fb5f84538822f6219b18608e3ece32372eef08 | [
"super().__init__(max_n_sources)\nself.min_distance = min_distance\nself.threshold_scale = threshold_scale\nif use_band is None and (not use_mean):\n raise ValueError(\"Either set 'use_mean=True' OR indicate a 'use_band' index\")\nif use_band is not None and use_mean:\n raise ValueError(\"Only one of the para... | <|body_start_0|>
super().__init__(max_n_sources)
self.min_distance = min_distance
self.threshold_scale = threshold_scale
if use_band is None and (not use_mean):
raise ValueError("Either set 'use_mean=True' OR indicate a 'use_band' index")
if use_band is not None and u... | This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the average of all the bands. | PeakLocalMax | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeakLocalMax:
"""This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the average of all the bands."""
def __init... | stack_v2_sparse_classes_36k_train_027328 | 24,907 | permissive | [
{
"docstring": "Initializes measurement class. Exactly one of 'use_mean' or 'use_band' must be specified. Args: max_n_sources: See parent class. threshold_scale: Minimum intensity of peaks. min_distance: Minimum distance in pixels between two peaks. use_mean: Flag to use the band average for the measurement. us... | 2 | stack_v2_sparse_classes_30k_train_013332 | Implement the Python class `PeakLocalMax` described below.
Class description:
This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the avera... | Implement the Python class `PeakLocalMax` described below.
Class description:
This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the avera... | f5b716a373f130238100db8980aa0d282822983a | <|skeleton|>
class PeakLocalMax:
"""This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the average of all the bands."""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeakLocalMax:
"""This class detects centroids with `skimage.feature.peak_local_max`. The function performs detection and deblending of the sources based on the provided band index. If use_mean feature is used, then the measurement function is using the average of all the bands."""
def __init__(self, max_... | the_stack_v2_python_sparse | btk/deblend.py | LSSTDESC/BlendingToolKit | train | 22 |
a8956c6aa972fc14b6b6f6c51bfd00d7af6d708a | [
"self.generic = config.get('generic', False)\nwrap = config.get('tex_inline_wrap', ['\\\\(', '\\\\)'])\nself.wrap = wrap[0] + '%s' + wrap[1]\nself.preview = config.get('preview', True)\nPattern.__init__(self, pattern)",
"if self.preview:\n el = md_util.etree.Element('span')\n preview = md_util.etree.SubElem... | <|body_start_0|>
self.generic = config.get('generic', False)
wrap = config.get('tex_inline_wrap', ['\\(', '\\)'])
self.wrap = wrap[0] + '%s' + wrap[1]
self.preview = config.get('preview', True)
Pattern.__init__(self, pattern)
<|end_body_0|>
<|body_start_1|>
if self.previ... | Arithmatex inline pattern handler. | InlineArithmatexPattern | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
<|body_0|>
def mathjax_output(self, math):
"""Default MathJax output."""
<|body_1|>
def generic_output(self, math):
"""Ge... | stack_v2_sparse_classes_36k_train_027329 | 9,236 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, pattern, config)"
},
{
"docstring": "Default MathJax output.",
"name": "mathjax_output",
"signature": "def mathjax_output(self, math)"
},
{
"docstring": "Generic output.",
"name": "generic_outp... | 4 | stack_v2_sparse_classes_30k_train_014173 | Implement the Python class `InlineArithmatexPattern` described below.
Class description:
Arithmatex inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config): Initialize.
- def mathjax_output(self, math): Default MathJax output.
- def generic_output(self, math): Generic output.
-... | Implement the Python class `InlineArithmatexPattern` described below.
Class description:
Arithmatex inline pattern handler.
Method signatures and docstrings:
- def __init__(self, pattern, config): Initialize.
- def mathjax_output(self, math): Default MathJax output.
- def generic_output(self, math): Generic output.
-... | 0e7796a61d4391ba51e3a9e21d3cdcd64a0ba8a4 | <|skeleton|>
class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
<|body_0|>
def mathjax_output(self, math):
"""Default MathJax output."""
<|body_1|>
def generic_output(self, math):
"""Ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InlineArithmatexPattern:
"""Arithmatex inline pattern handler."""
def __init__(self, pattern, config):
"""Initialize."""
self.generic = config.get('generic', False)
wrap = config.get('tex_inline_wrap', ['\\(', '\\)'])
self.wrap = wrap[0] + '%s' + wrap[1]
self.previ... | the_stack_v2_python_sparse | thirdparty/pymdownx/arithmatex.py | cxsjclassroom/webserver | train | 5 |
c2f5c2275fefe544786ff5cb8c5e467a62467ed8 | [
"errors = super(OfficialClubSerializer, self).validate(data, get_errors=True)\nvalidate_profanity_serializer(data, 'room', errors, field_name='Club room')\nraise_validation_errors(errors)\nclean_field(data, 'room')\nreturn data",
"meta = super(OfficialClubSerializer, self).get_meta(obj)\nmeta['is_valid'] = is_val... | <|body_start_0|>
errors = super(OfficialClubSerializer, self).validate(data, get_errors=True)
validate_profanity_serializer(data, 'room', errors, field_name='Club room')
raise_validation_errors(errors)
clean_field(data, 'room')
return data
<|end_body_0|>
<|body_start_1|>
... | Official club serializer | OfficialClubSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialClubSerializer:
"""Official club serializer"""
def validate(self, data, get_errors=False):
"""Validate data"""
<|body_0|>
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
errors = super(Offic... | stack_v2_sparse_classes_36k_train_027330 | 25,313 | permissive | [
{
"docstring": "Validate data",
"name": "validate",
"signature": "def validate(self, data, get_errors=False)"
},
{
"docstring": "Retrieve meta data",
"name": "get_meta",
"signature": "def get_meta(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010584 | Implement the Python class `OfficialClubSerializer` described below.
Class description:
Official club serializer
Method signatures and docstrings:
- def validate(self, data, get_errors=False): Validate data
- def get_meta(self, obj): Retrieve meta data | Implement the Python class `OfficialClubSerializer` described below.
Class description:
Official club serializer
Method signatures and docstrings:
- def validate(self, data, get_errors=False): Validate data
- def get_meta(self, obj): Retrieve meta data
<|skeleton|>
class OfficialClubSerializer:
"""Official club ... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class OfficialClubSerializer:
"""Official club serializer"""
def validate(self, data, get_errors=False):
"""Validate data"""
<|body_0|>
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialClubSerializer:
"""Official club serializer"""
def validate(self, data, get_errors=False):
"""Validate data"""
errors = super(OfficialClubSerializer, self).validate(data, get_errors=True)
validate_profanity_serializer(data, 'room', errors, field_name='Club room')
r... | the_stack_v2_python_sparse | community/serializers.py | 810Teams/clubs-and-events-backend | train | 3 |
ab78b870bd9a5feaad0bfb6e815e4d406863f31d | [
"sqlStr = \"\\nCREATE TABLE %s(\\n id INTEGER PRIMARY KEY AUTOINCREMENT,\\n event varchar(255) NOT NULL,\\n payload text NOT NULL,\\n state enum('queued','process') default 'queued',\\n ) \" % threadpool\nsqlString1 = '\\nCREA... | <|body_start_0|>
sqlStr = "\nCREATE TABLE %s(\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n event varchar(255) NOT NULL,\n payload text NOT NULL,\n state enum('queued','process') default 'queued',\n ) " % threadpool
sq... | _Queries_ This module implements the SQLite backend for the persistent threadpool. | Queries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queries:
"""_Queries_ This module implements the SQLite backend for the persistent threadpool."""
def insertThreadPoolTables(self, threadpool):
"""__insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) when multi queue is enabled. SQLite version"""
<|... | stack_v2_sparse_classes_36k_train_027331 | 3,815 | no_license | [
{
"docstring": "__insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) when multi queue is enabled. SQLite version",
"name": "insertThreadPoolTables",
"signature": "def insertThreadPoolTables(self, threadpool)"
},
{
"docstring": "_moveWorkToBufferOut_ Moves work from buf... | 3 | null | Implement the Python class `Queries` described below.
Class description:
_Queries_ This module implements the SQLite backend for the persistent threadpool.
Method signatures and docstrings:
- def insertThreadPoolTables(self, threadpool): __insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) ... | Implement the Python class `Queries` described below.
Class description:
_Queries_ This module implements the SQLite backend for the persistent threadpool.
Method signatures and docstrings:
- def insertThreadPoolTables(self, threadpool): __insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) ... | f4cb398de940560e40491ba676b704e1489d4682 | <|skeleton|>
class Queries:
"""_Queries_ This module implements the SQLite backend for the persistent threadpool."""
def insertThreadPoolTables(self, threadpool):
"""__insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) when multi queue is enabled. SQLite version"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queries:
"""_Queries_ This module implements the SQLite backend for the persistent threadpool."""
def insertThreadPoolTables(self, threadpool):
"""__insertThreadPoolTable Inserts tables for threadpool (one for each threadpool) when multi queue is enabled. SQLite version"""
sqlStr = "\nCRE... | the_stack_v2_python_sparse | src/python/WMCore/ThreadPool/SQLite/Queries.py | PerilousApricot/WMCore | train | 1 |
4f72c82577b47bb8b61cf2924d7eeb2685756292 | [
"article = get_object_or_404(Article, slug=slug)\nif article.author == self.request.user:\n raise PermissionDenied({'error': 'You cannot rate an article you created'})\nif Rating.objects.filter(reader=user.pk).filter(article=article.id).exists():\n raise ParseError({'error': 'You already rated this article'})... | <|body_start_0|>
article = get_object_or_404(Article, slug=slug)
if article.author == self.request.user:
raise PermissionDenied({'error': 'You cannot rate an article you created'})
if Rating.objects.filter(reader=user.pk).filter(article=article.id).exists():
raise ParseEr... | Class to handle the rating of articles | CreateRatingsView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_027332 | 17,142 | permissive | [
{
"docstring": "Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article",
"name": "get_queryset",
"signature": "def get_queryset(self, data, user, slug)"
},
{
"docstring": "Method that edit a rating... | 2 | null | Implement the Python class `CreateRatingsView` described below.
Class description:
Class to handle the rating of articles
Method signatures and docstrings:
- def get_queryset(self, data, user, slug): Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissio... | Implement the Python class `CreateRatingsView` described below.
Class description:
Class to handle the rating of articles
Method signatures and docstrings:
- def get_queryset(self, data, user, slug): Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissio... | cc84c18f7c222bc69cf4a263a1c2296b6d335c8b | <|skeleton|>
class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateRatingsView:
"""Class to handle the rating of articles"""
def get_queryset(self, data, user, slug):
"""Method to get the article slug and compare it with available slugs in the database. It shall also handle all permissions in relation to rating an article"""
article = get_object_or... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/Ah-backend-guardians | train | 0 |
2d43ee9133a47b53caef7d151d3fb3622d3d8ba1 | [
"self.date_to_use = datetime.datetime.now()\nself.car_name = 'car123'\nself.test_data = agentdata.DictionaryConstructor(self.car_name, self.date_to_use)\nself.action = 1\nself.username = 'uname'\nself.password = 'pword'\nself.usertoken = 'abc123'\nself.test_data.set_action(1)\nself.test_data.set_username(self.usern... | <|body_start_0|>
self.date_to_use = datetime.datetime.now()
self.car_name = 'car123'
self.test_data = agentdata.DictionaryConstructor(self.car_name, self.date_to_use)
self.action = 1
self.username = 'uname'
self.password = 'pword'
self.usertoken = 'abc123'
... | This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary. | TestAgentData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAgentData:
"""This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary."""
def setUp(self):
"""Set Data to be converted and validated."""
<|body_0|>
def test_data_integrity(self):
"""Tests the data returned... | stack_v2_sparse_classes_36k_train_027333 | 23,291 | no_license | [
{
"docstring": "Set Data to be converted and validated.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests the data returned.",
"name": "test_data_integrity",
"signature": "def test_data_integrity(self)"
},
{
"docstring": "Tests the conversion of dates for... | 3 | null | Implement the Python class `TestAgentData` described below.
Class description:
This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary.
Method signatures and docstrings:
- def setUp(self): Set Data to be converted and validated.
- def test_data_integrity(self): Te... | Implement the Python class `TestAgentData` described below.
Class description:
This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary.
Method signatures and docstrings:
- def setUp(self): Set Data to be converted and validated.
- def test_data_integrity(self): Te... | 8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf | <|skeleton|>
class TestAgentData:
"""This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary."""
def setUp(self):
"""Set Data to be converted and validated."""
<|body_0|>
def test_data_integrity(self):
"""Tests the data returned... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAgentData:
"""This class tests the :mod:`agentdata` module. .. warning:: Do not use helper functions to create a dictionary."""
def setUp(self):
"""Set Data to be converted and validated."""
self.date_to_use = datetime.datetime.now()
self.car_name = 'car123'
self.test_... | the_stack_v2_python_sparse | AgentPi/agenttesting.py | JiewenGuan/Iot-Carshare | train | 0 |
53e47d7e875f3f5abf9f1fac172be0bfdbda66eb | [
"allCards = self.getCardsToDeal(context)\nwhile len(allCards) > 0:\n for foe in context.foes:\n if len(allCards) > 0:\n zone = context.getPlayerContext(foe).loadZone(HAND)\n zone.add(allCards.pop())",
"allCards = []\neventZone = context.loadZone(EVENT)\nfor card in list(eventZone):... | <|body_start_0|>
allCards = self.getCardsToDeal(context)
while len(allCards) > 0:
for foe in context.foes:
if len(allCards) > 0:
zone = context.getPlayerContext(foe).loadZone(HAND)
zone.add(allCards.pop())
<|end_body_0|>
<|body_start_1... | Represents an effect to Shuffle Cards and Deal them to the foes | ShuffleAndDeal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShuffleAndDeal:
"""Represents an effect to Shuffle Cards and Deal them to the foes"""
def perform(self, context):
"""Perform the Game Effect"""
<|body_0|>
def getCardsToDeal(self, context):
"""Get the Cards to Deal to the Character"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_027334 | 869 | no_license | [
{
"docstring": "Perform the Game Effect",
"name": "perform",
"signature": "def perform(self, context)"
},
{
"docstring": "Get the Cards to Deal to the Character",
"name": "getCardsToDeal",
"signature": "def getCardsToDeal(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021003 | Implement the Python class `ShuffleAndDeal` described below.
Class description:
Represents an effect to Shuffle Cards and Deal them to the foes
Method signatures and docstrings:
- def perform(self, context): Perform the Game Effect
- def getCardsToDeal(self, context): Get the Cards to Deal to the Character | Implement the Python class `ShuffleAndDeal` described below.
Class description:
Represents an effect to Shuffle Cards and Deal them to the foes
Method signatures and docstrings:
- def perform(self, context): Perform the Game Effect
- def getCardsToDeal(self, context): Get the Cards to Deal to the Character
<|skeleto... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class ShuffleAndDeal:
"""Represents an effect to Shuffle Cards and Deal them to the foes"""
def perform(self, context):
"""Perform the Game Effect"""
<|body_0|>
def getCardsToDeal(self, context):
"""Get the Cards to Deal to the Character"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShuffleAndDeal:
"""Represents an effect to Shuffle Cards and Deal them to the foes"""
def perform(self, context):
"""Perform the Game Effect"""
allCards = self.getCardsToDeal(context)
while len(allCards) > 0:
for foe in context.foes:
if len(allCards) > ... | the_stack_v2_python_sparse | src/Game/Effects/shuffle_and_deal.py | dfwarden/DeckBuilding | train | 0 |
3a0b8de2a2c252a8d35fcf7d19d0ff217926ab2f | [
"super(DCN, self).__init__()\nself.cate_fea_size = len(cate_fea_uniques)\nself.num_fea_size = num_fea_size\nself.num_layers = num_layers\nself.sparse_embedding = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in cate_fea_uniques])\nself.cross_layer = Cross_Layer()\nself.all_dims = [self.cate_fea_size ... | <|body_start_0|>
super(DCN, self).__init__()
self.cate_fea_size = len(cate_fea_uniques)
self.num_fea_size = num_fea_size
self.num_layers = num_layers
self.sparse_embedding = nn.ModuleList([nn.Embedding(voc_size, emb_size) for voc_size in cate_fea_uniques])
self.cross_laye... | DCN | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DCN:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_027335 | 5,894 | permissive | [
{
"docstring": ":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:",
"name": "__init__",
"signature": "def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2... | 2 | null | Implement the Python class `DCN` described below.
Class description:
Implement the DCN class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param... | Implement the Python class `DCN` described below.
Class description:
Implement the DCN class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class DCN:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DCN:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8, hidden_dims=[256, 128], dropout=[0.2, 0.2], num_layer=2):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: :param hidden_dims: :param num_classes: :param dropout:"""
super(DCN, self).__init__()
... | the_stack_v2_python_sparse | PyTorch/dev/others/Widedeep_ID2866_for_PyTorch/Deep&Cross/model.py | Ascend/ModelZoo-PyTorch | train | 23 | |
215761a77421206f14003a7107b9846c81d66994 | [
"super().__init__()\nactivation_func = F.leaky_relu\nglobal_pool_func = torchMax\nself.literal_code = embeddings[0][0]\nself.clause_code = embeddings[1][0]\nself.global_code = embeddings[2][0]\nself.encoder = nn.ModuleList()\nfor key, embedding_size in embeddings:\n self.encoder.append(conv_map[sum(key)](embeddi... | <|body_start_0|>
super().__init__()
activation_func = F.leaky_relu
global_pool_func = torchMax
self.literal_code = embeddings[0][0]
self.clause_code = embeddings[1][0]
self.global_code = embeddings[2][0]
self.encoder = nn.ModuleList()
for key, embedding_si... | This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as a critic value (combined actor-critic model). | Encode_Process_Decode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encode_Process_Decode:
"""This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as a critic value (combined actor-critic m... | stack_v2_sparse_classes_36k_train_027336 | 5,317 | no_license | [
{
"docstring": ":param embeddings: List of tupels containing code and embedding size for literals, clauses and global state :param additional_information: dictionary mapping codes of input features to their respective channel size",
"name": "__init__",
"signature": "def __init__(self, embeddings: List[t... | 2 | stack_v2_sparse_classes_30k_train_000064 | Implement the Python class `Encode_Process_Decode` described below.
Class description:
This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as ... | Implement the Python class `Encode_Process_Decode` described below.
Class description:
This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as ... | db61890e1a194ce47c7c945104b42abd7a1bee5b | <|skeleton|>
class Encode_Process_Decode:
"""This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as a critic value (combined actor-critic m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encode_Process_Decode:
"""This class implements the encode-process-decode architecture as specified here https://arxiv.org/abs/1806.01261. Given a population of graph encoded SAT problems, it outputs appropiate action distributions per individual as well as a critic value (combined actor-critic model)."""
... | the_stack_v2_python_sparse | src/neural_networks/encode_process_decode.py | KreitnerL/sat-evolution | train | 0 |
297cc63ae6165de7612fc90b26a42053206f13ae | [
"self.src, self.src_lengths = torch_batch.src\nself.src_mask = (self.src != pad_index).unsqueeze(1)\nself.nseqs = self.src.size(0)\nself.trg_input = None\nself.trg = None\nself.trg_mask = None\nself.trg_lengths = None\nself.ntokens = None\nself.use_cuda = use_cuda\nif hasattr(torch_batch, 'trg'):\n trg, trg_leng... | <|body_start_0|>
self.src, self.src_lengths = torch_batch.src
self.src_mask = (self.src != pad_index).unsqueeze(1)
self.nseqs = self.src.size(0)
self.trg_input = None
self.trg = None
self.trg_mask = None
self.trg_lengths = None
self.ntokens = None
... | Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator. | Batch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Batch:
"""Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator."""
def __init__(self, torch_batch, pad_index, use_cuda=False):
"""Create a new joey batch from a torch batch. This batch extends torch text's batch attributes with src... | stack_v2_sparse_classes_36k_train_027337 | 8,555 | permissive | [
{
"docstring": "Create a new joey batch from a torch batch. This batch extends torch text's batch attributes with src and trg length, masks, number of non-padded tokens in trg. Furthermore, it can be sorted by src length. :param torch_batch: :param pad_index: :param use_cuda:",
"name": "__init__",
"sign... | 3 | stack_v2_sparse_classes_30k_train_014874 | Implement the Python class `Batch` described below.
Class description:
Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator.
Method signatures and docstrings:
- def __init__(self, torch_batch, pad_index, use_cuda=False): Create a new joey batch from a torch batch. ... | Implement the Python class `Batch` described below.
Class description:
Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator.
Method signatures and docstrings:
- def __init__(self, torch_batch, pad_index, use_cuda=False): Create a new joey batch from a torch batch. ... | 3fda572a1996955061b2d478214f5157c064da3a | <|skeleton|>
class Batch:
"""Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator."""
def __init__(self, torch_batch, pad_index, use_cuda=False):
"""Create a new joey batch from a torch batch. This batch extends torch text's batch attributes with src... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Batch:
"""Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator."""
def __init__(self, torch_batch, pad_index, use_cuda=False):
"""Create a new joey batch from a torch batch. This batch extends torch text's batch attributes with src and trg leng... | the_stack_v2_python_sparse | joeynmt/batch.py | marvosyntactical/joeynmt | train | 3 |
e57bd5b1c83a97d32364399c502c8686a7c0dce3 | [
"dict = Counter(nums)\nnum = len(nums) // 3\nres = []\nfor key in dict.keys():\n if dict[key] > num:\n res.append(key)\nreturn res",
"num1, num2 = (nums[0], nums[0])\ncount1 = count2 = 0\nres = []\nfor i in range(len(nums)):\n if nums[i] == num1:\n count1 += 1\n elif nums[i] == num2:\n ... | <|body_start_0|>
dict = Counter(nums)
num = len(nums) // 3
res = []
for key in dict.keys():
if dict[key] > num:
res.append(key)
return res
<|end_body_0|>
<|body_start_1|>
num1, num2 = (nums[0], nums[0])
count1 = count2 = 0
res ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def majorityElement2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = Counter(nums)
... | stack_v2_sparse_classes_36k_train_027338 | 1,537 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "majorityElement2",
"signature": "def majorityElement2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018353 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: List[int]
- def majorityElement2(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: List[int]
- def majorityElement2(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def majorityElement2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: List[int]"""
dict = Counter(nums)
num = len(nums) // 3
res = []
for key in dict.keys():
if dict[key] > num:
res.append(key)
return res
def majorityElemen... | the_stack_v2_python_sparse | 229. Majority Element II/majority.py | Macielyoung/LeetCode | train | 1 | |
429c841a3c29d49bad9df1b2e84b729d7c2d2388 | [
"DBTYPE_MAP = {'mysql': None, 'sqlite': self._connectSqlite}\nfunk = DBTYPE_MAP[dbopts['type']]\nreturn funk(dbopts)",
"import apsw\nf = dbopts['filename']\nif not os.path.isfile(f):\n raise FileNotFoundError(\"DB '%s' does not exist - look at the --initdb option\" % f)\ndb = apsw.Connection(f)\ndb.setbusytime... | <|body_start_0|>
DBTYPE_MAP = {'mysql': None, 'sqlite': self._connectSqlite}
funk = DBTYPE_MAP[dbopts['type']]
return funk(dbopts)
<|end_body_0|>
<|body_start_1|>
import apsw
f = dbopts['filename']
if not os.path.isfile(f):
raise FileNotFoundError("DB '%s' do... | DbConnectionFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbConnectionFactory:
def connect(self, dbopts):
"""Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you can dump the .ini file's [database] section straight in."""
<|body_0|>
def _connectSqlite(self, ... | stack_v2_sparse_classes_36k_train_027339 | 1,257 | permissive | [
{
"docstring": "Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you can dump the .ini file's [database] section straight in.",
"name": "connect",
"signature": "def connect(self, dbopts)"
},
{
"docstring": "Create a conne... | 2 | null | Implement the Python class `DbConnectionFactory` described below.
Class description:
Implement the DbConnectionFactory class.
Method signatures and docstrings:
- def connect(self, dbopts): Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you c... | Implement the Python class `DbConnectionFactory` described below.
Class description:
Implement the DbConnectionFactory class.
Method signatures and docstrings:
- def connect(self, dbopts): Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you c... | 815502c06117c22456d20a5064a20e95bce4470d | <|skeleton|>
class DbConnectionFactory:
def connect(self, dbopts):
"""Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you can dump the .ini file's [database] section straight in."""
<|body_0|>
def _connectSqlite(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbConnectionFactory:
def connect(self, dbopts):
"""Return a connection to our database using the options from dict dbopts. Keys in this dict match those in our config file so you can dump the .ini file's [database] section straight in."""
DBTYPE_MAP = {'mysql': None, 'sqlite': self._connectSql... | the_stack_v2_python_sparse | code/storage/_connection.py | alexmbird/luckyhorse | train | 4 | |
6806e0d3dcfae4849b8586447c1c77d7c28763f6 | [
"exp_value = 'Hello'\nobj = String(exp_value)\nself.assertEqual(exp_value, obj.icpw_value)",
"exp_value = 'World'\nobj0 = String(exp_value)\nobj1 = String(exp_value)\nself.assertEqual(obj0, obj1)",
"exp_value = 'abc'\nobj0 = String(exp_value)\nobj1 = String('def')\nself.assertNotEqual(obj0, obj1)",
"exp_value... | <|body_start_0|>
exp_value = 'Hello'
obj = String(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
<|end_body_0|>
<|body_start_1|>
exp_value = 'World'
obj0 = String(exp_value)
obj1 = String(exp_value)
self.assertEqual(obj0, obj1)
<|end_body_1|>
<|body_star... | StringTester | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringTester:
def test_value(self):
"""Test retrieving the value of a String."""
<|body_0|>
def test_eq(self):
"""Test that String's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that String's with different values c... | stack_v2_sparse_classes_36k_train_027340 | 42,194 | permissive | [
{
"docstring": "Test retrieving the value of a String.",
"name": "test_value",
"signature": "def test_value(self)"
},
{
"docstring": "Test that String's with the same value compare equal.",
"name": "test_eq",
"signature": "def test_eq(self)"
},
{
"docstring": "Test that String's ... | 4 | stack_v2_sparse_classes_30k_train_008287 | Implement the Python class `StringTester` described below.
Class description:
Implement the StringTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a String.
- def test_eq(self): Test that String's with the same value compare equal.
- def test_ne(self): Test that Str... | Implement the Python class `StringTester` described below.
Class description:
Implement the StringTester class.
Method signatures and docstrings:
- def test_value(self): Test retrieving the value of a String.
- def test_eq(self): Test that String's with the same value compare equal.
- def test_ne(self): Test that Str... | a626f881d55c307bd857d0ff980cc526f2b18de2 | <|skeleton|>
class StringTester:
def test_value(self):
"""Test retrieving the value of a String."""
<|body_0|>
def test_eq(self):
"""Test that String's with the same value compare equal."""
<|body_1|>
def test_ne(self):
"""Test that String's with different values c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringTester:
def test_value(self):
"""Test retrieving the value of a String."""
exp_value = 'Hello'
obj = String(exp_value)
self.assertEqual(exp_value, obj.icpw_value)
def test_eq(self):
"""Test that String's with the same value compare equal."""
exp_value... | the_stack_v2_python_sparse | icypaw/test_types.py | sandialabs/IcyPaw | train | 0 | |
86991bc2941dda2f6d2aa41d66998454603299fc | [
"examples_dir = Path(pkg_resources.resource_filename('traits.stubs_tests', 'examples'))\nfor file_path in examples_dir.glob('*{}.py'.format(filename_suffix)):\n with self.subTest(file_path=file_path):\n self.assertRaisesMypyError(file_path)",
"examples_dir = Path(pkg_resources.resource_filename('traits.... | <|body_start_0|>
examples_dir = Path(pkg_resources.resource_filename('traits.stubs_tests', 'examples'))
for file_path in examples_dir.glob('*{}.py'.format(filename_suffix)):
with self.subTest(file_path=file_path):
self.assertRaisesMypyError(file_path)
<|end_body_0|>
<|body_s... | TestAnnotations | [
"CC-BY-3.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnnotations:
def test_all(self, filename_suffix=''):
"""Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside these files. Any mismatch will raise an assertion error. Parameters ---------- filename_suffix: str Optional... | stack_v2_sparse_classes_36k_train_027341 | 2,105 | permissive | [
{
"docstring": "Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside these files. Any mismatch will raise an assertion error. Parameters ---------- filename_suffix: str Optional filename suffix filter.",
"name": "test_all",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_020134 | Implement the Python class `TestAnnotations` described below.
Class description:
Implement the TestAnnotations class.
Method signatures and docstrings:
- def test_all(self, filename_suffix=''): Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside thes... | Implement the Python class `TestAnnotations` described below.
Class description:
Implement the TestAnnotations class.
Method signatures and docstrings:
- def test_all(self, filename_suffix=''): Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside thes... | d066c6d6d9000e2fe2226b47643db5ede528b2fd | <|skeleton|>
class TestAnnotations:
def test_all(self, filename_suffix=''):
"""Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside these files. Any mismatch will raise an assertion error. Parameters ---------- filename_suffix: str Optional... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnnotations:
def test_all(self, filename_suffix=''):
"""Run mypy for all files contained in traits.stubs_tests/examples directory. Lines with expected errors are marked inside these files. Any mismatch will raise an assertion error. Parameters ---------- filename_suffix: str Optional filename suff... | the_stack_v2_python_sparse | traits/stubs_tests/test_all.py | enthought/traits | train | 333 | |
6269d8d4f5120b1c608477a7e1a9793cc79edd40 | [
"layout_section_slug = request.GET.get('layout_section_slug', None)\nlayout_template_slug = request.GET.get('layout_template_slug', None)\nplugin_relation_default = request.GET.getlist('plugin_relation_default[]')\nplugin_relation_default_placeholder = request.GET.getlist('plugin_relation_default_placeholder[]')\ni... | <|body_start_0|>
layout_section_slug = request.GET.get('layout_section_slug', None)
layout_template_slug = request.GET.get('layout_template_slug', None)
plugin_relation_default = request.GET.getlist('plugin_relation_default[]')
plugin_relation_default_placeholder = request.GET.getlist('p... | Manage the layout of a placeholder. | LayoutListView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
<|body_0|>
def post(self, request):
"""Change the page layout"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027342 | 5,299 | permissive | [
{
"docstring": "Change and preview the layout of a placeholder",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Change the page layout",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017463 | Implement the Python class `LayoutListView` described below.
Class description:
Manage the layout of a placeholder.
Method signatures and docstrings:
- def get(self, request): Change and preview the layout of a placeholder
- def post(self, request): Change the page layout | Implement the Python class `LayoutListView` described below.
Class description:
Manage the layout of a placeholder.
Method signatures and docstrings:
- def get(self, request): Change and preview the layout of a placeholder
- def post(self, request): Change the page layout
<|skeleton|>
class LayoutListView:
"""Ma... | 00947315b5bca4977f1de40ddb951f843c345532 | <|skeleton|>
class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
<|body_0|>
def post(self, request):
"""Change the page layout"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayoutListView:
"""Manage the layout of a placeholder."""
def get(self, request):
"""Change and preview the layout of a placeholder"""
layout_section_slug = request.GET.get('layout_section_slug', None)
layout_template_slug = request.GET.get('layout_template_slug', None)
pl... | the_stack_v2_python_sparse | ionyweb/administration/views/manifest.py | ionyse/ionyweb | train | 4 |
61fb353296b05ae2ce3c47000c2daa3a1f04acc0 | [
"super().__init__(containers=containers, image=pygame.Surface(size), start=start)\nself.color = color\nself.size = size\nself.border_size = border_size\nself.inner_size = self.size - 2 * self.border_size\nself.fill = fill",
"self.image.fill(self.color)\nif not self.fill:\n self.image.fill((0, 0, 0), pygame.Rec... | <|body_start_0|>
super().__init__(containers=containers, image=pygame.Surface(size), start=start)
self.color = color
self.size = size
self.border_size = border_size
self.inner_size = self.size - 2 * self.border_size
self.fill = fill
<|end_body_0|>
<|body_start_1|>
... | A sprite that displays a rectangle | RectangleSprite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RectangleSprite:
"""A sprite that displays a rectangle"""
def __init__(self, containers, color, size, border_size, start, fill=False):
"""Creates the RectangleSprite"""
<|body_0|>
def update(self):
"""Draws the image for the sprite"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_027343 | 7,153 | no_license | [
{
"docstring": "Creates the RectangleSprite",
"name": "__init__",
"signature": "def __init__(self, containers, color, size, border_size, start, fill=False)"
},
{
"docstring": "Draws the image for the sprite",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000519 | Implement the Python class `RectangleSprite` described below.
Class description:
A sprite that displays a rectangle
Method signatures and docstrings:
- def __init__(self, containers, color, size, border_size, start, fill=False): Creates the RectangleSprite
- def update(self): Draws the image for the sprite | Implement the Python class `RectangleSprite` described below.
Class description:
A sprite that displays a rectangle
Method signatures and docstrings:
- def __init__(self, containers, color, size, border_size, start, fill=False): Creates the RectangleSprite
- def update(self): Draws the image for the sprite
<|skeleto... | 8604a243baeecdd393a54c18bf2ff9e003b4b8a0 | <|skeleton|>
class RectangleSprite:
"""A sprite that displays a rectangle"""
def __init__(self, containers, color, size, border_size, start, fill=False):
"""Creates the RectangleSprite"""
<|body_0|>
def update(self):
"""Draws the image for the sprite"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RectangleSprite:
"""A sprite that displays a rectangle"""
def __init__(self, containers, color, size, border_size, start, fill=False):
"""Creates the RectangleSprite"""
super().__init__(containers=containers, image=pygame.Surface(size), start=start)
self.color = color
self... | the_stack_v2_python_sparse | src/sprite/sprite_library.py | ZXQYC/random-shooter-game | train | 0 |
b0dde38ca32d9cb6f940d0cfac13eaf2cb04d2c7 | [
"n = len(A)\nif n < 3 or A[0] >= A[1] or A[n - 2] <= A[n - 1]:\n return False\ni = 1\nwhile i < n:\n if A[i - 1] < A[i]:\n i += 1\n else:\n break\nif i == n or A[i - 1] == A[i]:\n return False\nwhile i < n:\n if A[i - 1] > A[i]:\n i += 1\n else:\n return False\nreturn i... | <|body_start_0|>
n = len(A)
if n < 3 or A[0] >= A[1] or A[n - 2] <= A[n - 1]:
return False
i = 1
while i < n:
if A[i - 1] < A[i]:
i += 1
else:
break
if i == n or A[i - 1] == A[i]:
return False
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(self, A: List[int]) -> bool:
"""Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5.26% of Python3 online submissions for Valid Mountain Array."""
<|body_0|>
def valid... | stack_v2_sparse_classes_36k_train_027344 | 1,841 | permissive | [
{
"docstring": "Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5.26% of Python3 online submissions for Valid Mountain Array.",
"name": "validMountainArray",
"signature": "def validMountainArray(self, A: List[int]) -> bool"
}... | 2 | stack_v2_sparse_classes_30k_val_001018 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A: List[int]) -> bool: Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(self, A: List[int]) -> bool: Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5... | 9d7759bea1f44673c2de4f25a94b27368928a59f | <|skeleton|>
class Solution:
def validMountainArray(self, A: List[int]) -> bool:
"""Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5.26% of Python3 online submissions for Valid Mountain Array."""
<|body_0|>
def valid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
"""Runtime: 236 ms, faster than 79.18% of Python3 online submissions for Valid Mountain Array. Memory Usage: 15.2 MB, less than 5.26% of Python3 online submissions for Valid Mountain Array."""
n = len(A)
if n < 3 or A[0] >= ... | the_stack_v2_python_sparse | leetcode/google/tagged/mountain_array.py | pagsamo/google-tech-dev-guide | train | 0 | |
e901ce40ae513ba3bc1d25862955e2f23048114f | [
"self._dimension = dimension\nself._threshold = threshold\nself._oriented_right = oriented_right\nsuper(SemiquadraticCost, self).__init__(name)",
"if self._oriented_right:\n if xu[self._dimension, 0] > self._threshold:\n return (xu[self._dimension, 0] - self._threshold) ** 2\nelif xu[self._dimension, 0]... | <|body_start_0|>
self._dimension = dimension
self._threshold = threshold
self._oriented_right = oriented_right
super(SemiquadraticCost, self).__init__(name)
<|end_body_0|>
<|body_start_1|>
if self._oriented_right:
if xu[self._dimension, 0] > self._threshold:
... | SemiquadraticCost | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemiquadraticCost:
def __init__(self, dimension, threshold, oriented_right, name=''):
"""Initialize with dimension to add cost to and threshold above which to impose quadratic cost. :param dimension: dimension to add cost :type dimension: uint :param threshold: value above which to impos... | stack_v2_sparse_classes_36k_train_027345 | 3,517 | permissive | [
{
"docstring": "Initialize with dimension to add cost to and threshold above which to impose quadratic cost. :param dimension: dimension to add cost :type dimension: uint :param threshold: value above which to impose quadratic cost :type threshold: float :param oriented_right: Boolean flag determining which sid... | 2 | stack_v2_sparse_classes_30k_train_000757 | Implement the Python class `SemiquadraticCost` described below.
Class description:
Implement the SemiquadraticCost class.
Method signatures and docstrings:
- def __init__(self, dimension, threshold, oriented_right, name=''): Initialize with dimension to add cost to and threshold above which to impose quadratic cost. ... | Implement the Python class `SemiquadraticCost` described below.
Class description:
Implement the SemiquadraticCost class.
Method signatures and docstrings:
- def __init__(self, dimension, threshold, oriented_right, name=''): Initialize with dimension to add cost to and threshold above which to impose quadratic cost. ... | fbe9501a51e33498e0b916e2a870dada7c61df57 | <|skeleton|>
class SemiquadraticCost:
def __init__(self, dimension, threshold, oriented_right, name=''):
"""Initialize with dimension to add cost to and threshold above which to impose quadratic cost. :param dimension: dimension to add cost :type dimension: uint :param threshold: value above which to impos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemiquadraticCost:
def __init__(self, dimension, threshold, oriented_right, name=''):
"""Initialize with dimension to add cost to and threshold above which to impose quadratic cost. :param dimension: dimension to add cost :type dimension: uint :param threshold: value above which to impose quadratic co... | the_stack_v2_python_sparse | python/semiquadratic_cost.py | HJReachability/ilqgames | train | 89 | |
e06be68e80c550f5149a56e2ae9516f30b0a5018 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RecentNotebook()",
"from .onenote_source_service import OnenoteSourceService\nfrom .recent_notebook_links import RecentNotebookLinks\nfrom .onenote_source_service import OnenoteSourceService\nfrom .recent_notebook_links import RecentNo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RecentNotebook()
<|end_body_0|>
<|body_start_1|>
from .onenote_source_service import OnenoteSourceService
from .recent_notebook_links import RecentNotebookLinks
from .onenote_sou... | RecentNotebook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecentNotebook:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecentNotebook:
"""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_027346 | 4,075 | 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: RecentNotebook",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | null | Implement the Python class `RecentNotebook` described below.
Class description:
Implement the RecentNotebook class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecentNotebook: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `RecentNotebook` described below.
Class description:
Implement the RecentNotebook class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecentNotebook: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RecentNotebook:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecentNotebook:
"""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 RecentNotebook:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RecentNotebook:
"""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: RecentNote... | the_stack_v2_python_sparse | msgraph/generated/models/recent_notebook.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b4f4983fbceb79e19e83864c628795184cd41d34 | [
"name = self.request.get('name')\nbarcode = self.request.get('barcode')\ncategory_name = self.request.get('category_name')\nAdminWorkerHandler.create_product(name, barcode, category_name)",
"query = Category.all()\nquery.filter('description =', category_name)\nret = query.get()\nif ret is None:\n ret = Categor... | <|body_start_0|>
name = self.request.get('name')
barcode = self.request.get('barcode')
category_name = self.request.get('category_name')
AdminWorkerHandler.create_product(name, barcode, category_name)
<|end_body_0|>
<|body_start_1|>
query = Category.all()
query.filter('d... | Processor for product task queue | AdminWorkerHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminWorkerHandler:
"""Processor for product task queue"""
def post(self):
"""POST request handler"""
<|body_0|>
def create_category(category_name):
"""Create a category in datastore"""
<|body_1|>
def create_product(name, barcode, category):
... | stack_v2_sparse_classes_36k_train_027347 | 4,007 | no_license | [
{
"docstring": "POST request handler",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Create a category in datastore",
"name": "create_category",
"signature": "def create_category(category_name)"
},
{
"docstring": "Create a product in datastore",
"name": "cr... | 4 | stack_v2_sparse_classes_30k_train_006286 | Implement the Python class `AdminWorkerHandler` described below.
Class description:
Processor for product task queue
Method signatures and docstrings:
- def post(self): POST request handler
- def create_category(category_name): Create a category in datastore
- def create_product(name, barcode, category): Create a pro... | Implement the Python class `AdminWorkerHandler` described below.
Class description:
Processor for product task queue
Method signatures and docstrings:
- def post(self): POST request handler
- def create_category(category_name): Create a category in datastore
- def create_product(name, barcode, category): Create a pro... | 394b4821b65191df221d62f807ba2895f38e86a3 | <|skeleton|>
class AdminWorkerHandler:
"""Processor for product task queue"""
def post(self):
"""POST request handler"""
<|body_0|>
def create_category(category_name):
"""Create a category in datastore"""
<|body_1|>
def create_product(name, barcode, category):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminWorkerHandler:
"""Processor for product task queue"""
def post(self):
"""POST request handler"""
name = self.request.get('name')
barcode = self.request.get('barcode')
category_name = self.request.get('category_name')
AdminWorkerHandler.create_product(name, bar... | the_stack_v2_python_sparse | handlers/adminhandler.py | szilardhuber/shopper | train | 1 |
931654d8c015c07ae2143f6c126416d28050ef7a | [
"super(InputBaro, self).store(baro)\nself.thermostat.store(baro.thermostat)\nself.tau.store(baro.tau)\nif type(baro) is BaroBZP:\n self.mode.store('isotropic')\n self.p.store(baro.p)\nelif type(baro) is BaroSCBZP:\n self.mode.store('sc-isotropic')\n self.p.store(baro.p)\nelif type(baro) is BaroMTK:\n ... | <|body_start_0|>
super(InputBaro, self).store(baro)
self.thermostat.store(baro.thermostat)
self.tau.store(baro.tau)
if type(baro) is BaroBZP:
self.mode.store('isotropic')
self.p.store(baro.p)
elif type(baro) is BaroSCBZP:
self.mode.store('sc-is... | Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat used. Defaults to 'dummy'. Fields: thermostat: A thermostat object giving the ... | InputBaro | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputBaro:
"""Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat used. Defaults to 'dummy'. Fields: thermo... | stack_v2_sparse_classes_36k_train_027348 | 7,338 | no_license | [
{
"docstring": "Takes a barostat instance and stores a minimal representation of it. Args: baro: A barostat object.",
"name": "store",
"signature": "def store(self, baro)"
},
{
"docstring": "Creates a barostat object. Returns: A barostat object of the appropriate type and with the appropriate th... | 2 | null | Implement the Python class `InputBaro` described below.
Class description:
Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat us... | Implement the Python class `InputBaro` described below.
Class description:
Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat us... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class InputBaro:
"""Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat used. Defaults to 'dummy'. Fields: thermo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputBaro:
"""Barostat input class. Handles generating the appropriate barostat class from the xml input file, and generating the xml checkpoint tags and data from an instance of the object. Attributes: mode: An optional string giving the type of barostat used. Defaults to 'dummy'. Fields: thermostat: A therm... | the_stack_v2_python_sparse | ipi/inputs/barostats.py | i-pi/i-pi | train | 170 |
5b0ce8ac4250a1bea07a7d1e4204c645cc2c054d | [
"if len(dictionary) > 0:\n self.abbreviation = collections.defaultdict(dict)\n for word in dictionary:\n if len(word) < 3:\n ab_word = word\n else:\n ab_word = word[0] + str(len(word[1:-1])) + word[-1]\n if word not in self.abbreviation[ab_word]:\n self.ab... | <|body_start_0|>
if len(dictionary) > 0:
self.abbreviation = collections.defaultdict(dict)
for word in dictionary:
if len(word) < 3:
ab_word = word
else:
ab_word = word[0] + str(len(word[1:-1])) + word[-1]
... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(dictionary) > 0:
self.abbreviati... | stack_v2_sparse_classes_36k_train_027349 | 2,047 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | 3aab1747a1e6a77de808073e8735f89704940496 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
if len(dictionary) > 0:
self.abbreviation = collections.defaultdict(dict)
for word in dictionary:
if len(word) < 3:
ab_word = word
else:
... | the_stack_v2_python_sparse | leetcode/hashtable/uniqueWordAbbreviation.py | ziqingW/pythonPlayground | train | 0 | |
d37326b03c8321941d999b234f6b8d5df599b284 | [
"self.id = id\nself.config = {'maxdelay': 3600 * 24, 'maxCount': -1, 'datasource': None, 'acknowledge_on_clear': False}\nfor i in config:\n self.config[i] = config[i]\nif not self.read_config_file():\n return None\nif not 'aggregator_class' in self.config:\n self.config['aggregator_class'] = AggregationPro... | <|body_start_0|>
self.id = id
self.config = {'maxdelay': 3600 * 24, 'maxCount': -1, 'datasource': None, 'acknowledge_on_clear': False}
for i in config:
self.config[i] = config[i]
if not self.read_config_file():
return None
if not 'aggregator_class' in self... | MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easier. | MultiaggregationProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiaggregationProcessor:
"""MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easier."""
def setup(self, id, config={... | stack_v2_sparse_classes_36k_train_027350 | 4,517 | no_license | [
{
"docstring": "Setup method that configures the instance of this method InstanceFactory calls this with the id and configuration from datasource definitions defined in the conf.d directory",
"name": "setup",
"signature": "def setup(self, id, config={})"
},
{
"docstring": "Loads the configuratio... | 4 | stack_v2_sparse_classes_30k_test_000990 | Implement the Python class `MultiaggregationProcessor` described below.
Class description:
MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easie... | Implement the Python class `MultiaggregationProcessor` described below.
Class description:
MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easie... | 6b1834a1a3337bbb11b9cdb37d084b3f6699fdee | <|skeleton|>
class MultiaggregationProcessor:
"""MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easier."""
def setup(self, id, config={... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiaggregationProcessor:
"""MultiaggregationProcessor act upon normal AggregationProcessors and allow to define multiple rules in one rules file. The processor then handles creation of the actual Aggregationprocessors, which makes configuration a lot easier."""
def setup(self, id, config={}):
"... | the_stack_v2_python_sparse | src/processors/multiaggregation_processor.py | NETWAYS/eventdbcorrelator | train | 0 |
c653ef0b248892879977259685362bf27d177e0a | [
"sol = [0]\nif root == None:\n return 0\nself.helper(root, 1, sol)\nreturn sol[-1]",
"if depth > depthArr[-1]:\n depthArr.append(depth)\nif root.left:\n self.helper(root.left, depth + 1, depthArr)\nif root.right:\n self.helper(root.right, depth + 1, depthArr)"
] | <|body_start_0|>
sol = [0]
if root == None:
return 0
self.helper(root, 1, sol)
return sol[-1]
<|end_body_0|>
<|body_start_1|>
if depth > depthArr[-1]:
depthArr.append(depth)
if root.left:
self.helper(root.left, depth + 1, depthArr)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root, depth, depthArr):
""":type root: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sol = [0]
if ... | stack_v2_sparse_classes_36k_train_027351 | 1,406 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :type depth: int :rtype: int",
"name": "helper",
"signature": "def helper(self, root, depth, depthArr)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def helper(self, root, depth, depthArr): :type root: TreeNode :type depth: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def helper(self, root, depth, depthArr): :type root: TreeNode :type depth: int :rtype: int
<|skeleton|>
class Soluti... | 61933e7c0b8d8ffef9bd9a4af4fddfdb77568b62 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root, depth, depthArr):
""":type root: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
sol = [0]
if root == None:
return 0
self.helper(root, 1, sol)
return sol[-1]
def helper(self, root, depth, depthArr):
""":type root: TreeNode :type depth: int :rtype: int... | the_stack_v2_python_sparse | 104-Maximum-Depth-of-Binary-Tree.py | OhMesch/Algorithm-Problems | train | 0 | |
34a54df374c8271a13f8c709f182788b9b44fc01 | [
"value = '<div>'\nclase = 'actions'\nperm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)\nperm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_item)\nurl = './'\nif UrlParser.parse_nombre(request.url, 'post_buscar'):\n url = '../'\nif perm_mod.is_met(request.environ):\n value +... | <|body_start_0|>
value = '<div>'
clase = 'actions'
perm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)
perm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_item)
url = './'
if UrlParser.parse_nombre(request.url, 'post_buscar'):
... | RolesTipoTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw):
"""Se muestra la lista de roles para este tipo de ítem."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_027352 | 12,240 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de roles para este tipo de ítem.",
"name": "_do_get_provider_count_and_objs",
"signature": "def _do_get_provider_count_and_obj... | 2 | stack_v2_sparse_classes_30k_train_007469 | Implement the Python class `RolesTipoTableFiller` described below.
Class description:
Implement the RolesTipoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw): Se muestra la li... | Implement the Python class `RolesTipoTableFiller` described below.
Class description:
Implement the RolesTipoTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw): Se muestra la li... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_tipo_item=None, **kw):
"""Se muestra la lista de roles para este tipo de ítem."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RolesTipoTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
value = '<div>'
clase = 'actions'
perm_mod = PoseePermiso('modificar rol', id_tipo_item=obj.id_tipo_item)
perm_del = PoseePermiso('eliminar rol', id_tipo_item=obj.id_tipo_ite... | the_stack_v2_python_sparse | lpm/controllers/roles_tipo_item.py | jorgeramirez/LPM | train | 1 | |
36bad1c0cc04e3146b0c850f3a80fd21b31bd3ae | [
"super().__init__(df_X, ser_y)\nself._max_corr = max_corr\nself._df_corr = self._df_X.corr()\nself._df_corr = self._df_corr.fillna(0)",
"if len(self.chosens) > 0:\n df_corr = copy.deepcopy(self._df_corr)\n df_corr = pd.DataFrame(df_corr.loc[:, self.chosens])\n candidates = self.getCandidates()\n df_co... | <|body_start_0|>
super().__init__(df_X, ser_y)
self._max_corr = max_corr
self._df_corr = self._df_X.corr()
self._df_corr = self._df_corr.fillna(0)
<|end_body_0|>
<|body_start_1|>
if len(self.chosens) > 0:
df_corr = copy.deepcopy(self._df_corr)
df_corr = p... | Selects features for a class using correlations. | FeatureCollectionCorr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureCollectionCorr:
"""Selects features for a class using correlations."""
def __init__(self, df_X, ser_y, max_corr=MAX_CORR):
""":param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: instances values: class :param float max_corr: maximum corr... | stack_v2_sparse_classes_36k_train_027353 | 6,221 | permissive | [
{
"docstring": ":param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: instances values: class :param float max_corr: maximum correlation between a new feature an an existing feature",
"name": "__init__",
"signature": "def __init__(self, df_X, ser_y, max_corr=MAX_COR... | 2 | stack_v2_sparse_classes_30k_train_018674 | Implement the Python class `FeatureCollectionCorr` described below.
Class description:
Selects features for a class using correlations.
Method signatures and docstrings:
- def __init__(self, df_X, ser_y, max_corr=MAX_CORR): :param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: in... | Implement the Python class `FeatureCollectionCorr` described below.
Class description:
Selects features for a class using correlations.
Method signatures and docstrings:
- def __init__(self, df_X, ser_y, max_corr=MAX_CORR): :param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: in... | a57542245f117fe6c835cc9d7ad570b9853b7e6c | <|skeleton|>
class FeatureCollectionCorr:
"""Selects features for a class using correlations."""
def __init__(self, df_X, ser_y, max_corr=MAX_CORR):
""":param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: instances values: class :param float max_corr: maximum corr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureCollectionCorr:
"""Selects features for a class using correlations."""
def __init__(self, df_X, ser_y, max_corr=MAX_CORR):
""":param pd.DataFrame df_X: columns: features index: instances :param pd.Series ser_y: index: instances values: class :param float max_corr: maximum correlation betwe... | the_stack_v2_python_sparse | common_python/classifier/save/feature_collection.py | ScienceStacks/common_python | train | 1 |
3a8db96316ae7cf529ccb021ad07c01931bb95f1 | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) == 0:\n return '[]'\nreturn json.dumps(list_dictionaries)",
"filename = cls.__name__ + '.json'\nmy_list = []\nif list_objs is not None:\n for ... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) == 0:
return '[]'
return json.dumps(list_dicti... | This class has a constructor and a private class attribute | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""This class has a constructor and a private class attribute"""
def __init__(self, id=None):
"""Constructor method"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representation of list_dictionaries"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_027354 | 2,315 | no_license | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Returns the JSON string representation of list_dictionaries",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "W... | 6 | stack_v2_sparse_classes_30k_train_008507 | Implement the Python class `Base` described below.
Class description:
This class has a constructor and a private class attribute
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method
- def to_json_string(list_dictionaries): Returns the JSON string representation of list_dictionaries
- de... | Implement the Python class `Base` described below.
Class description:
This class has a constructor and a private class attribute
Method signatures and docstrings:
- def __init__(self, id=None): Constructor method
- def to_json_string(list_dictionaries): Returns the JSON string representation of list_dictionaries
- de... | 70068c87f3058324dca58fc5ef988af124a9a965 | <|skeleton|>
class Base:
"""This class has a constructor and a private class attribute"""
def __init__(self, id=None):
"""Constructor method"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representation of list_dictionaries"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
"""This class has a constructor and a private class attribute"""
def __init__(self, id=None):
"""Constructor method"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_di... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | tayloradam1999/holbertonschool-higher_level_programming | train | 1 |
4e010c3f79150e0ae9bad2034feb0a180c7a9b3e | [
"self.cluster_name = cluster_name\nself.encryption_key_data = encryption_key_data\nself.key_uid = key_uid\nself.vault_id = vault_id\nself.vault_name = vault_name",
"if dictionary is None:\n return None\ncluster_name = dictionary.get('clusterName')\nencryption_key_data = dictionary.get('encryptionKeyData')\nkey... | <|body_start_0|>
self.cluster_name = cluster_name
self.encryption_key_data = encryption_key_data
self.key_uid = key_uid
self.vault_id = vault_id
self.vault_name = vault_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
cluster_na... | Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. encryption_key_data (string): Specifies the encryption key data corresponding to the sp... | VaultEncryptionKey | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultEncryptionKey:
"""Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. encryption_key_data (string): Specifies t... | stack_v2_sparse_classes_36k_train_027355 | 2,880 | permissive | [
{
"docstring": "Constructor for the VaultEncryptionKey class",
"name": "__init__",
"signature": "def __init__(self, cluster_name=None, encryption_key_data=None, key_uid=None, vault_id=None, vault_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary ... | 2 | stack_v2_sparse_classes_30k_train_004175 | Implement the Python class `VaultEncryptionKey` described below.
Class description:
Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. en... | Implement the Python class `VaultEncryptionKey` described below.
Class description:
Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. en... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultEncryptionKey:
"""Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. encryption_key_data (string): Specifies t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VaultEncryptionKey:
"""Implementation of the 'VaultEncryptionKey' model. Specifies the encryption information needed to restore data. Attributes: cluster_name (string): Specifies the name of the source Cohesity Cluster that archived the data on the Vault. encryption_key_data (string): Specifies the encryption... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_encryption_key.py | cohesity/management-sdk-python | train | 24 |
3e7493bba61b7f6cb13a492764f5d6407b894617 | [
"self.X = X_init\nself.Y = Y_init\nself.sigma_f = sigma_f\nself.l = l\nself.K = self.kernel(self.X, self.X)",
"a = np.sum(X1 ** 2, 1).reshape(-1, 1)\nb = np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\nsqdist = a + b\nreturn self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqdist)",
"K = self.kernel(self.X, self.X)\n... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.sigma_f = sigma_f
self.l = l
self.K = self.kernel(self.X, self.X)
<|end_body_0|>
<|body_start_1|>
a = np.sum(X1 ** 2, 1).reshape(-1, 1)
b = np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
sqdist = a + b
... | Gaussian class | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Gaussian class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box ... | stack_v2_sparse_classes_36k_train_027356 | 2,092 | no_license | [
{
"docstring": "Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :param Y_init: is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box func... | 3 | stack_v2_sparse_classes_30k_train_002131 | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian class
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) re... | Implement the Python class `GaussianProcess` described below.
Class description:
Gaussian class
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) re... | f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7 | <|skeleton|>
class GaussianProcess:
"""Gaussian class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Gaussian class"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Create the class GaussianProcess that represents a noiseless 1D Gaussian process: :param X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function :par... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py | jalondono/holbertonschool-machine_learning | train | 2 |
b6bc83affd0875661f1c4492cc02f34e8d31934f | [
"super().__init__()\nif expression:\n if expression.isalpha():\n self[tuple({expression})] = 1\n else:\n self[tuple()] = int(expression)",
"ans = Polymerization()\nans.update(self)\nans.update(other)\nreturn ans",
"ans = Polymerization()\nans.update(self)\nans.update({k: -v for k, v in other... | <|body_start_0|>
super().__init__()
if expression:
if expression.isalpha():
self[tuple({expression})] = 1
else:
self[tuple()] = int(expression)
<|end_body_0|>
<|body_start_1|>
ans = Polymerization()
ans.update(self)
ans.upd... | 多项式类 | Polymerization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Polymerization:
"""多项式类"""
def __init__(self, expression: str=None):
"""构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)"""
<|body_0|>
def __add__(self, other):
"""返回加法操作"""
<|body_1|>
def __sub__(self, other):
"""实现减法操作"""
<|body_2... | stack_v2_sparse_classes_36k_train_027357 | 6,020 | no_license | [
{
"docstring": "构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)",
"name": "__init__",
"signature": "def __init__(self, expression: str=None)"
},
{
"docstring": "返回加法操作",
"name": "__add__",
"signature": "def __add__(self, other)"
},
{
"docstring": "实现减法操作",
"name": "__sub__... | 4 | null | Implement the Python class `Polymerization` described below.
Class description:
多项式类
Method signatures and docstrings:
- def __init__(self, expression: str=None): 构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)
- def __add__(self, other): 返回加法操作
- def __sub__(self, other): 实现减法操作
- def __mul__(self, other): 实现乘法操作 | Implement the Python class `Polymerization` described below.
Class description:
多项式类
Method signatures and docstrings:
- def __init__(self, expression: str=None): 构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)
- def __add__(self, other): 返回加法操作
- def __sub__(self, other): 实现减法操作
- def __mul__(self, other): 实现乘法操作... | a2209206cdd7229dd33e416f611e71a984a8dd9e | <|skeleton|>
class Polymerization:
"""多项式类"""
def __init__(self, expression: str=None):
"""构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)"""
<|body_0|>
def __add__(self, other):
"""返回加法操作"""
<|body_1|>
def __sub__(self, other):
"""实现减法操作"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Polymerization:
"""多项式类"""
def __init__(self, expression: str=None):
"""构造方法 :param expression: 只能构造基本单项式(不能包括加法、减法、乘法、括号)"""
super().__init__()
if expression:
if expression.isalpha():
self[tuple({expression})] = 1
else:
self... | the_stack_v2_python_sparse | 0701-0800/0770/0770_Python_1.py | ChangxingJiang/LeetCode | train | 0 |
4ca4327a7bbfc0a9adbcbfe9d8e552b5f57bf898 | [
"def wrapper(self, *args, **kwargs):\n dct = dict(zip(fun.__code__.co_varnames[1:len(args) + 1], args))\n slf = self\n kwargs.update(dct)\n hook = kwargs['hook']\n if not hook is None:\n hook._begin(**kwargs)\n kwargs['self'] = slf\n F, lb = fun(**kwargs)\n kwargs['Y'] = F\n kwargs... | <|body_start_0|>
def wrapper(self, *args, **kwargs):
dct = dict(zip(fun.__code__.co_varnames[1:len(args) + 1], args))
slf = self
kwargs.update(dct)
hook = kwargs['hook']
if not hook is None:
hook._begin(**kwargs)
kwargs['sel... | Skeleton class for GSSL Filters. | GSSLFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GSSLFilter:
"""Skeleton class for GSSL Filters."""
def autohooks(cls, fun):
"""Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeledIndexes'."""
<|body_0|>
def fit(self, X, Y, ... | stack_v2_sparse_classes_36k_train_027358 | 1,910 | no_license | [
{
"docstring": "Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeledIndexes'.",
"name": "autohooks",
"signature": "def autohooks(cls, fun)"
},
{
"docstring": "Filters the input data. Args: X (`NDArray... | 2 | stack_v2_sparse_classes_30k_train_004202 | Implement the Python class `GSSLFilter` described below.
Class description:
Skeleton class for GSSL Filters.
Method signatures and docstrings:
- def autohooks(cls, fun): Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeled... | Implement the Python class `GSSLFilter` described below.
Class description:
Skeleton class for GSSL Filters.
Method signatures and docstrings:
- def autohooks(cls, fun): Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeled... | df70cbbb48899e0c5c4c770c9c3bb72e288c7f5d | <|skeleton|>
class GSSLFilter:
"""Skeleton class for GSSL Filters."""
def autohooks(cls, fun):
"""Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeledIndexes'."""
<|body_0|>
def fit(self, X, Y, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GSSLFilter:
"""Skeleton class for GSSL Filters."""
def autohooks(cls, fun):
"""Automatically calls the begin and end method of the hook. At the end, the filtered labels are passed as 'Y', and the new labeled indexes as 'labeledIndexes'."""
def wrapper(self, *args, **kwargs):
d... | the_stack_v2_python_sparse | src/gssl/filters/filter.py | brunoklaus/GSSL_label_noise | train | 3 |
716598e54713fde901b3625461d59204dc4e9cb7 | [
"self.input_size = input_size\nself.output_size = output_size\nself.X = tf.placeholder(tf.float32, shape=[None, self.input_size])\nself.Y = tf.placeholder(tf.float32, shape=[None, self.output_size])\nself.n_layer_1 = 512\nself.n_layer_2 = 256\nself.weights = {'w1': tf.Variable(tf.glorot_uniform_initializer()((self.... | <|body_start_0|>
self.input_size = input_size
self.output_size = output_size
self.X = tf.placeholder(tf.float32, shape=[None, self.input_size])
self.Y = tf.placeholder(tf.float32, shape=[None, self.output_size])
self.n_layer_1 = 512
self.n_layer_2 = 256
self.weigh... | MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
def __init__(self, input_size, output_size, dropout=False, BN=False):
"""Function: Initialization of all variables"""
<|body_0|>
def MultiLayers(self):
"""Function: Define Neural Nets as y = sigmoid(w3 * relu(w2 * relu(w1 * x + b1) + b2) + b3) Using tf function ... | stack_v2_sparse_classes_36k_train_027359 | 19,475 | no_license | [
{
"docstring": "Function: Initialization of all variables",
"name": "__init__",
"signature": "def __init__(self, input_size, output_size, dropout=False, BN=False)"
},
{
"docstring": "Function: Define Neural Nets as y = sigmoid(w3 * relu(w2 * relu(w1 * x + b1) + b2) + b3) Using tf function tf.lay... | 5 | stack_v2_sparse_classes_30k_train_019272 | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, dropout=False, BN=False): Function: Initialization of all variables
- def MultiLayers(self): Function: Define Neural Nets as y = sigmoid(w3 * re... | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, dropout=False, BN=False): Function: Initialization of all variables
- def MultiLayers(self): Function: Define Neural Nets as y = sigmoid(w3 * re... | 929e28c3ea5aec63bc655035c48d96d2d3cff5bc | <|skeleton|>
class MLP:
def __init__(self, input_size, output_size, dropout=False, BN=False):
"""Function: Initialization of all variables"""
<|body_0|>
def MultiLayers(self):
"""Function: Define Neural Nets as y = sigmoid(w3 * relu(w2 * relu(w1 * x + b1) + b2) + b3) Using tf function ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLP:
def __init__(self, input_size, output_size, dropout=False, BN=False):
"""Function: Initialization of all variables"""
self.input_size = input_size
self.output_size = output_size
self.X = tf.placeholder(tf.float32, shape=[None, self.input_size])
self.Y = tf.placehol... | the_stack_v2_python_sparse | Ao_Zhang/assignment2/assignment2_question3.py | ZhangAoCanada/CSI5138_Assignments | train | 1 | |
f554712b62d991c5cd4f157f42604d5f98e280d7 | [
"def search(node, count):\n if node not in records:\n return 0\n elif (node[0] + 1, (node[1] - 1) * 2 + 1) not in records and (node[0] + 1, (node[1] - 1) * 2 + 2) not in records:\n return count + records[node]\n else:\n return search((node[0] + 1, (node[1] - 1) * 2 + 1), count + record... | <|body_start_0|>
def search(node, count):
if node not in records:
return 0
elif (node[0] + 1, (node[1] - 1) * 2 + 1) not in records and (node[0] + 1, (node[1] - 1) * 2 + 2) not in records:
return count + records[node]
else:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def pathSum_v2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def pathSum_verbose(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_027360 | 4,057 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "pathSum",
"signature": "def pathSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "pathSum_v2",
"signature": "def pathSum_v2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: in... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, nums): :type nums: List[int] :rtype: int
- def pathSum_v2(self, nums): :type nums: List[int] :rtype: int
- def pathSum_verbose(self, nums): :type nums: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, nums): :type nums: List[int] :rtype: int
- def pathSum_v2(self, nums): :type nums: List[int] :rtype: int
- def pathSum_verbose(self, nums): :type nums: List[int... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def pathSum(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def pathSum_v2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def pathSum_verbose(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pathSum(self, nums):
""":type nums: List[int] :rtype: int"""
def search(node, count):
if node not in records:
return 0
elif (node[0] + 1, (node[1] - 1) * 2 + 1) not in records and (node[0] + 1, (node[1] - 1) * 2 + 2) not in records:
... | the_stack_v2_python_sparse | src/lt_666.py | oxhead/CodingYourWay | train | 0 | |
3be6320f8695fef09aed55bfeaf49027d736e2e4 | [
"message = args.message\ncommit = XML.dig(message.xml, 'message', 'body', 'commit')\nsource = XML.dig(message.xml, 'message', 'source')\nauthor = XML.dig(commit, 'author')\nversion = XML.dig(commit, 'version')\nrevision = XML.dig(commit, 'revision')\ndiffLines = XML.dig(commit, 'diffLines')\nurl = XML.dig(commit, '... | <|body_start_0|>
message = args.message
commit = XML.dig(message.xml, 'message', 'body', 'commit')
source = XML.dig(message.xml, 'message', 'source')
author = XML.dig(commit, 'author')
version = XML.dig(commit, 'version')
revision = XML.dig(commit, 'revision')
dif... | Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing. | CommitToXHTMLLong | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommitToXHTMLLong:
"""Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing."""
def component_headers(self, element, args):
"""Format all relevant commit metadata in an email-style header box"""... | stack_v2_sparse_classes_36k_train_027361 | 21,460 | no_license | [
{
"docstring": "Format all relevant commit metadata in an email-style header box",
"name": "component_headers",
"signature": "def component_headers(self, element, args)"
},
{
"docstring": "Format the contents of our <files> tag as a tree with nested lists",
"name": "component_files",
"si... | 4 | stack_v2_sparse_classes_30k_train_005751 | Implement the Python class `CommitToXHTMLLong` described below.
Class description:
Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing.
Method signatures and docstrings:
- def component_headers(self, element, args): Format all... | Implement the Python class `CommitToXHTMLLong` described below.
Class description:
Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing.
Method signatures and docstrings:
- def component_headers(self, element, args): Format all... | fd505c3badbe3d13dd1d339b719f849a3e24f864 | <|skeleton|>
class CommitToXHTMLLong:
"""Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing."""
def component_headers(self, element, args):
"""Format all relevant commit metadata in an email-style header box"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommitToXHTMLLong:
"""Builds on the xhtml formatter to generate a longer representation of the commit, suitable for a full page rather than just an item in a listing."""
def component_headers(self, element, args):
"""Format all relevant commit metadata in an email-style header box"""
mess... | the_stack_v2_python_sparse | cia/LibCIA/Formatters/Commit.py | Justasic/cia-vc | train | 6 |
4cdcd2254e219ca22f778cf162069424188aa01a | [
"super().__init__()\nself.in_dim = in_dim\nself.out_dim = out_dim\nself.hidden_dims = hidden_dims\nself.n_properties = n_properties\nself.min_var = min_var\nself.non_linearity = non_linearity\nself.restrict_var = restrict_var\nself.network = nn.ModuleList()\nfor i in range(self.n_properties):\n self.network.appe... | <|body_start_0|>
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.hidden_dims = hidden_dims
self.n_properties = n_properties
self.min_var = min_var
self.non_linearity = non_linearity
self.restrict_var = restrict_var
self.network ... | MultiProbabilisticVanillaNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiProbabilisticVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False):
""":param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :... | stack_v2_sparse_classes_36k_train_027362 | 16,175 | no_license | [
{
"docstring": ":param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :param output_size: An integer describing the dimensionality of the output, in this case output_size = x_size :param decoder_n_hidden: An integer describing the ... | 2 | stack_v2_sparse_classes_30k_train_018518 | Implement the Python class `MultiProbabilisticVanillaNN` described below.
Class description:
Implement the MultiProbabilisticVanillaNN class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): :param input_size: A... | Implement the Python class `MultiProbabilisticVanillaNN` described below.
Class description:
Implement the MultiProbabilisticVanillaNN class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False): :param input_size: A... | de60f831ee082ab2ae232c498cf2755da7c14c27 | <|skeleton|>
class MultiProbabilisticVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False):
""":param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiProbabilisticVanillaNN:
def __init__(self, in_dim, out_dim, hidden_dims, n_properties, non_linearity=F.tanh, min_var=0.01, restrict_var=False):
""":param input_size: An integer describing the dimensionality of the input, in this case r_size, (the dimensionality of the embedding r) :param output_s... | the_stack_v2_python_sparse | models/networks/np_networks.py | PenelopeJones/neural_processes | train | 4 | |
dcb11597b0ea376c0d3e84af7aa58b8327e4a129 | [
"index = 0\nfor i in range(len(nums)):\n if nums[i] >= target:\n break\n index += 1\nreturn index",
"l, r = (0, len(nums) - 1)\nif r < 0:\n return 0\nwhile l < r:\n mid = (l + r) // 2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n r = mid - 1\n else:\... | <|body_start_0|>
index = 0
for i in range(len(nums)):
if nums[i] >= target:
break
index += 1
return index
<|end_body_0|>
<|body_start_1|>
l, r = (0, len(nums) - 1)
if r < 0:
return 0
while l < r:
mid = (l + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
"""O(n) :type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsert2(self, nums, target):
"""O(logn) :type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_027363 | 868 | no_license | [
{
"docstring": "O(n) :type nums: List[int] :type target: int :rtype: int",
"name": "searchInsert",
"signature": "def searchInsert(self, nums, target)"
},
{
"docstring": "O(logn) :type nums: List[int] :type target: int :rtype: int",
"name": "searchInsert2",
"signature": "def searchInsert2... | 2 | stack_v2_sparse_classes_30k_train_019758 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): O(n) :type nums: List[int] :type target: int :rtype: int
- def searchInsert2(self, nums, target): O(logn) :type nums: List[int] :type target... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): O(n) :type nums: List[int] :type target: int :rtype: int
- def searchInsert2(self, nums, target): O(logn) :type nums: List[int] :type target... | d71e725d779d7b45402893b311939c2cce60fbca | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
"""O(n) :type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsert2(self, nums, target):
"""O(logn) :type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchInsert(self, nums, target):
"""O(n) :type nums: List[int] :type target: int :rtype: int"""
index = 0
for i in range(len(nums)):
if nums[i] >= target:
break
index += 1
return index
def searchInsert2(self, nums, tar... | the_stack_v2_python_sparse | algorithm/0035Search_Insert_Position.py | xkoma001/leetcode | train | 0 | |
faeeebb0e4842426259135fbae9cab2d2406a928 | [
"if num1 == '0' or num2 == '0':\n return '0'\nlength = len(num1) + len(num2) - 1\nret = [0] * length\nfor i, num_i in enumerate(num1):\n for j, num_j in enumerate(num2):\n ret[i + j] += int(num_i) * int(num_j)\ncarry = 0\nfor i in range(length - 1, -1, -1):\n cur = ret[i] + carry\n ret[i] = str(c... | <|body_start_0|>
if num1 == '0' or num2 == '0':
return '0'
length = len(num1) + len(num2) - 1
ret = [0] * length
for i, num_i in enumerate(num1):
for j, num_j in enumerate(num2):
ret[i + j] += int(num_i) * int(num_j)
carry = 0
for i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def multiply1(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num1 == '0' or ... | stack_v2_sparse_classes_36k_train_027364 | 1,644 | no_license | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "multiply",
"signature": "def multiply(self, num1, num2)"
},
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "multiply1",
"signature": "def multiply1(self, num1, num2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def multiply1(self, num1, num2): :type num1: str :type num2: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def multiply1(self, num1, num2): :type num1: str :type num2: str :rtype: str
<|skeleton|>
class Sol... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def multiply1(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
if num1 == '0' or num2 == '0':
return '0'
length = len(num1) + len(num2) - 1
ret = [0] * length
for i, num_i in enumerate(num1):
for j, num_j in enumerate... | the_stack_v2_python_sparse | python/leetcode_bak/43_Multiply_Strings.py | bobcaoge/my-code | train | 0 | |
c1d5c9cd4b2c84248d98e8f59c62dc63ef57f65a | [
"super().__init__()\nself._lock: RLock = RLock()\nself._last: int = 0\nself._count: int = 0\nself._urn: Optional[str] = urn",
"with self._lock:\n now: int = int(time())\n if now == self._last:\n self._count += 1\n else:\n self._count = 0\n self._last = now\n if self._urn is not No... | <|body_start_0|>
super().__init__()
self._lock: RLock = RLock()
self._last: int = 0
self._count: int = 0
self._urn: Optional[str] = urn
<|end_body_0|>
<|body_start_1|>
with self._lock:
now: int = int(time())
if now == self._last:
s... | An event ID generator that always generates a unique, non-repeating ID. | BoboGenEventIDUnique | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
<|body_0|>
def generate(self) -> str:
""":... | stack_v2_sparse_classes_36k_train_027365 | 1,403 | permissive | [
{
"docstring": ":param urn: A URN to prefix before the generated event ID (optional).",
"name": "__init__",
"signature": "def __init__(self, urn: Optional[str]=None)"
},
{
"docstring": ":return: A generated event ID.",
"name": "generate",
"signature": "def generate(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_val_000336 | Implement the Python class `BoboGenEventIDUnique` described below.
Class description:
An event ID generator that always generates a unique, non-repeating ID.
Method signatures and docstrings:
- def __init__(self, urn: Optional[str]=None): :param urn: A URN to prefix before the generated event ID (optional).
- def gen... | Implement the Python class `BoboGenEventIDUnique` described below.
Class description:
An event ID generator that always generates a unique, non-repeating ID.
Method signatures and docstrings:
- def __init__(self, urn: Optional[str]=None): :param urn: A URN to prefix before the generated event ID (optional).
- def gen... | 7035feece42ae3494d4471e90f8ce818ed5ab670 | <|skeleton|>
class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
<|body_0|>
def generate(self) -> str:
""":... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
super().__init__()
self._lock: RLock = RLock()
self.... | the_stack_v2_python_sparse | bobocep/cep/gen/event_id.py | r3w0p/bobocep | train | 10 |
9c031704a42a5213d8455b26de9faad8a89709ab | [
"if not strs:\n return []\ncounter = {}\nfor i in range(len(strs)):\n item = sorted(strs[i])\n if str(item) not in counter:\n counter[str(item)] = [strs[i]]\n else:\n counter[str(item)].append(strs[i])\nresult = []\nfor item in counter:\n result.append(counter[item])\nreturn result",
... | <|body_start_0|>
if not strs:
return []
counter = {}
for i in range(len(strs)):
item = sorted(strs[i])
if str(item) not in counter:
counter[str(item)] = [strs[i]]
else:
counter[str(item)].append(strs[i])
resu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: list) -> list:
"""49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] 说明: 所有输入均为小写字母。 不考虑答案输出的顺序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/... | stack_v2_sparse_classes_36k_train_027366 | 1,937 | no_license | [
{
"docstring": "49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] 输出: [ [\"ate\",\"eat\",\"tea\"], [\"nat\",\"tan\"], [\"bat\"] ] 说明: 所有输入均为小写字母。 不考虑答案输出的顺序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/group-anagrams",
"name": "gro... | 3 | stack_v2_sparse_classes_30k_train_018537 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: list) -> list: 49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"],... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs: list) -> list: 49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"],... | 6580c7fd9a62494f82cedf69edda793865b5bd2d | <|skeleton|>
class Solution:
def groupAnagrams(self, strs: list) -> list:
"""49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] 说明: 所有输入均为小写字母。 不考虑答案输出的顺序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs: list) -> list:
"""49. 字母异位词分组 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] 说明: 所有输入均为小写字母。 不考虑答案输出的顺序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/group... | the_stack_v2_python_sparse | Week_02/groupAnagrams.py | ZGingko/algorithm008-class02 | train | 0 | |
a6d97ef7f26775c7455be5066c29797257552af2 | [
"if max_year is None:\n max_year = min_year\n min_year = datetime.datetime(max_year.year - 10, 2, 1)\ndiff = int(max_year.timestamp() * 1000 - min_year.timestamp() * 1000)\nif diff <= 0:\n return min_year\n_time = (min_year.timestamp() * 1000 + RandomInteger.next_integer(0, diff)) / 1000\ndate = datetime.d... | <|body_start_0|>
if max_year is None:
max_year = min_year
min_year = datetime.datetime(max_year.year - 10, 2, 1)
diff = int(max_year.timestamp() * 1000 - min_year.timestamp() * 1000)
if diff <= 0:
return min_year
_time = (min_year.timestamp() * 1000 + ... | Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.datetime(2017,1,1)) # Possible result: 2007-03-11 11:20:32 value3 = RandomDateTime.u... | RandomDateTime | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomDateTime:
"""Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.datetime(2017,1,1)) # Possible result: 200... | stack_v2_sparse_classes_36k_train_027367 | 3,392 | permissive | [
{
"docstring": "Generates a random Date in the range ['min_year', 'max_year']. This method generate dates without time (or time set to 00:00:00 :param min_year: min range args :param max_year: (optional) maximum range args :return: a random Date and time args.",
"name": "next_date",
"signature": "def ne... | 3 | null | Implement the Python class `RandomDateTime` described below.
Class description:
Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.dat... | Implement the Python class `RandomDateTime` described below.
Class description:
Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.dat... | 17f8a231fb75684032ec57b24025c9a3ca3dcdd6 | <|skeleton|>
class RandomDateTime:
"""Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.datetime(2017,1,1)) # Possible result: 200... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomDateTime:
"""Random generator for Date time values. Example: .. code-block:: python (month must be in 1..12) value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1)) # Possible result: 2008-01-03 value2 = RandomDateTime.next_datetime(datetime.datetime(2017,1,1)) # Possible result: 2007-03-11 11:20... | the_stack_v2_python_sparse | pip_services3_commons/random/RandomDateTime.py | pip-services3-python/pip-services3-commons-python | train | 0 |
f4cc49a6153b9d5fda25a7386ea34942d3d96557 | [
"sql = '\\n SELECT t.name, COUNT(*) FROM\\n cmdb.cmdb_assets a,\\n cmdb.cmdb_baseassettype t\\n WHERE\\n t.id = a.usetype_id'\nif custid:\n sql = \"{0} AND a.cust_id='{1}' \".format(sql, custid)\nsql = '{0} GROUP BY a.usetype_id'.format(sql)\nresult_li... | <|body_start_0|>
sql = '\n SELECT t.name, COUNT(*) FROM\n cmdb.cmdb_assets a,\n cmdb.cmdb_baseassettype t\n WHERE\n t.id = a.usetype_id'
if custid:
sql = "{0} AND a.cust_id='{1}' ".format(sql, custid)
sql = '{0} GROUP BY a.... | AssetsManage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssetsManage:
def asset_type_group_count(self, custid=None):
"""统计服务器设备数量,按设备类型统计 :param custid: :return:"""
<|body_0|>
def month_group_count(self, month_value_dict, custid=None):
"""获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_027368 | 7,277 | permissive | [
{
"docstring": "统计服务器设备数量,按设备类型统计 :param custid: :return:",
"name": "asset_type_group_count",
"signature": "def asset_type_group_count(self, custid=None)"
},
{
"docstring": "获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:",
"name": "month_group_count",
"signature": "def month_group_c... | 2 | stack_v2_sparse_classes_30k_train_021621 | Implement the Python class `AssetsManage` described below.
Class description:
Implement the AssetsManage class.
Method signatures and docstrings:
- def asset_type_group_count(self, custid=None): 统计服务器设备数量,按设备类型统计 :param custid: :return:
- def month_group_count(self, month_value_dict, custid=None): 获取当前月份以及之前12月内所有设备数... | Implement the Python class `AssetsManage` described below.
Class description:
Implement the AssetsManage class.
Method signatures and docstrings:
- def asset_type_group_count(self, custid=None): 统计服务器设备数量,按设备类型统计 :param custid: :return:
- def month_group_count(self, month_value_dict, custid=None): 获取当前月份以及之前12月内所有设备数... | 002f80dcc07e3502610b0a0be1e91fe61bcfc42c | <|skeleton|>
class AssetsManage:
def asset_type_group_count(self, custid=None):
"""统计服务器设备数量,按设备类型统计 :param custid: :return:"""
<|body_0|>
def month_group_count(self, month_value_dict, custid=None):
"""获取当前月份以及之前12月内所有设备数量统计 :param custid: 客户ID :return:"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssetsManage:
def asset_type_group_count(self, custid=None):
"""统计服务器设备数量,按设备类型统计 :param custid: :return:"""
sql = '\n SELECT t.name, COUNT(*) FROM\n cmdb.cmdb_assets a,\n cmdb.cmdb_baseassettype t\n WHERE\n t.id = a.usetype_id'
... | the_stack_v2_python_sparse | cmdb/afcat/cmdb/custmanage.py | tonglinge/MyProjects | train | 4 | |
7dc579854ceee91eba46e9c2c20511f4fac46fbe | [
"graph = collections.defaultdict(list)\nfor u, v, w in times:\n graph[u].append((v, w))\ndist = {node: float('inf') for node in range(1, N + 1)}\n\ndef dfs(node, time):\n if time >= dist[node]:\n return\n dist[node] = time\n for neib, t in sorted(graph[node]):\n dfs(neib, time + t)\ndfs(K,... | <|body_start_0|>
graph = collections.defaultdict(list)
for u, v, w in times:
graph[u].append((v, w))
dist = {node: float('inf') for node in range(1, N + 1)}
def dfs(node, time):
if time >= dist[node]:
return
dist[node] = time
... | Solution | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int:
"""DFS"""
<|body_0|>
def networkDelayTime2(self, times: List[List[int]], N: int, K: int) -> int:
"""Dijkstra"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
graph ... | stack_v2_sparse_classes_36k_train_027369 | 1,819 | permissive | [
{
"docstring": "DFS",
"name": "networkDelayTime1",
"signature": "def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int"
},
{
"docstring": "Dijkstra",
"name": "networkDelayTime2",
"signature": "def networkDelayTime2(self, times: List[List[int]], N: int, K: int) -> int... | 2 | stack_v2_sparse_classes_30k_train_006349 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int: DFS
- def networkDelayTime2(self, times: List[List[int]], N: int, K: int) -> int: Dijkstra | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int: DFS
- def networkDelayTime2(self, times: List[List[int]], N: int, K: int) -> int: Dijkstra
<|skeleton... | 5e5e7098d2310c972314c9c9895aafd048047fe6 | <|skeleton|>
class Solution:
def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int:
"""DFS"""
<|body_0|>
def networkDelayTime2(self, times: List[List[int]], N: int, K: int) -> int:
"""Dijkstra"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int:
"""DFS"""
graph = collections.defaultdict(list)
for u, v, w in times:
graph[u].append((v, w))
dist = {node: float('inf') for node in range(1, N + 1)}
def dfs(node, time):
... | the_stack_v2_python_sparse | 0743_Network_Delay_Time.py | imguozr/LC-Solutions | train | 0 | |
389b9fa23a0a2c3dd53a3233497902dd335903bc | [
"super(SFTableView, self).__init__(parent=parent)\nself.setHorizontalHeader(SFHeaderView(QtCore.Qt.Horizontal))\ndelegate_static = sfitemdelegate.SFItemStaticDelegate()\ndelegate = sfitemdelegate.SFItemDelegate(self, macontroller)\nself.setItemDelegateForColumn(0, delegate)\nself.setItemDelegateForColumn(1, delegat... | <|body_start_0|>
super(SFTableView, self).__init__(parent=parent)
self.setHorizontalHeader(SFHeaderView(QtCore.Qt.Horizontal))
delegate_static = sfitemdelegate.SFItemStaticDelegate()
delegate = sfitemdelegate.SFItemDelegate(self, macontroller)
self.setItemDelegateForColumn(0, del... | SFTableView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SFTableView:
def __init__(self, parent, macontroller=None):
"""A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controller for the interactions with maya @note: for some inexplicable reason, itemDelegateForColumn has to ... | stack_v2_sparse_classes_36k_train_027370 | 3,711 | no_license | [
{
"docstring": "A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controller for the interactions with maya @note: for some inexplicable reason, itemDelegateForColumn has to be called after a setItemDelegateForColumn in order for the latter to w... | 3 | null | Implement the Python class `SFTableView` described below.
Class description:
Implement the SFTableView class.
Method signatures and docstrings:
- def __init__(self, parent, macontroller=None): A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controll... | Implement the Python class `SFTableView` described below.
Class description:
Implement the SFTableView class.
Method signatures and docstrings:
- def __init__(self, parent, macontroller=None): A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controll... | a3c08d75e1ec396e0545b1ccb57ba8abdd2fb441 | <|skeleton|>
class SFTableView:
def __init__(self, parent, macontroller=None):
"""A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controller for the interactions with maya @note: for some inexplicable reason, itemDelegateForColumn has to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SFTableView:
def __init__(self, parent, macontroller=None):
"""A table view to display the shot finaling sculpts. @param parent: the parent of this widget @param macontroller: the controller for the interactions with maya @note: for some inexplicable reason, itemDelegateForColumn has to be called afte... | the_stack_v2_python_sparse | src/python/tool/autorigger_v01_obsolete/tools/shotFinaling/ui/sftableview.py | EmreTekinalp/Public | train | 0 | |
5c199d0954c49d94681cced4948842a3c3cd9cec | [
"if not root:\n return 0\nif not root.left and (not root.right):\n return 1\nif not root.left:\n return self.minDepth(root.right) + 1\nif not root.right:\n return self.minDepth(root.left) + 1\nreturn min(self.minDepth(root.left), self.minDepth(root.right)) + 1",
"if not root:\n return 0\nif not roo... | <|body_start_0|>
if not root:
return 0
if not root.left and (not root.right):
return 1
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left)... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def _minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_2... | stack_v2_sparse_classes_36k_train_027371 | 2,444 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "__minDepth",
"signature": "def __minDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int... | 3 | stack_v2_sparse_classes_30k_train_005586 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def __minDepth(self, root): :type root: TreeNode :rtype: int
- def _minDepth(self, root): :type root: TreeNode :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def __minDepth(self, root): :type root: TreeNode :rtype: int
- def _minDepth(self, root): :type root: TreeNode :rtype... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def __minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def _minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
if not root.left and (not root.right):
return 1
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
ret... | the_stack_v2_python_sparse | 111.minimum-depth-of-binary-tree.py | windard/leeeeee | train | 0 | |
d0cecff4ee02e5fcb692726947e3b79546ddac09 | [
"kwargs.setdefault('id', field.id)\nhtml = ['<!-- data: %r -->' % (field.data,), '<div %s>' % html_params(**kwargs)]\nhtml.extend(self.render_select('year', field))\nhtml.extend(self.render_select('month', field))\nhtml.extend(self.render_select('day', field))\nhtml.append('</div>')\nreturn HTMLString(''.join(html)... | <|body_start_0|>
kwargs.setdefault('id', field.id)
html = ['<!-- data: %r -->' % (field.data,), '<div %s>' % html_params(**kwargs)]
html.extend(self.render_select('year', field))
html.extend(self.render_select('month', field))
html.extend(self.render_select('day', field))
... | Widget for a partical date with 3 selectors (year, month, day). | PartialDate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartialDate:
"""Widget for a partical date with 3 selectors (year, month, day)."""
def __call__(self, field, **kwargs):
"""Render widget."""
<|body_0|>
def render_select(cls, part, field):
"""Render select for a specific part of date."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_027372 | 15,157 | permissive | [
{
"docstring": "Render widget.",
"name": "__call__",
"signature": "def __call__(self, field, **kwargs)"
},
{
"docstring": "Render select for a specific part of date.",
"name": "render_select",
"signature": "def render_select(cls, part, field)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016187 | Implement the Python class `PartialDate` described below.
Class description:
Widget for a partical date with 3 selectors (year, month, day).
Method signatures and docstrings:
- def __call__(self, field, **kwargs): Render widget.
- def render_select(cls, part, field): Render select for a specific part of date. | Implement the Python class `PartialDate` described below.
Class description:
Widget for a partical date with 3 selectors (year, month, day).
Method signatures and docstrings:
- def __call__(self, field, **kwargs): Render widget.
- def render_select(cls, part, field): Render select for a specific part of date.
<|skel... | ba412d49cff0158842878753b65fc60731df158c | <|skeleton|>
class PartialDate:
"""Widget for a partical date with 3 selectors (year, month, day)."""
def __call__(self, field, **kwargs):
"""Render widget."""
<|body_0|>
def render_select(cls, part, field):
"""Render select for a specific part of date."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartialDate:
"""Widget for a partical date with 3 selectors (year, month, day)."""
def __call__(self, field, **kwargs):
"""Render widget."""
kwargs.setdefault('id', field.id)
html = ['<!-- data: %r -->' % (field.data,), '<div %s>' % html_params(**kwargs)]
html.extend(self.... | the_stack_v2_python_sparse | orcid_hub/forms.py | jpeerz/NZ-ORCID-Hub | train | 0 |
0b14bf3b24df04160eefac84323c336d0db5f373 | [
"super(ShotRenderCrawler, self).__init__(*args, **kwargs)\nparts = self.var('name').split('_')\nlocationParts = parts[0].split('-')\nself.setVar('seq', locationParts[1], True)\nself.setVar('shot', parts[0], True)\nself.setVar('step', parts[1], True)\nself.setVar('pass', parts[2], True)\nself.setVar('renderName', '{... | <|body_start_0|>
super(ShotRenderCrawler, self).__init__(*args, **kwargs)
parts = self.var('name').split('_')
locationParts = parts[0].split('-')
self.setVar('seq', locationParts[1], True)
self.setVar('shot', parts[0], True)
self.setVar('step', parts[1], True)
sel... | Custom crawler used to detect renders for shots. | ShotRenderCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShotRenderCrawler:
"""Custom crawler used to detect renders for shots."""
def __init__(self, *args, **kwargs):
"""Create a Render object."""
<|body_0|>
def test(cls, pathHolder, parentCrawler):
"""Test if the path holder contains a shot render."""
<|body_... | stack_v2_sparse_classes_36k_train_027373 | 1,277 | permissive | [
{
"docstring": "Create a Render object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Test if the path holder contains a shot render.",
"name": "test",
"signature": "def test(cls, pathHolder, parentCrawler)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016394 | Implement the Python class `ShotRenderCrawler` described below.
Class description:
Custom crawler used to detect renders for shots.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a Render object.
- def test(cls, pathHolder, parentCrawler): Test if the path holder contains a shot rende... | Implement the Python class `ShotRenderCrawler` described below.
Class description:
Custom crawler used to detect renders for shots.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a Render object.
- def test(cls, pathHolder, parentCrawler): Test if the path holder contains a shot rende... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class ShotRenderCrawler:
"""Custom crawler used to detect renders for shots."""
def __init__(self, *args, **kwargs):
"""Create a Render object."""
<|body_0|>
def test(cls, pathHolder, parentCrawler):
"""Test if the path holder contains a shot render."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShotRenderCrawler:
"""Custom crawler used to detect renders for shots."""
def __init__(self, *args, **kwargs):
"""Create a Render object."""
super(ShotRenderCrawler, self).__init__(*args, **kwargs)
parts = self.var('name').split('_')
locationParts = parts[0].split('-')
... | the_stack_v2_python_sparse | src/lib/kombi/Crawler/Fs/Render/ShotRenderCrawler.py | kombiHQ/kombi | train | 2 |
665d6428c4e4bb264bf7313e961b9e625f5f77e4 | [
"self._capacity = float(tokens)\nself._tokens = float(tokens)\nself._fill_rate = float(fill_rate)\nself._timestamp = time.time()",
"while block and tokens > self.tokens:\n deficit = tokens - self._tokens\n delay = deficit / self._fill_rate\n time.sleep(delay)\nif tokens <= self.tokens:\n self._tokens ... | <|body_start_0|>
self._capacity = float(tokens)
self._tokens = float(tokens)
self._fill_rate = float(fill_rate)
self._timestamp = time.time()
<|end_body_0|>
<|body_start_1|>
while block and tokens > self.tokens:
deficit = tokens - self._tokens
delay = def... | An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe. | TokenBucket | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenBucket:
"""An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe."""
def __init__(self, tokens, fill_rate):
""":param int tokens: the total tokens in the bucket :param float fill_rate: the ra... | stack_v2_sparse_classes_36k_train_027374 | 2,497 | permissive | [
{
"docstring": ":param int tokens: the total tokens in the bucket :param float fill_rate: the rate in tokens/second that the bucket will be refilled.",
"name": "__init__",
"signature": "def __init__(self, tokens, fill_rate)"
},
{
"docstring": "Consume tokens from the bucket. Returns True if ther... | 3 | stack_v2_sparse_classes_30k_train_018648 | Implement the Python class `TokenBucket` described below.
Class description:
An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.
Method signatures and docstrings:
- def __init__(self, tokens, fill_rate): :param int tokens: the ... | Implement the Python class `TokenBucket` described below.
Class description:
An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe.
Method signatures and docstrings:
- def __init__(self, tokens, fill_rate): :param int tokens: the ... | a9562268497c1b95cb2a5f38deba1dcde9b08cf7 | <|skeleton|>
class TokenBucket:
"""An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe."""
def __init__(self, tokens, fill_rate):
""":param int tokens: the total tokens in the bucket :param float fill_rate: the ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenBucket:
"""An implementation of the token bucket algorithm. Usage:: >>> bucket = TokenBucket(80, 0.5) >>> print(bucket.consume(10)) True Not thread safe."""
def __init__(self, tokens, fill_rate):
""":param int tokens: the total tokens in the bucket :param float fill_rate: the rate in tokens/... | the_stack_v2_python_sparse | spinnman/connections/token_bucket.py | SpiNNakerManchester/SpiNNMan | train | 8 |
23f4c499b34d66492d508e0218d6810312aadd06 | [
"self.state = state\nself.t_score_gte = t_score_gte\nself.c_score_gte = c_score_gte\nself.fetch_size = fetch_size\nself.headers = {'Authorization': f'Token {api_token}'}\nself.base_url = vectra_url + '/api/v2.1/'\nself.verify = verify\nself.proxies = proxy\nself.first_fetch = first_fetch",
"full_url = self.base_u... | <|body_start_0|>
self.state = state
self.t_score_gte = t_score_gte
self.c_score_gte = c_score_gte
self.fetch_size = fetch_size
self.headers = {'Authorization': f'Token {api_token}'}
self.base_url = vectra_url + '/api/v2.1/'
self.verify = verify
self.proxie... | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def __init__(self, vectra_url: str, api_token: str, verify: bool, proxy: dict, fetch_size: int, first_fetch: str, t_score_gte: int, c_score_gte: int, state: str):
""":param vectra_url: IP or hostname of Vectra brain (ex https://www.example.com) - required :param api_token: API to... | stack_v2_sparse_classes_36k_train_027375 | 29,008 | permissive | [
{
"docstring": ":param vectra_url: IP or hostname of Vectra brain (ex https://www.example.com) - required :param api_token: API token for authentication when using API v2* :param verify: Boolean, controls whether we verify the server's TLS certificate :param proxy: Dictionary mapping protocol to the URL of the ... | 3 | stack_v2_sparse_classes_30k_train_009088 | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, vectra_url: str, api_token: str, verify: bool, proxy: dict, fetch_size: int, first_fetch: str, t_score_gte: int, c_score_gte: int, state: str): :param vectra_url: ... | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, vectra_url: str, api_token: str, verify: bool, proxy: dict, fetch_size: int, first_fetch: str, t_score_gte: int, c_score_gte: int, state: str): :param vectra_url: ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Client:
def __init__(self, vectra_url: str, api_token: str, verify: bool, proxy: dict, fetch_size: int, first_fetch: str, t_score_gte: int, c_score_gte: int, state: str):
""":param vectra_url: IP or hostname of Vectra brain (ex https://www.example.com) - required :param api_token: API to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
def __init__(self, vectra_url: str, api_token: str, verify: bool, proxy: dict, fetch_size: int, first_fetch: str, t_score_gte: int, c_score_gte: int, state: str):
""":param vectra_url: IP or hostname of Vectra brain (ex https://www.example.com) - required :param api_token: API token for authen... | the_stack_v2_python_sparse | Packs/Vectra/Integrations/Vectra_v2/Vectra_v2.py | demisto/content | train | 1,023 | |
4570a96598f5e57f6d8d66e24b426fdb8382f5ce | [
"batch = batch.to(self.device)\nchars, char_lens = batch.grapheme_encoded\nphn_bos, phn_lens = batch.phn_encoded_bos\nemb_char = self.hparams.encoder_emb(chars)\nx, _ = self.modules.enc(emb_char)\ne_in = self.modules.emb(phn_bos)\nh, w = self.modules.dec(e_in, x, char_lens)\nlogits = self.modules.lin(h)\np_seq = se... | <|body_start_0|>
batch = batch.to(self.device)
chars, char_lens = batch.grapheme_encoded
phn_bos, phn_lens = batch.phn_encoded_bos
emb_char = self.hparams.encoder_emb(chars)
x, _ = self.modules.enc(emb_char)
e_in = self.modules.emb(phn_bos)
h, w = self.modules.dec... | ASR | [
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASR:
def compute_forward(self, batch, stage):
"""Forward computations from the char batches to the output probabilities."""
<|body_0|>
def compute_objectives(self, predictions, batch, stage):
"""Computes the loss (CTC+NLL) given predictions and targets."""
<|... | stack_v2_sparse_classes_36k_train_027376 | 10,934 | permissive | [
{
"docstring": "Forward computations from the char batches to the output probabilities.",
"name": "compute_forward",
"signature": "def compute_forward(self, batch, stage)"
},
{
"docstring": "Computes the loss (CTC+NLL) given predictions and targets.",
"name": "compute_objectives",
"signa... | 6 | stack_v2_sparse_classes_30k_train_003635 | Implement the Python class `ASR` described below.
Class description:
Implement the ASR class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Forward computations from the char batches to the output probabilities.
- def compute_objectives(self, predictions, batch, stage): Computes the los... | Implement the Python class `ASR` described below.
Class description:
Implement the ASR class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Forward computations from the char batches to the output probabilities.
- def compute_objectives(self, predictions, batch, stage): Computes the los... | d4c9a53773f13d5a2843f25bc7f89482936e2f17 | <|skeleton|>
class ASR:
def compute_forward(self, batch, stage):
"""Forward computations from the char batches to the output probabilities."""
<|body_0|>
def compute_objectives(self, predictions, batch, stage):
"""Computes the loss (CTC+NLL) given predictions and targets."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ASR:
def compute_forward(self, batch, stage):
"""Forward computations from the char batches to the output probabilities."""
batch = batch.to(self.device)
chars, char_lens = batch.grapheme_encoded
phn_bos, phn_lens = batch.phn_encoded_bos
emb_char = self.hparams.encoder_... | the_stack_v2_python_sparse | recipes/LibriSpeech/G2P/train.py | zycv/speechbrain | train | 2 | |
8e753b7822a1a2802eb91ec30309d37fb4469ec1 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria. | CustomerNegativeCriterionServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerNegativeCriterionServiceServicer:
"""Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria."""
def GetCustomerNegativeCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
<|body_... | stack_v2_sparse_classes_36k_train_027377 | 6,280 | permissive | [
{
"docstring": "Returns the requested criterion in full detail.",
"name": "GetCustomerNegativeCriterion",
"signature": "def GetCustomerNegativeCriterion(self, request, context)"
},
{
"docstring": "Creates or removes criteria. Operation statuses are returned.",
"name": "MutateCustomerNegative... | 2 | stack_v2_sparse_classes_30k_train_012978 | Implement the Python class `CustomerNegativeCriterionServiceServicer` described below.
Class description:
Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria.
Method signatures and docstrings:
- def GetCustomerNegativeCriterion(self, request, context): Returns t... | Implement the Python class `CustomerNegativeCriterionServiceServicer` described below.
Class description:
Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria.
Method signatures and docstrings:
- def GetCustomerNegativeCriterion(self, request, context): Returns t... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class CustomerNegativeCriterionServiceServicer:
"""Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria."""
def GetCustomerNegativeCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerNegativeCriterionServiceServicer:
"""Proto file describing the Customer Negative Criterion service. Service to manage customer negative criteria."""
def GetCustomerNegativeCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
context.set_code(grp... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/customer_negative_criterion_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
5f87a34a957465945b1fb0a41931b57ae316adea | [
"if data is None:\n if n <= 0:\n raise ValueError('n must be a positive value')\n if p <= 0 or 1 <= p:\n raise ValueError('p must be greater than 0 and less than 1')\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise Value... | <|body_start_0|>
if data is None:
if n <= 0:
raise ValueError('n must be a positive value')
if p <= 0 or 1 <= p:
raise ValueError('p must be greater than 0 and less than 1')
else:
if type(data) is not list:
raise TypeErr... | represents a binomial distribution | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”"""
<|body_0|>
def pmf(self, k):... | stack_v2_sparse_classes_36k_train_027378 | 2,297 | no_license | [
{
"docstring": "Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "Calculates the value of the PMF (probab... | 3 | stack_v2_sparse_classes_30k_train_020920 | Implement the Python class `Binomial` described below.
Class description:
represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of... | Implement the Python class `Binomial` described below.
Class description:
represents a binomial distribution
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of... | c20d4dc396f53f2adf73ab9b360977ecf8834af4 | <|skeleton|>
class Binomial:
"""represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”"""
<|body_0|>
def pmf(self, k):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binomial:
"""represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize Binomial Args: data: list of the data used to estimate the distribution n: number of Bernoulli trials p: probability of a “success”"""
if data is None:
if n <= 0:
... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | afarizap/holbertonschool-machine_learning | train | 0 |
1c723b91eaa360c93fac1627b68762c84b69bb09 | [
"memo = {}\nfor i, num in enumerate(nums):\n if num in memo and i - memo[num] <= k:\n return True\n memo[num] = i\nreturn False",
"memo = set()\nfor i, num in enumerate(nums):\n if i > k:\n memo.discard(nums[i - k - 1])\n if num in memo:\n return True\n memo.add(num)\nreturn Fa... | <|body_start_0|>
memo = {}
for i, num in enumerate(nums):
if num in memo and i - memo[num] <= k:
return True
memo[num] = i
return False
<|end_body_0|>
<|body_start_1|>
memo = set()
for i, num in enumerate(nums):
if i > k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool:
"""Use dict"""
<|body_0|>
def containsNearbyDuplicate_MK2(self, nums: List[int], k: int) -> bool:
"""Use set"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
memo = {}
... | stack_v2_sparse_classes_36k_train_027379 | 690 | no_license | [
{
"docstring": "Use dict",
"name": "containsNearbyDuplicate_MK1",
"signature": "def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool"
},
{
"docstring": "Use set",
"name": "containsNearbyDuplicate_MK2",
"signature": "def containsNearbyDuplicate_MK2(self, nums: List[int],... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool: Use dict
- def containsNearbyDuplicate_MK2(self, nums: List[int], k: int) -> bool: Use set | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool: Use dict
- def containsNearbyDuplicate_MK2(self, nums: List[int], k: int) -> bool: Use set
<|skeleton|>
c... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool:
"""Use dict"""
<|body_0|>
def containsNearbyDuplicate_MK2(self, nums: List[int], k: int) -> bool:
"""Use set"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate_MK1(self, nums: List[int], k: int) -> bool:
"""Use dict"""
memo = {}
for i, num in enumerate(nums):
if num in memo and i - memo[num] <= k:
return True
memo[num] = i
return False
def containsNearb... | the_stack_v2_python_sparse | 0219. Contains Duplicate II/Solution.py | faterazer/LeetCode | train | 4 | |
a3baa22307cf1f2b3fe36efffea78c0dc62ea697 | [
"assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.LinearRegressionModel(_py2java(sc, self._coeff), self.intercept)\njava_model.save(sc._jsc.sc(), path)",
"assert sc._jvm is not None\njava_model = sc._jvm.org.apache.spark.mllib.regression.LinearRegressionModel.load(sc._jsc.sc(), p... | <|body_start_0|>
assert sc._jvm is not None
java_model = sc._jvm.org.apache.spark.mllib.regression.LinearRegressionModel(_py2java(sc, self._coeff), self.intercept)
java_model.save(sc._jsc.sc(), path)
<|end_body_0|>
<|body_start_1|>
assert sc._jvm is not None
java_model = sc._jvm... | A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, [1.0]), ... LabeledPoint(3.0, [2.0]), ... Labeled... | LinearRegressionModel | [
"BSD-3-Clause",
"CC0-1.0",
"CDDL-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown",... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegressionModel:
"""A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, ... | stack_v2_sparse_classes_36k_train_027380 | 36,577 | permissive | [
{
"docstring": "Save a LinearRegressionModel.",
"name": "save",
"signature": "def save(self, sc: SparkContext, path: str) -> None"
},
{
"docstring": "Load a LinearRegressionModel.",
"name": "load",
"signature": "def load(cls, sc: SparkContext, path: str) -> 'LinearRegressionModel'"
}
] | 2 | null | Implement the Python class `LinearRegressionModel` described below.
Class description:
A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPo... | Implement the Python class `LinearRegressionModel` described below.
Class description:
A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPo... | 60d8fc49bec5dae1b8cf39a0670cb640b430f520 | <|skeleton|>
class LinearRegressionModel:
"""A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearRegressionModel:
"""A linear regression model derived from a least-squares fit. .. versionadded:: 0.9.0 Examples -------- >>> from pyspark.mllib.linalg import SparseVector >>> from pyspark.mllib.regression import LabeledPoint >>> data = [ ... LabeledPoint(0.0, [0.0]), ... LabeledPoint(1.0, [1.0]), ... L... | the_stack_v2_python_sparse | python/pyspark/mllib/regression.py | apache/spark | train | 39,983 |
2b2e0e3322b6a103815664f6f409ebeca538a599 | [
"self.object = self.get_object()\nsuccess_url = self.get_success_url()\nself.object.delete()\ndel request.session['username']\nrequest.session.modified = True\nreturn HttpResponseRedirect(success_url)",
"current_user = super(DeleteUserProfile, self).get_object(queryset)\nif current_user.username != self.request.u... | <|body_start_0|>
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
del request.session['username']
request.session.modified = True
return HttpResponseRedirect(success_url)
<|end_body_0|>
<|body_start_1|>
current_user = supe... | Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect. | DeleteUserProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteUserProfile:
"""Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect."""
def delete(self, request, *args, **kwargs):
"... | stack_v2_sparse_classes_36k_train_027381 | 5,860 | permissive | [
{
"docstring": "Deletes the session",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
},
{
"docstring": "This will verify if the current user is deleting his profile or not",
"name": "get_object",
"signature": "def get_object(self, queryset=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000233 | Implement the Python class `DeleteUserProfile` described below.
Class description:
Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect.
Method signatures and... | Implement the Python class `DeleteUserProfile` described below.
Class description:
Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect.
Method signatures and... | 9ee3366ab6550fe73845f76ae6136319e59cbdac | <|skeleton|>
class DeleteUserProfile:
"""Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect."""
def delete(self, request, *args, **kwargs):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteUserProfile:
"""Deletes the user profile :param LoginRequiredMixin, DeleteView: Mixin that will check if user is logged in, Django's Generic View :return: Render login form if successfully delete the current session and redirect."""
def delete(self, request, *args, **kwargs):
"""Deletes the... | the_stack_v2_python_sparse | BestStore/User/views.py | rishabh-22/BestStore | train | 1 |
5cc9d4fce0ac1d601bd9ee6c6c92ec016ba228ff | [
"super().__init__(*args, **kwargs)\nself.dias_colegio = par.DIAS_COLEGIO\nself.probabilidad = par.PROBABILIDAD_DIA_COLEGIO",
"if self.dia in self.dias_colegio:\n if uniform(0, 1) < self.probabilidad:\n self._funcion()\n self.escribir_log()"
] | <|body_start_0|>
super().__init__(*args, **kwargs)
self.dias_colegio = par.DIAS_COLEGIO
self.probabilidad = par.PROBABILIDAD_DIA_COLEGIO
<|end_body_0|>
<|body_start_1|>
if self.dia in self.dias_colegio:
if uniform(0, 1) < self.probabilidad:
self._funcion()
... | DiaColegio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
<|body_0|>
def funcion(self):
"""si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None"""
... | stack_v2_sparse_classes_36k_train_027382 | 4,009 | no_license | [
{
"docstring": "dias_colegio: set(str) probabilidad: float",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None",
"name"... | 2 | null | Implement the Python class `DiaColegio` described below.
Class description:
Implement the DiaColegio class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): dias_colegio: set(str) probabilidad: float
- def funcion(self): si es que el dia está entre los habilitados para dia colegio, existe cier... | Implement the Python class `DiaColegio` described below.
Class description:
Implement the DiaColegio class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): dias_colegio: set(str) probabilidad: float
- def funcion(self): si es que el dia está entre los habilitados para dia colegio, existe cier... | 884be9365cd20a87aa0a75018a724e6ca0bc0182 | <|skeleton|>
class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
<|body_0|>
def funcion(self):
"""si es que el dia está entre los habilitados para dia colegio, existe cierta dprobabilidad de que se realice la función, retorna None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiaColegio:
def __init__(self, *args, **kwargs):
"""dias_colegio: set(str) probabilidad: float"""
super().__init__(*args, **kwargs)
self.dias_colegio = par.DIAS_COLEGIO
self.probabilidad = par.PROBABILIDAD_DIA_COLEGIO
def funcion(self):
"""si es que el dia está ent... | the_stack_v2_python_sparse | Tareas/T04/eventos.py | JoseAvanzada2019/IIC2233-2018-1-SantiRepo | train | 0 | |
9147e6e42b554b1e4b69e6061abeef698caa2663 | [
"article = Article.objects.get(slug=slug)\nbookmark = {}\nbookmark['user'] = self.request.user.id\nbookmark['article'] = article.pk\nserializer = self.serializer_class(data=bookmark)\nserializer.is_valid(raise_exception=True)\nserializer.save()\narticle_serializer = ArticleSerializer(instance=article, context={'req... | <|body_start_0|>
article = Article.objects.get(slug=slug)
bookmark = {}
bookmark['user'] = self.request.user.id
bookmark['article'] = article.pk
serializer = self.serializer_class(data=bookmark)
serializer.is_valid(raise_exception=True)
serializer.save()
a... | Views for the bookmark functionality | BookmarkAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
<|body_0|>
def check_article(self, slug):
"""Check if article with the pass in slug exists if not :return 404"""
<|body... | stack_v2_sparse_classes_36k_train_027383 | 3,951 | permissive | [
{
"docstring": "Create a bookmark method",
"name": "post",
"signature": "def post(self, request, slug=None, pk=None)"
},
{
"docstring": "Check if article with the pass in slug exists if not :return 404",
"name": "check_article",
"signature": "def check_article(self, slug)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_019858 | Implement the Python class `BookmarkAPIView` described below.
Class description:
Views for the bookmark functionality
Method signatures and docstrings:
- def post(self, request, slug=None, pk=None): Create a bookmark method
- def check_article(self, slug): Check if article with the pass in slug exists if not :return ... | Implement the Python class `BookmarkAPIView` described below.
Class description:
Views for the bookmark functionality
Method signatures and docstrings:
- def post(self, request, slug=None, pk=None): Create a bookmark method
- def check_article(self, slug): Check if article with the pass in slug exists if not :return ... | e8438b78b88c52d108520429d0b67cd3d13e0824 | <|skeleton|>
class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
<|body_0|>
def check_article(self, slug):
"""Check if article with the pass in slug exists if not :return 404"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookmarkAPIView:
"""Views for the bookmark functionality"""
def post(self, request, slug=None, pk=None):
"""Create a bookmark method"""
article = Article.objects.get(slug=slug)
bookmark = {}
bookmark['user'] = self.request.user.id
bookmark['article'] = article.pk
... | the_stack_v2_python_sparse | authors/apps/bookmarks/views.py | andela/ah-sealteam | train | 1 |
96cc7420b3d25dc25f1b1cbca43d80ddf496ae94 | [
"try:\n request_info = json.loads(str(request.body, 'utf-8'))\n result = netconf.create_new_network(request_info)\n if request_info['type'] == 'wdnn':\n JobStateLoader().check_exist(request_info['nn_id'], '1')\n else:\n JobStateLoader().check_exist(request_info['nn_id'], '2')\n return_d... | <|body_start_0|>
try:
request_info = json.loads(str(request.body, 'utf-8'))
result = netconf.create_new_network(request_info)
if request_info['type'] == 'wdnn':
JobStateLoader().check_exist(request_info['nn_id'], '1')
else:
JobState... | 1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/{args}/... | CommonNetInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonNetInfo:
"""1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/datafr... | stack_v2_sparse_classes_36k_train_027384 | 4,036 | no_license | [
{
"docstring": "- Request json data example <texfied> <font size = 1> { \"nn_id\": \"nn0000012\", \"category\": \"MES\", \"subcate\" : \"M60\", \"name\": \"evaluation\", \"desc\" : \"wdnn_protoType\" } </font> </textfield> --- parameters: - name: body paramType: body pytype: json",
"name": "post",
"sign... | 4 | stack_v2_sparse_classes_30k_test_000271 | Implement the Python class `CommonNetInfo` described below.
Class description:
1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/tabl... | Implement the Python class `CommonNetInfo` described below.
Class description:
1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/tabl... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class CommonNetInfo:
"""1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/datafr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonNetInfo:
"""1. Name : CommonNetInfo (step 2) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{bas... | the_stack_v2_python_sparse | tfmsarest/views/common_nninfo.py | TensorMSA/tensormsa_old | train | 6 |
ac5dfff75236146ede375c4ba8757575f4c6a95b | [
"async with database.connection() as connection:\n raw_connection = connection.raw_connection\n raw_connection.row_factory = aiosqlite.Row\n query = 'SELECT * FROM authors LIMIT :limit OFFSET :offset;'\n cursor = await raw_connection.execute(query, request_data)\n return await cursor.fetchall()",
"... | <|body_start_0|>
async with database.connection() as connection:
raw_connection = connection.raw_connection
raw_connection.row_factory = aiosqlite.Row
query = 'SELECT * FROM authors LIMIT :limit OFFSET :offset;'
cursor = await raw_connection.execute(query, request... | AuthorsEndpoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
<|body_0|>
async def post(self, request_data: typing.Dict) -> aiosqlite.Row:
"""Creat... | stack_v2_sparse_classes_36k_train_027385 | 3,278 | permissive | [
{
"docstring": "Retrieves the list of authors. List is limited with `limit` and `offset` fields.",
"name": "get",
"signature": "async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]"
},
{
"docstring": "Creates a new author and returns the created record",
"name": "post... | 2 | stack_v2_sparse_classes_30k_test_000176 | Implement the Python class `AuthorsEndpoint` described below.
Class description:
Implement the AuthorsEndpoint class.
Method signatures and docstrings:
- async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]: Retrieves the list of authors. List is limited with `limit` and `offset` fields.
- asy... | Implement the Python class `AuthorsEndpoint` described below.
Class description:
Implement the AuthorsEndpoint class.
Method signatures and docstrings:
- async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]: Retrieves the list of authors. List is limited with `limit` and `offset` fields.
- asy... | 4c18a1cf1cfa088d67a61b89e64217e2e4dac809 | <|skeleton|>
class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
<|body_0|>
async def post(self, request_data: typing.Dict) -> aiosqlite.Row:
"""Creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
async with database.connection() as connection:
raw_connection = connection.raw_connection
... | the_stack_v2_python_sparse | example_app/base_api/base_common.py | gvbgduh/starlette-cbge | train | 7 | |
8e79beb2aa31bd126e63deaddf60b57da985beac | [
"if target == trackSum:\n self.res.append(track[:])\n return\nfor i in range(k, len(candidates)):\n if trackSum + candidates[i] > target:\n continue\n track.append(candidates[i])\n trackSum += candidates[i]\n self.backtrack(candidates, i, track, trackSum, target)\n track.pop()\n track... | <|body_start_0|>
if target == trackSum:
self.res.append(track[:])
return
for i in range(k, len(candidates)):
if trackSum + candidates[i] > target:
continue
track.append(candidates[i])
trackSum += candidates[i]
self.b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] ... | stack_v2_sparse_classes_36k_train_027386 | 1,096 | no_license | [
{
"docstring": ":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int",
"name": "backtrack",
"signature": "def backtrack(self, candidates, k, track, trackSum, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[Li... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, candidates, k, track, trackSum, target): :type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int
- def combinati... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backtrack(self, candidates, k, track, trackSum, target): :type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int
- def combinati... | 532ceca2c7ded27fd446ee540a3c906b4135a257 | <|skeleton|>
class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
<|body_0|>
def combinationSum(self, candidates, target):
""":type candidates: List[int] ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def backtrack(self, candidates, k, track, trackSum, target):
""":type candidates: List[int] :type k: int :type track: List[int] :type trackSum: int :type target: int"""
if target == trackSum:
self.res.append(track[:])
return
for i in range(k, len(candi... | the_stack_v2_python_sparse | pyland/solutions/sum_to_target_bfs.py | yerassyldanay/leetcode | train | 0 | |
ec759c4b5795570872b9b5c7d819558b5ea41801 | [
"remove_columns = ['containing_subdossier', 'checked_out']\ncolumns = []\nfor col in super(InboxDocuments, self).columns:\n if isinstance(col, dict) and col.get('column') in remove_columns:\n pass\n elif isinstance(col, tuple) and col[1] == external_edit_link:\n pass\n else:\n columns.... | <|body_start_0|>
remove_columns = ['containing_subdossier', 'checked_out']
columns = []
for col in super(InboxDocuments, self).columns:
if isinstance(col, dict) and col.get('column') in remove_columns:
pass
elif isinstance(col, tuple) and col[1] == externa... | Lists all Forwardings in this container | InboxDocuments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InboxDocuments:
"""Lists all Forwardings in this container"""
def columns(self):
"""Gets the columns wich wich will be displayed"""
<|body_0|>
def enabled_actions(self):
"""Defines the enabled Actions"""
<|body_1|>
def major_actions(self):
""... | stack_v2_sparse_classes_36k_train_027387 | 3,154 | no_license | [
{
"docstring": "Gets the columns wich wich will be displayed",
"name": "columns",
"signature": "def columns(self)"
},
{
"docstring": "Defines the enabled Actions",
"name": "enabled_actions",
"signature": "def enabled_actions(self)"
},
{
"docstring": "Defines wich actions are majo... | 3 | null | Implement the Python class `InboxDocuments` described below.
Class description:
Lists all Forwardings in this container
Method signatures and docstrings:
- def columns(self): Gets the columns wich wich will be displayed
- def enabled_actions(self): Defines the enabled Actions
- def major_actions(self): Defines wich a... | Implement the Python class `InboxDocuments` described below.
Class description:
Lists all Forwardings in this container
Method signatures and docstrings:
- def columns(self): Gets the columns wich wich will be displayed
- def enabled_actions(self): Defines the enabled Actions
- def major_actions(self): Defines wich a... | 954964872f73c0d18d5b0e0ab2dbf603849e4e87 | <|skeleton|>
class InboxDocuments:
"""Lists all Forwardings in this container"""
def columns(self):
"""Gets the columns wich wich will be displayed"""
<|body_0|>
def enabled_actions(self):
"""Defines the enabled Actions"""
<|body_1|>
def major_actions(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InboxDocuments:
"""Lists all Forwardings in this container"""
def columns(self):
"""Gets the columns wich wich will be displayed"""
remove_columns = ['containing_subdossier', 'checked_out']
columns = []
for col in super(InboxDocuments, self).columns:
if isinsta... | the_stack_v2_python_sparse | opengever/inbox/inbox.py | hellfish2/opengever.core | train | 1 |
a5ede93dd30265c32154896e8ac3a08ee7105073 | [
"if not root:\n return 0\nvalues = self.dfs(root)\nreturn max(values[0], values[1])",
"if not node:\n return (0, 0)\nleft = self.dfs(node.left)\nright = self.dfs(node.right)\nrob_node = left[1] + right[1] + node.val\nnot_rob = max(left[0], left[1]) + max(right[0], right[1])\nreturn (rob_node, not_rob)"
] | <|body_start_0|>
if not root:
return 0
values = self.dfs(root)
return max(values[0], values[1])
<|end_body_0|>
<|body_start_1|>
if not node:
return (0, 0)
left = self.dfs(node.left)
right = self.dfs(node.right)
rob_node = left[1] + right[1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_027388 | 876 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob",
"signature": "def rob(self, root)"
},
{
"docstring": "return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node",
"name": "dfs",
"signature": "def dfs(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001205 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob n... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
values = self.dfs(root)
return max(values[0], values[1])
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the n... | the_stack_v2_python_sparse | Algorithm/337_House_Rob_III.py | Gi1ia/TechNoteBook | train | 7 | |
3db277d7078183e0f80cff8bc228f1233832e171 | [
"vars_dict = {entry_point: {}}\ntry:\n for _name, argument in nested_args.items():\n dict_utils.dict_insert(vars_dict[entry_point], argument, *_name.split(delimiter))\nexcept exceptions.IRKeyNotFoundException as key_exception:\n if key_exception and key_exception.key.startswith('private.'):\n ra... | <|body_start_0|>
vars_dict = {entry_point: {}}
try:
for _name, argument in nested_args.items():
dict_utils.dict_insert(vars_dict[entry_point], argument, *_name.split(delimiter))
except exceptions.IRKeyNotFoundException as key_exception:
if key_exception an... | VarsDictManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VarsDictManager:
def generate_settings(entry_point, nested_args, delimiter='-'):
"""Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nested under this key :param nested_args: dict. these values will be nested example: { foo-bar: value1, foo... | stack_v2_sparse_classes_36k_train_027389 | 3,195 | permissive | [
{
"docstring": "Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nested under this key :param nested_args: dict. these values will be nested example: { foo-bar: value1, foo2: value2 foo-another-bar: value3 } :param delimiter: character to split keys by. :return: d... | 2 | null | Implement the Python class `VarsDictManager` described below.
Class description:
Implement the VarsDictManager class.
Method signatures and docstrings:
- def generate_settings(entry_point, nested_args, delimiter='-'): Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nes... | Implement the Python class `VarsDictManager` described below.
Class description:
Implement the VarsDictManager class.
Method signatures and docstrings:
- def generate_settings(entry_point, nested_args, delimiter='-'): Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nes... | 1ff4b3c151bc365ef97b6a27bc3eb12eb55cf4ce | <|skeleton|>
class VarsDictManager:
def generate_settings(entry_point, nested_args, delimiter='-'):
"""Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nested under this key :param nested_args: dict. these values will be nested example: { foo-bar: value1, foo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VarsDictManager:
def generate_settings(entry_point, nested_args, delimiter='-'):
"""Unifies all input into a single dict of Ansible extra-vars :param entry_point: All input will be nested under this key :param nested_args: dict. these values will be nested example: { foo-bar: value1, foo2: value2 foo-... | the_stack_v2_python_sparse | infrared/core/settings.py | redhat-openstack/infrared | train | 91 | |
386fbdb9239fc74634400ff63f903a9d5fa6fdc6 | [
"orchestrator = None\nbackend = 'consul'\nif kwargs.get('--orchestrator'):\n orchestrator = kwargs['--orchestrator']\nif kwargs.get('--backend'):\n backend = kwargs['--backend']\nif not orchestrator or not backend:\n logger.error('Orchestrator and backend need to be specified')\n sys.exit(1)\ntry:\n ... | <|body_start_0|>
orchestrator = None
backend = 'consul'
if kwargs.get('--orchestrator'):
orchestrator = kwargs['--orchestrator']
if kwargs.get('--backend'):
backend = kwargs['--backend']
if not orchestrator or not backend:
logger.error('Orchest... | Manage config from command given to sentinel | ConfigManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigManager:
"""Manage config from command given to sentinel"""
def create_config(cls, logger=None, **kwargs):
"""Create the config"""
<|body_0|>
def swarm_consul_gen_config(logger=None, **kwargs):
"""Generate SwarmNodeConfig from command given to sentinel"""
... | stack_v2_sparse_classes_36k_train_027390 | 7,321 | permissive | [
{
"docstring": "Create the config",
"name": "create_config",
"signature": "def create_config(cls, logger=None, **kwargs)"
},
{
"docstring": "Generate SwarmNodeConfig from command given to sentinel",
"name": "swarm_consul_gen_config",
"signature": "def swarm_consul_gen_config(logger=None,... | 2 | stack_v2_sparse_classes_30k_train_016181 | Implement the Python class `ConfigManager` described below.
Class description:
Manage config from command given to sentinel
Method signatures and docstrings:
- def create_config(cls, logger=None, **kwargs): Create the config
- def swarm_consul_gen_config(logger=None, **kwargs): Generate SwarmNodeConfig from command g... | Implement the Python class `ConfigManager` described below.
Class description:
Manage config from command given to sentinel
Method signatures and docstrings:
- def create_config(cls, logger=None, **kwargs): Create the config
- def swarm_consul_gen_config(logger=None, **kwargs): Generate SwarmNodeConfig from command g... | bfe0c0007c4ee448703efc25e8110a926d432328 | <|skeleton|>
class ConfigManager:
"""Manage config from command given to sentinel"""
def create_config(cls, logger=None, **kwargs):
"""Create the config"""
<|body_0|>
def swarm_consul_gen_config(logger=None, **kwargs):
"""Generate SwarmNodeConfig from command given to sentinel"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigManager:
"""Manage config from command given to sentinel"""
def create_config(cls, logger=None, **kwargs):
"""Create the config"""
orchestrator = None
backend = 'consul'
if kwargs.get('--orchestrator'):
orchestrator = kwargs['--orchestrator']
if k... | the_stack_v2_python_sparse | sentinel/discovery/layers/presentation/coordination/create_config.py | alterway/sentinel | train | 0 |
fbf59c87144cded7349c7f078e03a87f0319f63d | [
"users = User.query.all()\nusersJSON = []\nfor u in users:\n usersJSON.append({'id': u.id, 'admin': u.admin})\nreturn {'users': usersJSON}",
"args = usr_parser.parse_args()\nif isinstance(args, current_app.response_class):\n return args\nadmin = False if 'admin' not in args else args['admin']\nif args['uid'... | <|body_start_0|>
users = User.query.all()
usersJSON = []
for u in users:
usersJSON.append({'id': u.id, 'admin': u.admin})
return {'users': usersJSON}
<|end_body_0|>
<|body_start_1|>
args = usr_parser.parse_args()
if isinstance(args, current_app.response_class... | Class for endpoints responsible for providing information about users and creating a new user | Users | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
<|b... | stack_v2_sparse_classes_36k_train_027391 | 5,124 | permissive | [
{
"docstring": "Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new user account endpoint To create, access token and admin p... | 2 | stack_v2_sparse_classes_30k_train_007676 | Implement the Python class `Users` described below.
Class description:
Class for endpoints responsible for providing information about users and creating a new user
Method signatures and docstrings:
- def get(self): Get info of all users endpoint To access, access token and admin permissions are required Returns: obj... | Implement the Python class `Users` described below.
Class description:
Class for endpoints responsible for providing information about users and creating a new user
Method signatures and docstrings:
- def get(self): Get info of all users endpoint To access, access token and admin permissions are required Returns: obj... | 4be6f7d951ba0d707a84a2cf8cbfc36689b85a3c | <|skeleton|>
class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
users = User.que... | the_stack_v2_python_sparse | idlak-server/app/endpoints/user.py | Idlak/idlak | train | 65 |
9ed44e8405a992a194d64ef1dfe95b7da8b63d1b | [
"outString = ''\nunitLen = 8\nfor singleStr in strs:\n strLen = len(singleStr)\n strLenLen = len(str(strLen))\n outString += '0' * (unitLen - strLenLen) + str(strLen)\n outString += singleStr\nreturn outString",
"strList = []\ninputLen = len(s)\nif inputLen > 0:\n unitLen = 8\n curIdx = 0\n w... | <|body_start_0|>
outString = ''
unitLen = 8
for singleStr in strs:
strLen = len(singleStr)
strLenLen = len(str(strLen))
outString += '0' * (unitLen - strLenLen) + str(strLen)
outString += singleStr
return outString
<|end_body_0|>
<|body_st... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
outString... | stack_v2_sparse_classes_36k_train_027392 | 1,253 | permissive | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_007246 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 48a57f6a5d5745199c5685cd2c8f5c4fa293e54a | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
outString = ''
unitLen = 8
for singleStr in strs:
strLen = len(singleStr)
strLenLen = len(str(strLen))
outString += '0' * (unitLen - strLenLen) +... | the_stack_v2_python_sparse | Q02__/71_Encode_and_Decode_Strings/Solution.py | hsclinical/leetcode | train | 0 | |
dc83002818180a7301698d0cdf59d8b35b05bd48 | [
"try:\n return super().emit(record)\nexcept FileNotFoundError:\n return self._emit_safely(record)\nexcept OSError as exception:\n if exception.errno == errno.ESTALE:\n return self._emit_safely(record)\n else:\n raise",
"ATTEMPTS_MAX = 8\nSLEEP_INTERVAL = 0.1\nfor attempt_index in range(A... | <|body_start_0|>
try:
return super().emit(record)
except FileNotFoundError:
return self._emit_safely(record)
except OSError as exception:
if exception.errno == errno.ESTALE:
return self._emit_safely(record)
else:
rai... | Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised exceptions from one or more of these processes. On log... | LogHandlerFileRotateSafe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised ex... | stack_v2_sparse_classes_36k_train_027393 | 17,464 | no_license | [
{
"docstring": "Log the passed logging record in a thread- *and* process-safe manner. Parameters ---------- record : LogRecord Logging record to be logged. Raises ---------- BetseLogRaceException If this method detects but fails to automatically resolve a logging race condition between multiple processes concur... | 2 | stack_v2_sparse_classes_30k_test_000627 | Implement the Python class `LogHandlerFileRotateSafe` described below.
Class description:
Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fa... | Implement the Python class `LogHandlerFileRotateSafe` described below.
Class description:
Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fa... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised exceptions from... | the_stack_v2_python_sparse | betse/util/io/log/conf/logconfhandle.py | R-Stefano/betse-ml | train | 0 |
58e3807195283351bb26e12ad3a8cc09e3bafaea | [
"import collections\ncount = collections.defaultdict(int)\nfor num in nums:\n count[num] += 1\nfor num in nums:\n if count[num] == 1:\n return num\nreturn -1",
"res = 0\nis_neg = 0\nfor i in range(32):\n count = 0\n for num in nums:\n if num >> i & 1:\n count += 1\n if coun... | <|body_start_0|>
import collections
count = collections.defaultdict(int)
for num in nums:
count[num] += 1
for num in nums:
if count[num] == 1:
return num
return -1
<|end_body_0|>
<|body_start_1|>
res = 0
is_neg = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections
count = collecti... | stack_v2_sparse_classes_36k_train_027394 | 1,561 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def singleNum... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
import collections
count = collections.defaultdict(int)
for num in nums:
count[num] += 1
for num in nums:
if count[num] == 1:
return num
retur... | the_stack_v2_python_sparse | 剑指 Offer II 004. 只出现一次的数字.py | yangyuxiang1996/leetcode | train | 0 | |
f2d08c1122e64dfe5dbcad1d2e41b211c0d709e8 | [
"try:\n student = Student.objects.get(pk=pk)\n deserialized = deserialize_student(student)\n return Response({'student': deserialized})\nexcept Student.DoesNotExist:\n return Response({'message': 'THE USER DOES NOT EXIST'})",
"data = request.data\ntry:\n a = Student.objects.get(pk=pk)\nexcept Stude... | <|body_start_0|>
try:
student = Student.objects.get(pk=pk)
deserialized = deserialize_student(student)
return Response({'student': deserialized})
except Student.DoesNotExist:
return Response({'message': 'THE USER DOES NOT EXIST'})
<|end_body_0|>
<|body_st... | StudentDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentDetailView:
def get(self, request, pk):
"""" Get the student detail by looking up its shit"""
<|body_0|>
def post(self, request, pk):
"""' Add to the code -> Update or delete things from the dastabase -> just get what is given and update profile accordingly"""... | stack_v2_sparse_classes_36k_train_027395 | 10,002 | no_license | [
{
"docstring": "\" Get the student detail by looking up its shit",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "' Add to the code -> Update or delete things from the dastabase -> just get what is given and update profile accordingly",
"name": "post",
"signa... | 2 | stack_v2_sparse_classes_30k_train_009934 | Implement the Python class `StudentDetailView` described below.
Class description:
Implement the StudentDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): " Get the student detail by looking up its shit
- def post(self, request, pk): ' Add to the code -> Update or delete things from the... | Implement the Python class `StudentDetailView` described below.
Class description:
Implement the StudentDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): " Get the student detail by looking up its shit
- def post(self, request, pk): ' Add to the code -> Update or delete things from the... | fcbc142c6dd11028819493499d7105b3a0b7995c | <|skeleton|>
class StudentDetailView:
def get(self, request, pk):
"""" Get the student detail by looking up its shit"""
<|body_0|>
def post(self, request, pk):
"""' Add to the code -> Update or delete things from the dastabase -> just get what is given and update profile accordingly"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentDetailView:
def get(self, request, pk):
"""" Get the student detail by looking up its shit"""
try:
student = Student.objects.get(pk=pk)
deserialized = deserialize_student(student)
return Response({'student': deserialized})
except Student.DoesN... | the_stack_v2_python_sparse | user_profiles/views.py | Jray-Tech/virtual_class_backend | train | 0 | |
3a20c79feacddab25b85d703660b81b2740ed03f | [
"self.users_id = set()\nself.tweets_id = list()\nself.users_follow = {}\nself.tweets_dict = {}",
"self.checkMenber(userId)\nself.tweets_id.append(tweetId)\nself.tweets_dict[tweetId] = userId",
"if self.checkMenber(userId):\n count = 0\n News = []\n for tweet in self.tweets_id[::-1]:\n author = s... | <|body_start_0|>
self.users_id = set()
self.tweets_id = list()
self.users_follow = {}
self.tweets_dict = {}
<|end_body_0|>
<|body_start_1|>
self.checkMenber(userId)
self.tweets_id.append(tweetId)
self.tweets_dict[tweetId] = userId
<|end_body_1|>
<|body_start_2|>... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> list:
"""Retrieve the 10 most r... | stack_v2_sparse_classes_36k_train_027396 | 3,205 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 6 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> list... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> list... | b6712c793bbfe443953e7186b5dbd876c01cd9a0 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> list:
"""Retrieve the 10 most r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.users_id = set()
self.tweets_id = list()
self.users_follow = {}
self.tweets_dict = {}
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
sel... | the_stack_v2_python_sparse | 05_leetcode/355.设计推特.py | niceNASA/Python-Foundation-Suda | train | 0 | |
c58a3025a80efdf77f7ac905b12b7c11a02db29d | [
"super(DARTSEvaluater, self).__init__(data_path, model_save_path, genotype, dataset, report_freq, eval_policy, gpu_id, epochs, cutout, 0.5, save_interval, auxiliary_tower, hash_string)\nif dataset == 'cifar10':\n self.model = NetworkCIFAR(EVAL_INIT_CHANNEL, 10, EVAL_LAYERS, self.auxiliary_tower, genotype)\n s... | <|body_start_0|>
super(DARTSEvaluater, self).__init__(data_path, model_save_path, genotype, dataset, report_freq, eval_policy, gpu_id, epochs, cutout, 0.5, save_interval, auxiliary_tower, hash_string)
if dataset == 'cifar10':
self.model = NetworkCIFAR(EVAL_INIT_CHANNEL, 10, EVAL_LAYERS, self... | DARTSEvaluater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DARTSEvaluater:
def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epochs: int=50, cutout: bool=False, save_interval: int=10, auxiliary_tower: bool=False, hash_string: str=None):
... | stack_v2_sparse_classes_36k_train_027397 | 14,047 | no_license | [
{
"docstring": "Evaluate a DARTS-style architecture on benchmark",
"name": "__init__",
"signature": "def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epochs: int=50, cutout: bool=False, save... | 2 | stack_v2_sparse_classes_30k_train_020101 | Implement the Python class `DARTSEvaluater` described below.
Class description:
Implement the DARTSEvaluater class.
Method signatures and docstrings:
- def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epo... | Implement the Python class `DARTSEvaluater` described below.
Class description:
Implement the DARTSEvaluater class.
Method signatures and docstrings:
- def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epo... | 30507e550567259c15d56b2a7b337da02f03b206 | <|skeleton|>
class DARTSEvaluater:
def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epochs: int=50, cutout: bool=False, save_interval: int=10, auxiliary_tower: bool=False, hash_string: str=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DARTSEvaluater:
def __init__(self, data_path: str, model_save_path: str, genotype: Genotype, dataset: str='cifar10', report_freq: int=50, eval_policy: str='last5', gpu_id: int=0, epochs: int=50, cutout: bool=False, save_interval: int=10, auxiliary_tower: bool=False, hash_string: str=None):
"""Evaluate... | the_stack_v2_python_sparse | darts/arch_trainer.py | Tommiyi/nasbowl | train | 0 | |
29c33f3dc01c0db0f1ab62bf51c90274bcb95767 | [
"left, right = (0, len(nums) - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n right = mid - 1\n else:\n left = mid + 1\nreturn None",
"if not nums:\n return 0\nleft, right = (0, len(nums) - 1)\nwhi... | <|body_start_0|>
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binary_search(self, nums, target):
"""二分查找 :param nums: :param target: :return:"""
<|body_0|>
def find_roate_index(self, nums):
"""寻找选择数组的分割点 :param nums: :return:"""
<|body_1|>
def search(self, nums, target):
""":type nums: List[in... | stack_v2_sparse_classes_36k_train_027398 | 2,168 | no_license | [
{
"docstring": "二分查找 :param nums: :param target: :return:",
"name": "binary_search",
"signature": "def binary_search(self, nums, target)"
},
{
"docstring": "寻找选择数组的分割点 :param nums: :return:",
"name": "find_roate_index",
"signature": "def find_roate_index(self, nums)"
},
{
"docstr... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, target): 二分查找 :param nums: :param target: :return:
- def find_roate_index(self, nums): 寻找选择数组的分割点 :param nums: :return:
- def search(self, nums, tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_search(self, nums, target): 二分查找 :param nums: :param target: :return:
- def find_roate_index(self, nums): 寻找选择数组的分割点 :param nums: :return:
- def search(self, nums, tar... | f564806bd8e18831eeb20f2fd4bdd2d4aaa829ce | <|skeleton|>
class Solution:
def binary_search(self, nums, target):
"""二分查找 :param nums: :param target: :return:"""
<|body_0|>
def find_roate_index(self, nums):
"""寻找选择数组的分割点 :param nums: :return:"""
<|body_1|>
def search(self, nums, target):
""":type nums: List[in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binary_search(self, nums, target):
"""二分查找 :param nums: :param target: :return:"""
left, right = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] ... | the_stack_v2_python_sparse | Week 03/id_684/LeetCode_33_684.py | cboopen/algorithm004-04 | train | 2 | |
70ddaab84676a0d72925d35e17cb2c281dc8f967 | [
"menu_domain = [('parent_id', '=', False)]\nif context.get('menu', None):\n menu_domain.append(('name', '=', context.get('menu')))\nreturn self.search(cr, uid, menu_domain, context=context)",
"fields = ['name', 'sequence', 'parent_id', 'action']\nmenu_root_ids = self.get_user_roots(cr, uid, context=context)\nm... | <|body_start_0|>
menu_domain = [('parent_id', '=', False)]
if context.get('menu', None):
menu_domain.append(('name', '=', context.get('menu')))
return self.search(cr, uid, menu_domain, context=context)
<|end_body_0|>
<|body_start_1|>
fields = ['name', 'sequence', 'parent_id'... | ir_ui_menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
<|body_0|>
def load_menu(self, cr, uid, context=None):
"""Loads all menu items (all applications and their s... | stack_v2_sparse_classes_36k_train_027399 | 4,502 | no_license | [
{
"docstring": "Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)",
"name": "get_user_roots",
"signature": "def get_user_roots(self, cr, uid, context=None)"
},
{
"docstring": "Loads all menu items (all applications and their sub-menus). :return: the menu... | 4 | stack_v2_sparse_classes_30k_train_002948 | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def get_user_roots(self, cr, uid, context=None): Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)
- def load_menu(self, cr, uid, co... | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def get_user_roots(self, cr, uid, context=None): Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)
- def load_menu(self, cr, uid, co... | e8c21082c187f4639373b29a7a0905d069d770f2 | <|skeleton|>
class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
<|body_0|>
def load_menu(self, cr, uid, context=None):
"""Loads all menu items (all applications and their s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ir_ui_menu:
def get_user_roots(self, cr, uid, context=None):
"""Return all root menu ids visible for the user. :return: the root menu ids :rtype: list(int)"""
menu_domain = [('parent_id', '=', False)]
if context.get('menu', None):
menu_domain.append(('name', '=', context.ge... | the_stack_v2_python_sparse | pabi_auth_cas/ir_ui_menu.py | pabi2/pb2_addons | train | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.