Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
class Rows(JsonListGenerator):
def __init__(self, data, registry):
super(Rows, self).__init__(data, registry, RowsItemBase)
<|code_end|>
. Use current file imports:
(from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.panels import Panels)
and context including class names, function names, or small code snippets from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/panels.py
# class Panels(JsonListGenerator):
# def __init__(self, data, registry):
# super(Panels, self).__init__(data, registry, PanelsItemBase)
. Output only the next line. | class RowsItemBase(JsonGenerator): |
Given the code snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
class Rows(JsonListGenerator):
def __init__(self, data, registry):
super(Rows, self).__init__(data, registry, RowsItemBase)
class RowsItemBase(JsonGenerator):
pass
class Row(RowsItemBase):
_copy_fields = {'repeat'}
def gen_json_from_data(self, data, context):
row_json = super(Row, self).gen_json_from_data(data, context)
row_json.update({
'title': data.get('title', ''),
'height': data.get('height', '250px'),
'showTitle': data.get('showTitle', False),
'collapse': data.get('collapse', False),
'panels': []
})
<|code_end|>
, generate the next line using the imports in this file:
from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.panels import Panels
and context (functions, classes, or occasionally code) from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/panels.py
# class Panels(JsonListGenerator):
# def __init__(self, data, registry):
# super(Panels, self).__init__(data, registry, PanelsItemBase)
. Output only the next line. | if get_component_type(Panels) in data: |
Given the following code snippet before the placeholder: <|code_start|> 'avg': self.data['legend'].get('avg', False),
'alignAsTable': self.data['legend'].get('alignAsTable', False),
'rightSide': self.data['legend'].get('rightSide', False),
'hideEmpty': self.data['legend'].get('hideEmpty', False),
'hideZero': self.data['legend'].get('hideZero', False),
'sideWidth': self.data['legend'].get('sideWidth', None)
}
if 'tooltip' in self.data:
panel_json['tooltip'] = {
'value_type': self.data['tooltip'].get('value_type', 'individual'),
'shared': self.data['tooltip'].get('shared', False),
}
if 'seriesOverrides' in self.data:
overrides = []
for override in self.data['seriesOverrides']:
for alias, settings in override.items():
to_add = {'alias': alias}
to_add.update(settings)
overrides.append(to_add)
panel_json['seriesOverrides'] = overrides
self._create_component(panel_json, Links, self.data)
if (('leftYAxisLabel' in self.data
or 'grid' in self.data and ('leftMin' in grid_data or 'leftMax' in grid_data))
and ('y_formats' not in self.data)):
panel_json['y_formats'] = ['short', 'short']
panel_json['xaxis'] = self.data.get('xaxis', {'show': True, 'format': 'time'})
self._create_component(panel_json, Yaxes, self.data)
return panel_json
def _create_component(self, panel_json, clazz, data):
<|code_end|>
, predict the next line using imports from the current file:
from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.axes import Yaxes
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.links import Links
from grafana_dashboards.components.targets import Targets
and context including class names, function names, and sometimes code from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/axes.py
# class Yaxes(JsonListGenerator):
# def __init__(self, data, registry):
# super(Yaxes, self).__init__(data, registry, YaxesItemBase)
#
# def gen_json_from_data(self, data, context):
# if len(data) == 1:
# data.append(data[0])
# return super(Yaxes, self).gen_json_from_data(data, context)
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, dict) and len(items) > 1:
# result_list.append(items)
# else:
# super(Yaxes, self).gen_item_json(items, result_list)
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/links.py
# class Links(JsonListGenerator):
# def __init__(self, data, registry):
# super(Links, self).__init__(data, registry, LinksItemBase)
#
# Path: grafana_dashboards/components/targets.py
# class Targets(JsonListGenerator):
# def __init__(self, data, registry):
# super(Targets, self).__init__(data, registry, TargetsItemBase)
#
# def gen_item_json(self, items, result_list):
# try:
# super(Targets, self).gen_item_json(items, result_list)
# except UnregisteredComponentError:
# result_list.append(
# self.registry.create_component(GraphiteTarget, {get_component_type(GraphiteTarget): items}).gen_json()
# )
. Output only the next line. | if get_component_type(clazz) in data: |
Predict the next line for this snippet: <|code_start|> 'min': self.data['legend'].get('min', False),
'max': self.data['legend'].get('max', False),
'current': self.data['legend'].get('current', False),
'total': self.data['legend'].get('total', False),
'avg': self.data['legend'].get('avg', False),
'alignAsTable': self.data['legend'].get('alignAsTable', False),
'rightSide': self.data['legend'].get('rightSide', False),
'hideEmpty': self.data['legend'].get('hideEmpty', False),
'hideZero': self.data['legend'].get('hideZero', False),
'sideWidth': self.data['legend'].get('sideWidth', None)
}
if 'tooltip' in self.data:
panel_json['tooltip'] = {
'value_type': self.data['tooltip'].get('value_type', 'individual'),
'shared': self.data['tooltip'].get('shared', False),
}
if 'seriesOverrides' in self.data:
overrides = []
for override in self.data['seriesOverrides']:
for alias, settings in override.items():
to_add = {'alias': alias}
to_add.update(settings)
overrides.append(to_add)
panel_json['seriesOverrides'] = overrides
self._create_component(panel_json, Links, self.data)
if (('leftYAxisLabel' in self.data
or 'grid' in self.data and ('leftMin' in grid_data or 'leftMax' in grid_data))
and ('y_formats' not in self.data)):
panel_json['y_formats'] = ['short', 'short']
panel_json['xaxis'] = self.data.get('xaxis', {'show': True, 'format': 'time'})
<|code_end|>
with the help of current file imports:
from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.axes import Yaxes
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.links import Links
from grafana_dashboards.components.targets import Targets
and context from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/axes.py
# class Yaxes(JsonListGenerator):
# def __init__(self, data, registry):
# super(Yaxes, self).__init__(data, registry, YaxesItemBase)
#
# def gen_json_from_data(self, data, context):
# if len(data) == 1:
# data.append(data[0])
# return super(Yaxes, self).gen_json_from_data(data, context)
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, dict) and len(items) > 1:
# result_list.append(items)
# else:
# super(Yaxes, self).gen_item_json(items, result_list)
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/links.py
# class Links(JsonListGenerator):
# def __init__(self, data, registry):
# super(Links, self).__init__(data, registry, LinksItemBase)
#
# Path: grafana_dashboards/components/targets.py
# class Targets(JsonListGenerator):
# def __init__(self, data, registry):
# super(Targets, self).__init__(data, registry, TargetsItemBase)
#
# def gen_item_json(self, items, result_list):
# try:
# super(Targets, self).gen_item_json(items, result_list)
# except UnregisteredComponentError:
# result_list.append(
# self.registry.create_component(GraphiteTarget, {get_component_type(GraphiteTarget): items}).gen_json()
# )
, which may contain function names, class names, or code. Output only the next line. | self._create_component(panel_json, Yaxes, self.data) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
class Panels(JsonListGenerator):
def __init__(self, data, registry):
super(Panels, self).__init__(data, registry, PanelsItemBase)
<|code_end|>
. Use current file imports:
from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.axes import Yaxes
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.links import Links
from grafana_dashboards.components.targets import Targets
and context (classes, functions, or code) from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/axes.py
# class Yaxes(JsonListGenerator):
# def __init__(self, data, registry):
# super(Yaxes, self).__init__(data, registry, YaxesItemBase)
#
# def gen_json_from_data(self, data, context):
# if len(data) == 1:
# data.append(data[0])
# return super(Yaxes, self).gen_json_from_data(data, context)
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, dict) and len(items) > 1:
# result_list.append(items)
# else:
# super(Yaxes, self).gen_item_json(items, result_list)
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/links.py
# class Links(JsonListGenerator):
# def __init__(self, data, registry):
# super(Links, self).__init__(data, registry, LinksItemBase)
#
# Path: grafana_dashboards/components/targets.py
# class Targets(JsonListGenerator):
# def __init__(self, data, registry):
# super(Targets, self).__init__(data, registry, TargetsItemBase)
#
# def gen_item_json(self, items, result_list):
# try:
# super(Targets, self).gen_item_json(items, result_list)
# except UnregisteredComponentError:
# result_list.append(
# self.registry.create_component(GraphiteTarget, {get_component_type(GraphiteTarget): items}).gen_json()
# )
. Output only the next line. | class PanelsItemBase(JsonGenerator): |
Next line prediction: <|code_start|> 'threshold2Color': grid_data.get('threshold2Color', 'rgba(234, 112, 112, 0.22)')
}
if 'legend' in self.data:
panel_json['legend'] = {
'show': self.data['legend'].get('show', True),
'values': self.data['legend'].get('values', False),
'min': self.data['legend'].get('min', False),
'max': self.data['legend'].get('max', False),
'current': self.data['legend'].get('current', False),
'total': self.data['legend'].get('total', False),
'avg': self.data['legend'].get('avg', False),
'alignAsTable': self.data['legend'].get('alignAsTable', False),
'rightSide': self.data['legend'].get('rightSide', False),
'hideEmpty': self.data['legend'].get('hideEmpty', False),
'hideZero': self.data['legend'].get('hideZero', False),
'sideWidth': self.data['legend'].get('sideWidth', None)
}
if 'tooltip' in self.data:
panel_json['tooltip'] = {
'value_type': self.data['tooltip'].get('value_type', 'individual'),
'shared': self.data['tooltip'].get('shared', False),
}
if 'seriesOverrides' in self.data:
overrides = []
for override in self.data['seriesOverrides']:
for alias, settings in override.items():
to_add = {'alias': alias}
to_add.update(settings)
overrides.append(to_add)
panel_json['seriesOverrides'] = overrides
<|code_end|>
. Use current file imports:
(from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.axes import Yaxes
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.links import Links
from grafana_dashboards.components.targets import Targets)
and context including class names, function names, or small code snippets from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/axes.py
# class Yaxes(JsonListGenerator):
# def __init__(self, data, registry):
# super(Yaxes, self).__init__(data, registry, YaxesItemBase)
#
# def gen_json_from_data(self, data, context):
# if len(data) == 1:
# data.append(data[0])
# return super(Yaxes, self).gen_json_from_data(data, context)
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, dict) and len(items) > 1:
# result_list.append(items)
# else:
# super(Yaxes, self).gen_item_json(items, result_list)
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/links.py
# class Links(JsonListGenerator):
# def __init__(self, data, registry):
# super(Links, self).__init__(data, registry, LinksItemBase)
#
# Path: grafana_dashboards/components/targets.py
# class Targets(JsonListGenerator):
# def __init__(self, data, registry):
# super(Targets, self).__init__(data, registry, TargetsItemBase)
#
# def gen_item_json(self, items, result_list):
# try:
# super(Targets, self).gen_item_json(items, result_list)
# except UnregisteredComponentError:
# result_list.append(
# self.registry.create_component(GraphiteTarget, {get_component_type(GraphiteTarget): items}).gen_json()
# )
. Output only the next line. | self._create_component(panel_json, Links, self.data) |
Continue the code snippet: <|code_start|>
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
class Panels(JsonListGenerator):
def __init__(self, data, registry):
super(Panels, self).__init__(data, registry, PanelsItemBase)
class PanelsItemBase(JsonGenerator):
pass
class Graph(PanelsItemBase):
_copy_fields = {'stack', 'fill', 'aliasColors', 'leftYAxisLabel', 'bars', 'lines', 'linewidth', 'y_formats',
'x-axis', 'y-axis', 'points', 'pointradius', 'percentage', 'steppedLine', 'repeat',
'repeatDirection', 'decimals', 'minSpan', 'datasource', 'description'}
def gen_json_from_data(self, data, context):
panel_json = super(Graph, self).gen_json_from_data(data, context)
panel_json.update({
'type': 'graph',
'title': self.data.get('title', None),
'span': self.data.get('span', 12),
})
targets = self.data.get('targets', [])
if 'target' in self.data:
targets.append(self.data['target'])
<|code_end|>
. Use current file imports:
from grafana_dashboards.common import get_component_type
from grafana_dashboards.components.axes import Yaxes
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
from grafana_dashboards.components.links import Links
from grafana_dashboards.components.targets import Targets
and context (classes, functions, or code) from other files:
# Path: grafana_dashboards/common.py
# def get_component_type(clazz):
# """
#
# :type clazz: type
# """
# return _all_cap_re.sub(r'\1-\2', _first_cap_re.sub(r'\1-\2', clazz.__name__)).lower()
#
# Path: grafana_dashboards/components/axes.py
# class Yaxes(JsonListGenerator):
# def __init__(self, data, registry):
# super(Yaxes, self).__init__(data, registry, YaxesItemBase)
#
# def gen_json_from_data(self, data, context):
# if len(data) == 1:
# data.append(data[0])
# return super(Yaxes, self).gen_json_from_data(data, context)
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, dict) and len(items) > 1:
# result_list.append(items)
# else:
# super(Yaxes, self).gen_item_json(items, result_list)
#
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
#
# Path: grafana_dashboards/components/links.py
# class Links(JsonListGenerator):
# def __init__(self, data, registry):
# super(Links, self).__init__(data, registry, LinksItemBase)
#
# Path: grafana_dashboards/components/targets.py
# class Targets(JsonListGenerator):
# def __init__(self, data, registry):
# super(Targets, self).__init__(data, registry, TargetsItemBase)
#
# def gen_item_json(self, items, result_list):
# try:
# super(Targets, self).gen_item_json(items, result_list)
# except UnregisteredComponentError:
# result_list.append(
# self.registry.create_component(GraphiteTarget, {get_component_type(GraphiteTarget): items}).gen_json()
# )
. Output only the next line. | self._create_component(panel_json, Targets, {'targets': targets}) |
Based on the snippet: <|code_start|> 'dashboards': [
'dashboard0',
'dashboard1',
'{single}',
'{dict}',
'{list}'
],
'single': 'first',
'list': [
'list0',
'list1'
],
'dict': [
{
'dict0': {
'dict-value': '00'
}
},
{
'dict1': {
'dict-value': '10'
}
}
],
'wrapped': '{single}',
'double-wrapped': '{wrapped}'
}
}
mocked_component = mock.Mock()
registry.get_component = mock.Mock(return_value=mocked_component)
<|code_end|>
, predict the immediate next line with the help of imports:
import mock
from grafana_dashboards.components.projects import Project
and context (classes, functions, sometimes code) from other files:
# Path: grafana_dashboards/components/projects.py
# class Project(ComponentBase):
# def __init__(self, data, registry):
# super(Project, self).__init__(data, registry)
# self._placeholders = [placeholder for dashboard in self._get_dashboard_names()
# for placeholder in get_placeholders(dashboard)]
#
# def _get_dashboard_names(self):
# return self.data.get('dashboards', [])
#
# def get_dashboards(self):
# return [self.registry.get_component(Dashboard, dashboard_name) for dashboard_name in
# self._get_dashboard_names()]
#
# def get_contexts(self, context=None):
# if context is None:
# context = {}
# data = self.data.copy()
# data.update(context)
# return Context.create_context(data, self._placeholders)
. Output only the next line. | project = Project(data, registry) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_project_processor():
dashboard_processor = MagicMock()
<|code_end|>
. Use current file imports:
(import pytest
from mock import patch, MagicMock
from grafana_dashboards.exporter import ProjectProcessor, FileExporter)
and context including class names, function names, or small code snippets from other files:
# Path: grafana_dashboards/exporter.py
# class ProjectProcessor(object):
#
# def __init__(self, dashboard_processors):
# """
#
# :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter]
# """
# super(ProjectProcessor, self).__init__()
# self._dashboard_processors = dashboard_processors
#
# def process_projects(self, projects, parent_context=None):
# """
#
# :type projects: list[grafana_dashboards.components.projects.Project]
# :type parent_context: dict
# """
# for project in projects:
# logger.info("Processing project '%s'", project.name)
# for context in project.get_contexts(parent_context):
# for dashboard in project.get_dashboards():
# json_obj = dashboard.gen_json(context)
# dashboard_name = context.expand_placeholders(dashboard.name)
# for processor in self._dashboard_processors:
# processor.process_dashboard(project.name, dashboard_name, json_obj)
#
# class FileExporter(DashboardExporter):
#
# def __init__(self, output_folder):
# super(FileExporter, self).__init__()
# self._output_folder = output_folder
# if not os.path.exists(self._output_folder):
# os.makedirs(self._output_folder)
# if not os.path.isdir(self._output_folder):
# raise Exception("'{0}' must be a directory".format(self._output_folder))
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data)
# dirname = os.path.join(self._output_folder, project_name)
# try:
# os.makedirs(dirname)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
#
# dashboard_path = os.path.join(dirname, dashboard_name + '.json')
# logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path))
# with open(dashboard_path, 'w') as f:
# json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
. Output only the next line. | processor = ProjectProcessor([dashboard_processor]) |
Predict the next line after this snippet: <|code_start|>
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_project_processor():
dashboard_processor = MagicMock()
processor = ProjectProcessor([dashboard_processor])
project = MagicMock()
context = MagicMock()
dashboard = MagicMock()
project.get_contexts.return_value = [context]
project.get_dashboards.return_value = [dashboard]
parent_context = MagicMock()
# noinspection PyTypeChecker
processor.process_projects([project], parent_context)
project.get_contexts.assert_called_once_with(parent_context)
dashboard.gen_json.assert_called_with(context)
context.expand_placeholders.assert_called_with(dashboard.name)
dashboard_processor.process_dashboard.assert_called_once_with(project.name, context.expand_placeholders(),
dashboard.gen_json())
@patch('grafana_dashboards.exporter.open', create=True)
@patch('json.dump')
@patch('os.makedirs', return_value=True)
@patch('os.path.isdir', return_value=True)
@patch('os.path.exists', return_value=True)
def test_file_exporter(patch_exists, path_isdir, makedirs, json_dump, mock_file):
<|code_end|>
using the current file's imports:
import pytest
from mock import patch, MagicMock
from grafana_dashboards.exporter import ProjectProcessor, FileExporter
and any relevant context from other files:
# Path: grafana_dashboards/exporter.py
# class ProjectProcessor(object):
#
# def __init__(self, dashboard_processors):
# """
#
# :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter]
# """
# super(ProjectProcessor, self).__init__()
# self._dashboard_processors = dashboard_processors
#
# def process_projects(self, projects, parent_context=None):
# """
#
# :type projects: list[grafana_dashboards.components.projects.Project]
# :type parent_context: dict
# """
# for project in projects:
# logger.info("Processing project '%s'", project.name)
# for context in project.get_contexts(parent_context):
# for dashboard in project.get_dashboards():
# json_obj = dashboard.gen_json(context)
# dashboard_name = context.expand_placeholders(dashboard.name)
# for processor in self._dashboard_processors:
# processor.process_dashboard(project.name, dashboard_name, json_obj)
#
# class FileExporter(DashboardExporter):
#
# def __init__(self, output_folder):
# super(FileExporter, self).__init__()
# self._output_folder = output_folder
# if not os.path.exists(self._output_folder):
# os.makedirs(self._output_folder)
# if not os.path.isdir(self._output_folder):
# raise Exception("'{0}' must be a directory".format(self._output_folder))
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data)
# dirname = os.path.join(self._output_folder, project_name)
# try:
# os.makedirs(dirname)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
#
# dashboard_path = os.path.join(dirname, dashboard_name + '.json')
# logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path))
# with open(dashboard_path, 'w') as f:
# json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
. Output only the next line. | exporter = FileExporter('output_folder') |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_elastic_search():
<|code_end|>
. Use current file imports:
import json
from mock import MagicMock
from grafana_dashboards.client.elastic_search import ElasticSearchExporter
and context (classes, functions, or code) from other files:
# Path: grafana_dashboards/client/elastic_search.py
# class ElasticSearchExporter(DashboardExporter):
# def __init__(self, **kwargs):
# super(ElasticSearchExporter, self).__init__()
# self._host = os.getenv('ES_HOST', kwargs.get('host'))
# password = os.getenv('ES_PASSWORD', kwargs.get('password'))
# username = os.getenv('ES_USERNAME', kwargs.get('username'))
# use_kerberos = os.getenv('ES_USE_KERBEROS', kwargs.get('use_kerberos'))
#
# if use_kerberos:
# self._connection = KerberosConnection(self._host)
# else:
# self._connection = BasicAuthConnection(username, password, self._host)
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# super(ElasticSearchExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data)
# body = {'user': 'guest', 'group': 'guest', 'title': dashboard_data['title'], 'tags': dashboard_data['tags'],
# 'dashboard': json.dumps(dashboard_data)}
# logger.info("Uploading dashboard '%s' to %s", dashboard_name, self._host)
# self._connection.make_request('/es/grafana-dash/dashboard/{0}'.format(dashboard_name), body)
. Output only the next line. | exporter = ElasticSearchExporter(host='host', username='username', password='password') |
Using the snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
class Yaxes(JsonListGenerator):
def __init__(self, data, registry):
super(Yaxes, self).__init__(data, registry, YaxesItemBase)
def gen_json_from_data(self, data, context):
if len(data) == 1:
data.append(data[0])
return super(Yaxes, self).gen_json_from_data(data, context)
def gen_item_json(self, items, result_list):
if isinstance(items, dict) and len(items) > 1:
result_list.append(items)
else:
super(Yaxes, self).gen_item_json(items, result_list)
<|code_end|>
, determine the next line of code. You have imports:
from grafana_dashboards.components.base import JsonListGenerator, JsonGenerator
and context (class names, function names, or code) available:
# Path: grafana_dashboards/components/base.py
# class JsonListGenerator(JsonGenerator):
# def __init__(self, data, registry, item_base_class):
# super(JsonListGenerator, self).__init__(data, registry)
# self.component_item_types = [get_component_type(clazz) for clazz in _get_subclasses(item_base_class)]
#
# def gen_json_from_data(self, data, context):
# super(JsonListGenerator, self).gen_json_from_data(data, context)
# result_list = []
# for items in data:
# self.gen_item_json(items, result_list)
# return result_list
#
# def gen_item_json(self, items, result_list):
# if isinstance(items, basestring):
# # this is component without context
# result_list += self.registry.get_component(type(self), items).gen_json()
# else:
# self._gen_item_json_with_context(items, result_list)
#
# def _gen_item_json_with_context(self, items, result_list):
# # TODO add check for dictionary
# for (item_type, item_data) in items.items():
# if item_type not in self.component_item_types:
# # this is named component with context
# for context in Context.create_context(item_data, get_placeholders(item_type)):
# result_list += self.registry.get_component(type(self), item_type).gen_json(context)
# else:
# # this is inplace defined component
# item = self.registry.create_component(item_type, {item_type: item_data}).gen_json()
# if isinstance(item, list):
# result_list += item
# else:
# result_list.append(item)
#
# class JsonGenerator(ComponentBase):
#
# _copy_fields = set()
#
# def gen_json(self, context=Context()):
# return self.gen_json_from_data(context.expand_placeholders(self.data), context)
#
# def gen_json_from_data(self, data, context):
# component_type = get_component_type(type(self))
# if self.name:
# logger.debug("Processing component '%s' with name '%s' from template '%s'",
# component_type, context.expand_placeholders(self.name), self.name)
# else:
# logger.debug("Processing anonymous component '%s'", component_type)
# json = {}
# for field in self._copy_fields:
# if field in data:
# json[field] = data[field]
# return json
. Output only the next line. | class YaxesItemBase(JsonGenerator): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_dict():
<|code_end|>
, predict the immediate next line with the help of imports:
from grafana_dashboards.context import DictDefaultingToPlaceholder, Context
and context (classes, functions, sometimes code) from other files:
# Path: grafana_dashboards/context.py
# class DictDefaultingToPlaceholder(dict):
# def __missing__(self, key):
# return '{' + key + '}'
#
# class Context(object):
#
# _pattern = re.compile('{.*}')
#
# def __init__(self, context=None):
# super(Context, self).__init__()
# if not context:
# self._context = None
# else:
# self._context = DictDefaultingToPlaceholder(context)
#
# def expand_placeholders(self, to_expand):
# """
#
# :rtype : dict
# """
# if not self._context:
# return to_expand
#
# if isinstance(to_expand, basestring):
# (result, to_expand) = self._expand(to_expand)
# while result != to_expand:
# (result, to_expand) = self._expand(result)
# if isinstance(result, basestring):
# return string.Formatter().vformat(result, (), self._context)
# else:
# return result
# elif isinstance(to_expand, list):
# return [self.expand_placeholders(value) for value in to_expand]
# elif isinstance(to_expand, dict):
# return dict([(key, self.expand_placeholders(value)) for (key, value) in to_expand.items()])
# else:
# return to_expand
#
# def _expand(self, to_expand):
# if not isinstance(to_expand, basestring):
# return to_expand, to_expand
# elif self._pattern.match(to_expand) and to_expand[1:-1] in self._context:
# return self._context[to_expand[1:-1]], to_expand
# escaped = to_expand.replace('{{', '{{{{').replace('}}', '}}}}')
# return string.Formatter().vformat(escaped, (), self._context), to_expand
#
# def __str__(self):
# return str(self._context)
#
# @staticmethod
# def create_context(data, keys_to_expand=None):
# return (Context(Context(context).expand_placeholders(context))
# for context in ContextExpander(keys_to_expand).create_context(None, data))
. Output only the next line. | d = DictDefaultingToPlaceholder({'a': 1}) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_dict():
d = DictDefaultingToPlaceholder({'a': 1})
assert d['a'] == 1
assert d['b'] == '{b}'
def test_context_expands_scalar_value():
data = {
'single': 'first',
'wrapped': '{single}',
'double-wrapped': '{wrapped}'
}
<|code_end|>
. Use current file imports:
from grafana_dashboards.context import DictDefaultingToPlaceholder, Context
and context (classes, functions, or code) from other files:
# Path: grafana_dashboards/context.py
# class DictDefaultingToPlaceholder(dict):
# def __missing__(self, key):
# return '{' + key + '}'
#
# class Context(object):
#
# _pattern = re.compile('{.*}')
#
# def __init__(self, context=None):
# super(Context, self).__init__()
# if not context:
# self._context = None
# else:
# self._context = DictDefaultingToPlaceholder(context)
#
# def expand_placeholders(self, to_expand):
# """
#
# :rtype : dict
# """
# if not self._context:
# return to_expand
#
# if isinstance(to_expand, basestring):
# (result, to_expand) = self._expand(to_expand)
# while result != to_expand:
# (result, to_expand) = self._expand(result)
# if isinstance(result, basestring):
# return string.Formatter().vformat(result, (), self._context)
# else:
# return result
# elif isinstance(to_expand, list):
# return [self.expand_placeholders(value) for value in to_expand]
# elif isinstance(to_expand, dict):
# return dict([(key, self.expand_placeholders(value)) for (key, value) in to_expand.items()])
# else:
# return to_expand
#
# def _expand(self, to_expand):
# if not isinstance(to_expand, basestring):
# return to_expand, to_expand
# elif self._pattern.match(to_expand) and to_expand[1:-1] in self._context:
# return self._context[to_expand[1:-1]], to_expand
# escaped = to_expand.replace('{{', '{{{{').replace('}}', '}}}}')
# return string.Formatter().vformat(escaped, (), self._context), to_expand
#
# def __str__(self):
# return str(self._context)
#
# @staticmethod
# def create_context(data, keys_to_expand=None):
# return (Context(Context(context).expand_placeholders(context))
# for context in ContextExpander(keys_to_expand).create_context(None, data))
. Output only the next line. | contexts = [context for context in Context.create_context(data, keys_to_expand=('expanded-list', 'expanded-dict'))] |
Given the following code snippet before the placeholder: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
logger = logging.getLogger(__name__)
class GrafanaExporter(DashboardExporter):
def __init__(self, **kwargs):
super(GrafanaExporter, self).__init__()
self._host = os.getenv('GRAFANA_HOST', kwargs.get('host'))
password = os.getenv('GRAFANA_PASSWORD', kwargs.get('password'))
username = os.getenv('GRAFANA_USERNAME', kwargs.get('username'))
auth_token = os.getenv('GRAFANA_TOKEN', kwargs.get('token'))
use_kerberos = os.getenv('GRAFANA_USE_KERBEROS', kwargs.get('use_kerberos'))
if use_kerberos:
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
from grafana_dashboards.client.connection import KerberosConnection, BearerAuthConnection, BasicAuthConnection
from grafana_dashboards.exporter import DashboardExporter
and context including class names, function names, and sometimes code from other files:
# Path: grafana_dashboards/client/connection.py
# class KerberosConnection(object):
# def __init__(self, host):
# logger.debug('Creating new kerberos connection with host=%s', host)
# self._host = host
#
# def make_request(self, uri, body=None):
# response = requests.post('{0}{1}'.format(self._host, uri), json=body, auth=HTTPKerberosAuth(), verify=False)
# return response.json()
#
# class BearerAuthConnection(BaseConnection):
# def __init__(self, token, host, debug=0):
# logger.debug('Creating new connection with token=%s host=%s', token[:5], host)
#
# super(BearerAuthConnection, self).__init__(host, 'Bearer %s' % token.strip(), debug)
#
# class BasicAuthConnection(BaseConnection):
# def __init__(self, username, password, host, debug=0):
# logger.debug('Creating new connection with username=%s host=%s', username, host)
#
# base64string = base64.encodestring(('%s:%s' % (username, password)).encode('utf-8')).replace(b'\n', b'')
#
# super(BasicAuthConnection, self).__init__(host, b'Basic ' + base64string, debug)
#
# Path: grafana_dashboards/exporter.py
# class DashboardExporter(object):
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# pass
. Output only the next line. | self._connection = KerberosConnection(self._host) |
Predict the next line after this snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
logger = logging.getLogger(__name__)
class GrafanaExporter(DashboardExporter):
def __init__(self, **kwargs):
super(GrafanaExporter, self).__init__()
self._host = os.getenv('GRAFANA_HOST', kwargs.get('host'))
password = os.getenv('GRAFANA_PASSWORD', kwargs.get('password'))
username = os.getenv('GRAFANA_USERNAME', kwargs.get('username'))
auth_token = os.getenv('GRAFANA_TOKEN', kwargs.get('token'))
use_kerberos = os.getenv('GRAFANA_USE_KERBEROS', kwargs.get('use_kerberos'))
if use_kerberos:
self._connection = KerberosConnection(self._host)
elif auth_token:
<|code_end|>
using the current file's imports:
import logging
import os
from grafana_dashboards.client.connection import KerberosConnection, BearerAuthConnection, BasicAuthConnection
from grafana_dashboards.exporter import DashboardExporter
and any relevant context from other files:
# Path: grafana_dashboards/client/connection.py
# class KerberosConnection(object):
# def __init__(self, host):
# logger.debug('Creating new kerberos connection with host=%s', host)
# self._host = host
#
# def make_request(self, uri, body=None):
# response = requests.post('{0}{1}'.format(self._host, uri), json=body, auth=HTTPKerberosAuth(), verify=False)
# return response.json()
#
# class BearerAuthConnection(BaseConnection):
# def __init__(self, token, host, debug=0):
# logger.debug('Creating new connection with token=%s host=%s', token[:5], host)
#
# super(BearerAuthConnection, self).__init__(host, 'Bearer %s' % token.strip(), debug)
#
# class BasicAuthConnection(BaseConnection):
# def __init__(self, username, password, host, debug=0):
# logger.debug('Creating new connection with username=%s host=%s', username, host)
#
# base64string = base64.encodestring(('%s:%s' % (username, password)).encode('utf-8')).replace(b'\n', b'')
#
# super(BasicAuthConnection, self).__init__(host, b'Basic ' + base64string, debug)
#
# Path: grafana_dashboards/exporter.py
# class DashboardExporter(object):
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# pass
. Output only the next line. | self._connection = BearerAuthConnection(auth_token, self._host) |
Given the following code snippet before the placeholder: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
logger = logging.getLogger(__name__)
class GrafanaExporter(DashboardExporter):
def __init__(self, **kwargs):
super(GrafanaExporter, self).__init__()
self._host = os.getenv('GRAFANA_HOST', kwargs.get('host'))
password = os.getenv('GRAFANA_PASSWORD', kwargs.get('password'))
username = os.getenv('GRAFANA_USERNAME', kwargs.get('username'))
auth_token = os.getenv('GRAFANA_TOKEN', kwargs.get('token'))
use_kerberos = os.getenv('GRAFANA_USE_KERBEROS', kwargs.get('use_kerberos'))
if use_kerberos:
self._connection = KerberosConnection(self._host)
elif auth_token:
self._connection = BearerAuthConnection(auth_token, self._host)
else:
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
from grafana_dashboards.client.connection import KerberosConnection, BearerAuthConnection, BasicAuthConnection
from grafana_dashboards.exporter import DashboardExporter
and context including class names, function names, and sometimes code from other files:
# Path: grafana_dashboards/client/connection.py
# class KerberosConnection(object):
# def __init__(self, host):
# logger.debug('Creating new kerberos connection with host=%s', host)
# self._host = host
#
# def make_request(self, uri, body=None):
# response = requests.post('{0}{1}'.format(self._host, uri), json=body, auth=HTTPKerberosAuth(), verify=False)
# return response.json()
#
# class BearerAuthConnection(BaseConnection):
# def __init__(self, token, host, debug=0):
# logger.debug('Creating new connection with token=%s host=%s', token[:5], host)
#
# super(BearerAuthConnection, self).__init__(host, 'Bearer %s' % token.strip(), debug)
#
# class BasicAuthConnection(BaseConnection):
# def __init__(self, username, password, host, debug=0):
# logger.debug('Creating new connection with username=%s host=%s', username, host)
#
# base64string = base64.encodestring(('%s:%s' % (username, password)).encode('utf-8')).replace(b'\n', b'')
#
# super(BasicAuthConnection, self).__init__(host, b'Basic ' + base64string, debug)
#
# Path: grafana_dashboards/exporter.py
# class DashboardExporter(object):
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# pass
. Output only the next line. | self._connection = BasicAuthConnection(username, password, self._host) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright 2015-2019 grafana-dashboard-builder contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
logger = logging.getLogger(__name__)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
from grafana_dashboards.client.connection import KerberosConnection, BearerAuthConnection, BasicAuthConnection
from grafana_dashboards.exporter import DashboardExporter
and context (class names, function names, or code) available:
# Path: grafana_dashboards/client/connection.py
# class KerberosConnection(object):
# def __init__(self, host):
# logger.debug('Creating new kerberos connection with host=%s', host)
# self._host = host
#
# def make_request(self, uri, body=None):
# response = requests.post('{0}{1}'.format(self._host, uri), json=body, auth=HTTPKerberosAuth(), verify=False)
# return response.json()
#
# class BearerAuthConnection(BaseConnection):
# def __init__(self, token, host, debug=0):
# logger.debug('Creating new connection with token=%s host=%s', token[:5], host)
#
# super(BearerAuthConnection, self).__init__(host, 'Bearer %s' % token.strip(), debug)
#
# class BasicAuthConnection(BaseConnection):
# def __init__(self, username, password, host, debug=0):
# logger.debug('Creating new connection with username=%s host=%s', username, host)
#
# base64string = base64.encodestring(('%s:%s' % (username, password)).encode('utf-8')).replace(b'\n', b'')
#
# super(BasicAuthConnection, self).__init__(host, b'Basic ' + base64string, debug)
#
# Path: grafana_dashboards/exporter.py
# class DashboardExporter(object):
#
# def process_dashboard(self, project_name, dashboard_name, dashboard_data):
# pass
. Output only the next line. | class GrafanaExporter(DashboardExporter): |
Predict the next line after this snippet: <|code_start|> "nargs": "*",
"help":
"""Optional identifiers for additional problems from
contest specified by previous argument. Identifiers
can be either:
- problem's ID
- problem's index (counting from 1)
""",
"metavar": "PROBLEM"
}
},
]
def get_pargs_pack_cli():
"""Returns CLI parse arguments.
"""
return _pargs_pack_cli
# Parser notes.
_parser_cli_description = \
"""To execute special command that doesn't fetch remote data run:
hac (--help | --version | --copy-config)
To execute command that fetches remote data and processes it run:
hac [options...] ({0}) (CONTEST | PROBLEM) [PROBLEM [PROBLEM ...]]
<|code_end|>
using the current file's imports:
import os
import argparse
from hac.commands import app_commands
and any relevant context from other files:
# Path: hac/commands.py
# def _command_prep(**args):
# def _command_show(**args):
. Output only the next line. | """.format(" | ".join(sorted(app_commands.keys()))) |
Using the snippet: <|code_start|> xpath_problem_name = '//*[@id="problem-name"]/text()'
xpath_problem_time = '//*[@id="problem-meta"]/tbody/tr[3]/td[2]/text()'
xpath_problem_source = '//*[@id="problem-meta"]/tbody/tr[4]/td[2]/text()'
xpath_problem_memory = '//*[@id="problem-meta"]/tbody/tr[5]/td[2]/text()'
xpath_problem_ins_outs = '//*[@id="problem-body"]//pre/text()'
# Proxy for HTTP requests (handles request caching during single run of the program).
_proxy = RequestsCache()
def __init__(self):
self.url = "www.spoj.com"
self.name = "Sphere online judge"
self.id = "spoj"
self.time_limit_ms = None
self.memory_limit_kbyte = None
self.source_limit_kbyte = None
self._info = "[SiteSpoj] Fetching only a subset of problems is supported!"
def match_contest(self, conf):
"""Overridden.
"""
return SiteSpoj.url_contest
def get_contest(self, url):
"""Overridden.
"""
<|code_end|>
, determine the next line of code. You have imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (class names, function names, or code) available:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | contest = Contest() |
Here is a snippet: <|code_start|> """
url_template_problem = SiteSpoj.url_contest + SiteSpoj.url_template_suffix_problem
ids = []
# Match single problem from 'location'.
location = urlparse(conf['location']).path or '/'
tokens = SiteSpoj.pattern_contest.search(location)
if tokens is not None:
id_raw = tokens.group('PROBLEM')
if id_raw:
ids.append(id_raw.upper())
# Match potentially multiple problems from 'problems'.
for problem in conf['problems']:
tokens = SiteSpoj.pattern_problem.findall(problem)
id_raw = tokens and tokens[-1]
if id_raw:
ids.append(id_raw.upper())
# Notify about selected but non-available problems.
urls = [url_template_problem.format(id) for id in ids]
return sorted(urls)
def get_problems(self, urls):
"""Overridden.
"""
problems = []
for url in urls:
<|code_end|>
. Write the next line using the current file imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
, which may include functions, classes, or code. Output only the next line. | problem = Problem() |
Here is a snippet: <|code_start|> if page.status_code == 200:
t = html.fromstring(page.text)
# - problem name,
e = t.xpath(SiteSpoj.xpath_problem_name)
problem.name = (e and str(e[0])) or None
# - problem time limit,
e = t.xpath(SiteSpoj.xpath_problem_time)
p = e and e[0].strip()[:-1] # remove whitespace characters and 's' at the end
problem.time_limit_ms = p and float(p) * 1000
# - problem source limit,
e = t.xpath(SiteSpoj.xpath_problem_source)
p = e and e[0].strip()[:-1] # remove whitespace characters and 'B' at the end
problem.source_limit_kbyte = p and float(p) / 1000
# - problem memory limit,
e = t.xpath(SiteSpoj.xpath_problem_memory)
p = e and e[0].strip()[:-2] # remove whitespace characters and 'MB' at the end
problem.memory_limit_kbyte = p and float(p) * 2**10
# - test inputs and outputs.
e = t.xpath(SiteSpoj.xpath_problem_ins_outs)
problem.inputs = [i.strip() for i in e[0:][::2]]
problem.outputs = [o.strip() for o in e[1:][::2]]
if (problem.name and
problem.time_limit_ms and
problem.source_limit_kbyte and
problem.memory_limit_kbyte and
problem.inputs and
problem.outputs):
problems.append(problem)
else:
<|code_end|>
. Write the next line using the current file imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
, which may include functions, classes, or code. Output only the next line. | warn('Problem "' + problem.id + '" not fetched successfully!') |
Based on the snippet: <|code_start|> >>> SiteSpoj.pattern_contest.search(path2).group("PROBLEM")
'BOOKS1'
>>> path3 = ""
>>> SiteSpoj.pattern_contest.search(path3) is None
True
>>> path4 = "/"
>>> SiteSpoj.pattern_contest.search(path4) is None
True
"""
# Regex patterns.
pattern_contest = re.compile(
r"(/problems)?/(?P<PROBLEM>[a-zA-Z0-9]+)" # (mandatory) problem identifier
)
pattern_problem = re.compile(r"[a-zA-Z0-9]+")
# URL templates.
url_contest = "http://www.spoj.com"
url_template_suffix_problem = "/problems/{0}"
# Xpath selectors.
xpath_problem_name = '//*[@id="problem-name"]/text()'
xpath_problem_time = '//*[@id="problem-meta"]/tbody/tr[3]/td[2]/text()'
xpath_problem_source = '//*[@id="problem-meta"]/tbody/tr[4]/td[2]/text()'
xpath_problem_memory = '//*[@id="problem-meta"]/tbody/tr[5]/td[2]/text()'
xpath_problem_ins_outs = '//*[@id="problem-body"]//pre/text()'
# Proxy for HTTP requests (handles request caching during single run of the program).
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (classes, functions, sometimes code) from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | _proxy = RequestsCache() |
Using the snippet: <|code_start|> selected_ids.append(available_ids[idx])
return sorted(set(selected_ids))
def __init__(self):
self.url = "www.codechef.com"
self.name = "CodeChef"
self.id = "codechef"
self.time_limit_ms = None
self.memory_limit_kbyte = 262144
self.source_limit_kbyte = 50
self._info = "[SiteCodeChef] Fetching test inputs/outputs not supported!"
def match_contest(self, conf):
"""Overridden.
"""
location = urlparse(conf["location"]).path or "/"
tokens = SiteCodeChef.pattern_contest.search(location)
contest_id = "404" if tokens is None else tokens.group("CONTEST")
return SiteCodeChef.url_template_contest.format(contest_id.upper())
def get_contest(self, url):
"""Overridden.
"""
url_path = urlparse(url).path
assert url_path
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (class names, function names, or code) available:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | contest = Contest() |
Continue the code snippet: <|code_start|> return []
ids_selected = []
# Match single problem from 'location'.
location = urlparse(conf["location"]).path or "/"
tokens = SiteCodeChef.pattern_contest.search(location)
if tokens is not None:
problem = tokens.group("PROBLEM")
if problem is not None:
ids_selected.append(problem)
# Match potentially multiple problems from 'problems'.
for problem in conf["problems"]:
tokens = SiteCodeChef.pattern_problem.findall(problem)
ids_selected.extend(tokens)
# If no problems are successfully manually selected, select them all.
if not ids_selected:
ids = ids_available
else:
ids = SiteCodeChef.get_problem_ids(ids_selected, ids_available)
return [url_template_problem.format(id) for id in ids]
def get_problems(self, urls):
"""Overridden.
"""
problems = []
for url in urls:
<|code_end|>
. Use current file imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (classes, functions, or code) from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | problem = Problem() |
Next line prediction: <|code_start|> tokens = SiteCodeChef.pattern_contest.search(url_path)
contest.id = tokens.group("CONTEST")
page = SiteCodeChef._proxy.get(url)
# Data from web:
# - contest name.
if page.status_code == 200:
t = html.fromstring(page.text)
e = t.xpath(SiteCodeChef.xpath_contest_name)
contest.name = (e and str(e[0])) or ""
return contest
def match_problems(self, conf):
"""Overridden.
"""
url_contest = self.match_contest(conf)
url_template_problem = url_contest + SiteCodeChef.url_template_suffix_problem
page = SiteCodeChef._proxy.get(url_contest)
# Data from web:
# - available problem ids.
if page.status_code == 200:
t = html.fromstring(page.text)
e = t.xpath(SiteCodeChef.xpath_problem_ids)
ids_available = [str(e.strip()) for e in e]
else:
<|code_end|>
. Use current file imports:
(import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache)
and context including class names, function names, or small code snippets from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | warn('Unable to fetch: ' + url_contest) |
Using the snippet: <|code_start|> >>> SiteCodeChef.pattern_contest.search(path3) is None
True
>>> path4 = "/"
>>> SiteCodeChef.pattern_contest.search(path4) is None
True
"""
# Regex patterns.
pattern_contest = re.compile(
r"/(?P<CONTEST>[a-zA-Z0-9]+)" # (mandatory) contest identifier
r"(/(problems/)?(?P<PROBLEM>[a-zA-Z0-9]+))?" # (optional) problem identifier
)
pattern_problem = re.compile(r"[a-zA-Z0-9]+")
# URL templates.
url_template_contest = "https://www.codechef.com/{0}"
url_template_suffix_problem = "/problems/{0}"
# Xpath selectors.
xpath_contest_name = '/html/head/title/text()'
xpath_problem_ids = '//*[@class="problems"]//*[@class="problemrow"]//*[substring(@title,1,6) = "Submit"]/text()'
xpath_problem_name = '//*[@id="pageContent"]//*[@class="header"]//*[@class="title"]/text()' #TODO fix
xpath_problem_time = '//*[@id="pageContent"]//*[@class="time-limit"]/text()' #TODO fix
xpath_problem_memory = '//*[@id="pageContent"]//*[@class="memory-limit"]/text()' #TODO fix
xpath_problem_ins = '//*[@id="pageContent"]//*[@class="sample-tests"]//*[@class="input"]//pre' #TODO fix
xpath_problem_outs = '//*[@id="pageContent"]//*[@class="sample-tests"]//*[@class="output"]//pre' #TODO fix
# Proxy for HTTP requests (handles request caching during single run of the program).
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (class names, function names, or code) available:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | _proxy = RequestsCache() |
Given the following code snippet before the placeholder: <|code_start|> # URL templates.
url_template_contest = "http://localhost/{0}"
url_template_suffix_problem = "/{0}"
def __init__(self):
self.url = "localhost"
self.name = "Local"
self.id = "local"
self.time_limit_ms = None
self.memory_limit_kbyte = None
self.source_limit_kbyte = None
self._info = None
def match_contest(self, conf):
"""Overridden.
"""
location = urlparse(conf['location']).path or '/'
tokens = SiteLocal.pattern_contest.search(location)
contest_id = 'local-contest' if tokens is None else tokens.group('CONTEST')
return SiteLocal.url_template_contest.format(contest_id)
def get_contest(self, url):
"""Overridden.
"""
url_path = urlparse(url).path
assert url_path
<|code_end|>
, predict the next line using imports from the current file:
import re
import sys
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
and context including class names, function names, and sometimes code from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
. Output only the next line. | contest = Contest() |
Given the code snippet: <|code_start|>
def match_problems(self, conf):
"""Overridden.
"""
url_contest = self.match_contest(conf)
url_template_problem = url_contest + SiteLocal.url_template_suffix_problem
urls = []
# Match single problem from 'location'.
location = urlparse(conf['location']).path or '/'
tokens = SiteLocal.pattern_contest.search(location)
problem_id = tokens and tokens.group('PROBLEM')
if problem_id:
urls.append(url_template_problem.format(problem_id))
# Match potentially multiple problems from 'problems'.
for problem in conf['problems']:
tokens = SiteLocal.pattern_problem.findall(problem)
problem_id = tokens and tokens[-1]
if problem_id:
urls.append(url_template_problem.format(problem_id))
return urls
def get_problems(self, urls):
"""Overridden.
"""
problems = []
for url in urls:
<|code_end|>
, generate the next line using the imports in this file:
import re
import sys
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
and context (functions, classes, or occasionally code) from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
. Output only the next line. | problem = Problem() |
Continue the code snippet: <|code_start|>
# Xpath selectors.
xpath_problem_name = '//h1/text()'
xpath_problem_ins = '//*[@id="sample-dataset"]/following::div[1]//pre/text()'
xpath_problem_outs = '//*[@id="sample-output"]/following::div[1]//pre/text()'
# Proxy for HTTP requests (handles request caching during single run of the program).
_proxy = RequestsCache()
def __init__(self):
self.url = "rosalind.info"
self.name = "Rosalind"
self.id = "rosalind"
self.time_limit_ms = None
self.memory_limit_kbyte = None
self.source_limit_kbyte = None
self._info = None
def match_contest(self, conf):
"""Overridden.
"""
return SiteRosalind.url_contest
def get_contest(self, url):
"""Overridden.
"""
<|code_end|>
. Use current file imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (classes, functions, or code) from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | contest = Contest() |
Predict the next line after this snippet: <|code_start|> url_template_problem = (SiteRosalind.url_contest +
SiteRosalind.url_template_suffix_problem)
ids = []
# Match single problem from 'location'.
location = urlparse(conf['location']).path or '/'
tokens = SiteRosalind.pattern_contest.search(location)
if tokens is not None:
id_raw = tokens.group('PROBLEM')
if id_raw:
ids.append(id_raw.lower())
# Match potentially multiple problems from 'problems'.
for problem in conf['problems']:
tokens = SiteRosalind.pattern_problem.findall(problem)
id_raw = tokens and tokens[-1]
if id_raw:
ids.append(id_raw.lower())
# Notify about selected but non-available problems.
urls = [url_template_problem.format(id) for id in ids]
return sorted(urls)
def get_problems(self, urls):
"""Overridden.
"""
problems = []
for url in urls:
<|code_end|>
using the current file's imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and any relevant context from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | problem = Problem() |
Given the following code snippet before the placeholder: <|code_start|> problems = []
for url in urls:
problem = Problem()
problem.url = url
url_path = urlparse(url).path
assert url_path
tokens = SiteRosalind.pattern_contest.search(url_path)
problem.id = tokens.group('PROBLEM')
assert problem.id
page = SiteRosalind._proxy.get(url)
# Data from web (for each problem):
if page.status_code == 200:
t = html.fromstring(page.text)
# - problem name,
e = t.xpath(SiteRosalind.xpath_problem_name)
problem.name = (e and str(e[0]).strip()) or None
# - test input, (single fetched)
e = t.xpath(SiteRosalind.xpath_problem_ins)
problem.inputs = e and [str(e[0]).strip()]
# - test outputs, (single fetched)
e = t.xpath(SiteRosalind.xpath_problem_outs)
problem.outputs = e and [str(e[0]).strip()]
if (problem.name and
problem.inputs and
problem.outputs):
problems.append(problem)
else:
<|code_end|>
, predict the next line using imports from the current file:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context including class names, function names, and sometimes code from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | warn('Problem "' + problem.id + '" does not exist on Rosalind!') |
Given snippet: <|code_start|> >>> path2 = "/wfmd/"
>>> SiteRosalind.pattern_contest.search(path2).group("PROBLEM")
'wfmd'
>>> path3 = ""
>>> SiteRosalind.pattern_contest.search(path3) is None
True
>>> path4 = "/"
>>> SiteRosalind.pattern_contest.search(path4) is None
True
"""
# Regex patterns.
pattern_contest = re.compile(
r"(/problems)?/(?P<PROBLEM>[a-zA-Z]+)" # (mandatory) problem identifier
r"(/)?" # (optional) slash
)
pattern_problem = re.compile(r"[a-zA-Z]+")
# URL templates.
url_contest = "http://rosalind.info"
url_template_suffix_problem = "/problems/{0}/"
# Xpath selectors.
xpath_problem_name = '//h1/text()'
xpath_problem_ins = '//*[@id="sample-dataset"]/following::div[1]//pre/text()'
xpath_problem_outs = '//*[@id="sample-output"]/following::div[1]//pre/text()'
# Proxy for HTTP requests (handles request caching during single run of the program).
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
which might include code, classes, or functions. Output only the next line. | _proxy = RequestsCache() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
"""Data-structures definitons for:
- web-sites
- contests
- problems
"""
# -- Dynamic data (plugins) ---------------------------------------------------
class ISiteRegistry(ABCMeta):
"""Dynamic registry of sites (plugin architecture).
"""
sites = []
def __init__(cls, name, bases, attrs):
if name != 'ISite':
ISiteRegistry.sites.append(cls)
<|code_end|>
, determine the next line of code. You have imports:
from abc import ABCMeta, abstractmethod
from hac.util_common import with_metaclass
import hac
and context (class names, function names, or code) available:
# Path: hac/util_common.py
# def with_metaclass(mcls):
# def decorator(cls):
# body = vars(cls).copy()
# # Clean out class body.
# body.pop('__dict__', None)
# body.pop('__weakref__', None)
# return mcls(cls.__name__, cls.__bases__, body)
# return decorator
. Output only the next line. | @with_metaclass(ISiteRegistry) |
Predict the next line after this snippet: <|code_start|> return id_out
return None
def __init__(self):
self.url = "codeforces.com"
self.name = "Codeforces"
self.id = "codeforces"
self.time_limit_ms = None
self.memory_limit_kbyte = None
self.source_limit_kbyte = 64
self._info = None
def match_contest(self, conf):
"""Overridden.
"""
location = urlparse(conf['location']).path or '/'
tokens = SiteCodeforces.pattern_contest.search(location)
contest_id = "999999" if tokens is None else tokens.group('CONTEST')
return SiteCodeforces.url_template_contest.format(contest_id)
def get_contest(self, url):
"""Overridden.
"""
url_path = urlparse(url).path
assert url_path
<|code_end|>
using the current file's imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and any relevant context from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | contest = Contest() |
Using the snippet: <|code_start|> ids.append(id_problem)
# Match potentially multiple problems from 'problems'.
for problem in conf['problems']:
tokens = SiteCodeforces.pattern_problem.findall(problem)
id_raw = tokens and tokens[-1]
id_problem = SiteCodeforces.resolve_problem_id(id_raw)
if id_problem:
ids.append(id_problem)
# If no problems are successfully manually selected, select them all.
if not ids:
ids = ids_available
# Notify about selected but non-available problems.
urls = []
for id in ids:
if id in ids_available:
urls.append(url_template_problem.format(id))
else:
warn('Problem "' + id + '" does not exist in ' + url_contest)
return sorted(urls)
def get_problems(self, urls):
"""Overridden.
"""
problems = []
for url in urls:
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context (class names, function names, or code) available:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
. Output only the next line. | problem = Problem() |
Given snippet: <|code_start|> ids_available = [str(e.strip()) for e in e]
ids = []
# Match single problem from 'location'.
location = urlparse(conf['location']).path or '/'
tokens = SiteCodeforces.pattern_contest.search(location)
if tokens is not None:
id_raw = tokens.group('PROBLEM')
id_problem = SiteCodeforces.resolve_problem_id(id_raw)
if id_problem:
ids.append(id_problem)
# Match potentially multiple problems from 'problems'.
for problem in conf['problems']:
tokens = SiteCodeforces.pattern_problem.findall(problem)
id_raw = tokens and tokens[-1]
id_problem = SiteCodeforces.resolve_problem_id(id_raw)
if id_problem:
ids.append(id_problem)
# If no problems are successfully manually selected, select them all.
if not ids:
ids = ids_available
# Notify about selected but non-available problems.
urls = []
for id in ids:
if id in ids_available:
urls.append(url_template_problem.format(id))
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
which might include code, classes, or functions. Output only the next line. | warn('Problem "' + id + '" does not exist in ' + url_contest) |
Predict the next line for this snippet: <|code_start|> >>> SiteCodeforces.pattern_contest.search(path4) is None
True
>>> path5 = "/425/C"
>>> SiteCodeforces.pattern_contest.search(path5).group("PROBLEM")
'C'
"""
# Regex patterns.
pattern_contest = re.compile(
r"(/contest)?" # (optional) '/contest' prefix
r"/(?P<CONTEST>[0-9]+)" # (mandatory) contest identifier
r"((/problem)?/(?P<PROBLEM>[a-zA-Z0-9]+))?" # (optional) problem identifier
)
pattern_problem = re.compile(r"[a-zA-Z0-9]+")
# URL templates.
url_template_contest = "http://codeforces.com/contest/{0}"
url_template_suffix_problem = "/problem/{0}"
# Xpath selectors.
xpath_contest_name = '//*[@id="sidebar"]//a[contains(@href, "contest")]/text()'
xpath_problem_ids = '//*[@id="pageContent"]//*[@class="id"]//a/text()'
xpath_problem_name = '//*[@id="pageContent"]//*[@class="header"]//*[@class="title"]/text()'
xpath_problem_time = '//*[@id="pageContent"]//*[@class="time-limit"]/text()'
xpath_problem_memory = '//*[@id="pageContent"]//*[@class="memory-limit"]/text()'
xpath_problem_ins = '//*[@id="pageContent"]//*[@class="sample-tests"]//*[@class="input"]//pre'
xpath_problem_outs = '//*[@id="pageContent"]//*[@class="sample-tests"]//*[@class="output"]//pre'
# Proxy for HTTP requests (handles request caching during single run of the program).
<|code_end|>
with the help of current file imports:
import os
import re
import sys
from lxml import html
from urlparse import urlparse
from urllib.parse import urlparse
from hac.data import ISite, Contest, Problem
from hac.util_common import warn
from hac.util_data import RequestsCache
and context from other files:
# Path: hac/data.py
# class ISite(object):
# """Site template.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64):
# self.name = name
# self.id = id
# # 'url' member used to distinguish between different sites.
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
#
# self._info = None
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte']
#
# @abstractmethod
# def match_contest(self, conf):
# """Generates well formated URL of the contest according to user input.
# """
# pass
#
# @abstractmethod
# def get_contest(self, url):
# """Fetches data from the provided contest URL and generates contest
# object.
# """
# pass
#
# @abstractmethod
# def match_problems(self, conf):
# """Generates list of well formated problem URLs according to user
# input.
# """
# pass
#
# @abstractmethod
# def get_problems(self, urls):
# """Fetches data from the provided problem URLs and generates list of
# problem objects.
# """
# pass
#
# class Contest(object):
# """Contest info container.
# """
#
# def __init__(self, name=None, id=None, url=None):
# self.name = name
# self.id = id
# self.url = url
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url']
#
# class Problem(object):
# """Problem info container.
# """
#
# def __init__(self, name=None, id=None, url=None, time_limit_ms=2000,
# memory_limit_kbyte=262144, source_limit_kbyte=64, inputs=None,
# outputs=None):
# self.name = name
# self.id = id
# self.url = url
# self.time_limit_ms = time_limit_ms
# self.memory_limit_kbyte = memory_limit_kbyte
# self.source_limit_kbyte = source_limit_kbyte
# self.inputs = inputs or []
# self.outputs = outputs or []
#
# @staticmethod
# def get_props(verbose=False):
# return ['id', 'url'] if not verbose else \
# ['name', 'id', 'url', 'time_limit_ms', 'memory_limit_kbyte',
# 'source_limit_kbyte', 'inputs', 'outputs']
#
# Path: hac/util_common.py
# def warn(msg):
# sys.stderr.write("WARNING: " + msg + os.linesep)
#
# Path: hac/util_data.py
# class RequestsCache(object):
#
# def __init__(self):
# self._store = {}
#
# def get(self, url):
# if url not in self._store:
# self._store[url] = requests.get(url)
# return self._store[url]
, which may contain function names, class names, or code. Output only the next line. | _proxy = RequestsCache() |
Next line prediction: <|code_start|>"""
定义 blog 应用的 URL 映射。
"""
sitemaps = {
'static': StaticSitemap,
'posts': PostSitemap,
'flatpages': FlatPageSitemap,
}
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^auth/', include('django.contrib.auth.urls')),
url(r'^post/([a-zA-Z0-9\+\-_]+)/$', views.post_detail, name='post'),
url(r'^edit-post/([a-zA-Z0-9\+\-_]+)/$', views.edit_post, name='edit_post'),
url(r'^new-post/$', views.new_post, name='new_post'),
url(r'^delete-post/([a-zA-Z0-9\+\-_]+)/$', views.delete_post, name='delete_post'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url, include
from django.contrib.sitemaps.views import sitemap
from django.contrib.flatpages.sitemaps import FlatPageSitemap
from blog.feeds import PostFeed
from blog.sitemaps import StaticSitemap, PostSitemap
from . import views)
and context including class names, function names, or small code snippets from other files:
# Path: blog/feeds.py
# class PostFeed(Feed):
# """
# 定义文章 ATOM 输出的类
# """
# feed_type = Atom1Feed
# title = "学习笔记"
# link = "/"
# subtitle = "恩岩的学习笔记"
#
# def items(self):
# return Post.objects.order_by('-id')
#
# def item_title(self, item):
# return item.title
#
# def item_description(self, item):
# return item.body_html
#
# Path: blog/sitemaps.py
# class StaticSitemap(Sitemap):
# """静态链接的站点地图"""
# changefreq = 'daily'
# priority = 0.5
#
# def items(self):
# return ['index', ]
#
# def location(self, item):
# from django.core.urlresolvers import reverse
# return reverse(item)
#
# class PostSitemap(Sitemap):
# """文章详情页面的站点地图"""
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
#
# def lastmod(self, obj):
# return obj.modification_time
. Output only the next line. | url(r'^feed/$', PostFeed(), name='feed'), |
Given snippet: <|code_start|>"""
定义 blog 应用的 URL 映射。
"""
sitemaps = {
'static': StaticSitemap,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url, include
from django.contrib.sitemaps.views import sitemap
from django.contrib.flatpages.sitemaps import FlatPageSitemap
from blog.feeds import PostFeed
from blog.sitemaps import StaticSitemap, PostSitemap
from . import views
and context:
# Path: blog/feeds.py
# class PostFeed(Feed):
# """
# 定义文章 ATOM 输出的类
# """
# feed_type = Atom1Feed
# title = "学习笔记"
# link = "/"
# subtitle = "恩岩的学习笔记"
#
# def items(self):
# return Post.objects.order_by('-id')
#
# def item_title(self, item):
# return item.title
#
# def item_description(self, item):
# return item.body_html
#
# Path: blog/sitemaps.py
# class StaticSitemap(Sitemap):
# """静态链接的站点地图"""
# changefreq = 'daily'
# priority = 0.5
#
# def items(self):
# return ['index', ]
#
# def location(self, item):
# from django.core.urlresolvers import reverse
# return reverse(item)
#
# class PostSitemap(Sitemap):
# """文章详情页面的站点地图"""
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
#
# def lastmod(self, obj):
# return obj.modification_time
which might include code, classes, or functions. Output only the next line. | 'posts': PostSitemap, |
Predict the next line for this snippet: <|code_start|>
# Register your models here.
class PostAdmin(admin.ModelAdmin):
readonly_fields = ('body_html',)
admin.site.register(Post, PostAdmin)
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from blog.models import Post, Comment, Tag, Category, Link
and context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Comment(models.Model):
# """评论的数据模型"""
# name = models.CharField(max_length=256)
# email = models.EmailField()
# url = models.URLField(blank=True)
# comment = models.TextField()
# timestamp = models.DateTimeField(auto_now=True)
# post = models.ForeignKey('Post')
#
# def __str__(self):
# return self.comment
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
, which may contain function names, class names, or code. Output only the next line. | admin.site.register(Comment) |
Using the snippet: <|code_start|>
# Register your models here.
class PostAdmin(admin.ModelAdmin):
readonly_fields = ('body_html',)
admin.site.register(Post, PostAdmin)
admin.site.register(Comment)
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from blog.models import Post, Comment, Tag, Category, Link
and context (class names, function names, or code) available:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Comment(models.Model):
# """评论的数据模型"""
# name = models.CharField(max_length=256)
# email = models.EmailField()
# url = models.URLField(blank=True)
# comment = models.TextField()
# timestamp = models.DateTimeField(auto_now=True)
# post = models.ForeignKey('Post')
#
# def __str__(self):
# return self.comment
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
. Output only the next line. | admin.site.register(Tag) |
Predict the next line after this snippet: <|code_start|>
# Register your models here.
class PostAdmin(admin.ModelAdmin):
readonly_fields = ('body_html',)
admin.site.register(Post, PostAdmin)
admin.site.register(Comment)
admin.site.register(Tag)
<|code_end|>
using the current file's imports:
from django.contrib import admin
from blog.models import Post, Comment, Tag, Category, Link
and any relevant context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Comment(models.Model):
# """评论的数据模型"""
# name = models.CharField(max_length=256)
# email = models.EmailField()
# url = models.URLField(blank=True)
# comment = models.TextField()
# timestamp = models.DateTimeField(auto_now=True)
# post = models.ForeignKey('Post')
#
# def __str__(self):
# return self.comment
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
. Output only the next line. | admin.site.register(Category) |
Given snippet: <|code_start|>
# Register your models here.
class PostAdmin(admin.ModelAdmin):
readonly_fields = ('body_html',)
admin.site.register(Post, PostAdmin)
admin.site.register(Comment)
admin.site.register(Tag)
admin.site.register(Category)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from blog.models import Post, Comment, Tag, Category, Link
and context:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Comment(models.Model):
# """评论的数据模型"""
# name = models.CharField(max_length=256)
# email = models.EmailField()
# url = models.URLField(blank=True)
# comment = models.TextField()
# timestamp = models.DateTimeField(auto_now=True)
# post = models.ForeignKey('Post')
#
# def __str__(self):
# return self.comment
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
which might include code, classes, or functions. Output only the next line. | admin.site.register(Link) |
Given the following code snippet before the placeholder: <|code_start|>"""
这个文件定义表单信息。
"""
class PostForm(forms.ModelForm):
"""文章内容编辑表单"""
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from blog.models import Post, Category, Tag
and context including class names, function names, and sometimes code from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
. Output only the next line. | model = Post |
Given the code snippet: <|code_start|> labels = {
'title': '标题',
'slug': '缩略名',
'categories': '分类',
'tags': '标签',
'body_markdown': '内容',
}
help_texts = {
'title': '您的文章标题',
'slug': '缩略名(slug)是文章标题的URL友好型版本',
'tags': '使用标签将更具体的关键字与您的文章关联起来',
'categories': '使用类别按主题对您的文章进行分组',
'body_markdown': '使用Markdown语法编辑文章',
}
error_messages = {
'title': {
'required': '标题不能为空',
},
'slug': {
'required': 'slug不能为空',
'invalid': 'slug无效',
},
'body_markdown': {
'required': '文章内容不能为空',
},
}
class CategoryForm(forms.ModelForm):
""""分类表单"""
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from blog.models import Post, Category, Tag
and context (functions, classes, or occasionally code) from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
. Output only the next line. | model = Category |
Predict the next line for this snippet: <|code_start|> 'tags': '使用标签将更具体的关键字与您的文章关联起来',
'categories': '使用类别按主题对您的文章进行分组',
'body_markdown': '使用Markdown语法编辑文章',
}
error_messages = {
'title': {
'required': '标题不能为空',
},
'slug': {
'required': 'slug不能为空',
'invalid': 'slug无效',
},
'body_markdown': {
'required': '文章内容不能为空',
},
}
class CategoryForm(forms.ModelForm):
""""分类表单"""
class Meta:
model = Category
fields = ['category',]
labels = {
'category': '分类',
}
class TagForm(forms.ModelForm):
"""标签表单"""
class Meta:
<|code_end|>
with the help of current file imports:
from django import forms
from django.forms.widgets import CheckboxSelectMultiple
from blog.models import Post, Category, Tag
and context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
, which may contain function names, class names, or code. Output only the next line. | model = Tag |
Here is a snippet: <|code_start|>"""
这个文件定义了RSS输出。
"""
class PostFeed(Feed):
"""
定义文章 ATOM 输出的类
"""
feed_type = Atom1Feed
title = "学习笔记"
link = "/"
subtitle = "恩岩的学习笔记"
def items(self):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from blog.models import Post
and context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
, which may include functions, classes, or code. Output only the next line. | return Post.objects.order_by('-id') |
Given the code snippet: <|code_start|>"""
定义站点地图。
"""
class StaticSitemap(Sitemap):
"""静态链接的站点地图"""
changefreq = 'daily'
priority = 0.5
def items(self):
return ['index', ]
def location(self, item):
return reverse(item)
class PostSitemap(Sitemap):
"""文章详情页面的站点地图"""
changefreq = 'never'
priority = 0.5
def items(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.sitemaps import Sitemap
from blog.models import Post
from django.core.urlresolvers import reverse
and context (functions, classes, or occasionally code) from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
. Output only the next line. | return Post.objects.all() |
Given the code snippet: <|code_start|>
register = template.Library()
@register.inclusion_tag('_navbar.html')
def show_navbar(active, user):
return {'active': active, 'user': user}
@register.inclusion_tag('_sidebar.html')
def show_sidebar():
categories = Category.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('category')
tags = Tag.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('tag')
<|code_end|>
, generate the next line using the imports in this file:
import hashlib
from django import template
from django.db.models import Count
from ..models import Post, Category, Tag, Link
and context (functions, classes, or occasionally code) from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
. Output only the next line. | archives = Post.objects.extra(select={ |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.inclusion_tag('_navbar.html')
def show_navbar(active, user):
return {'active': active, 'user': user}
@register.inclusion_tag('_sidebar.html')
def show_sidebar():
<|code_end|>
with the help of current file imports:
import hashlib
from django import template
from django.db.models import Count
from ..models import Post, Category, Tag, Link
and context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
, which may contain function names, class names, or code. Output only the next line. | categories = Category.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('category') |
Next line prediction: <|code_start|>
register = template.Library()
@register.inclusion_tag('_navbar.html')
def show_navbar(active, user):
return {'active': active, 'user': user}
@register.inclusion_tag('_sidebar.html')
def show_sidebar():
categories = Category.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('category')
<|code_end|>
. Use current file imports:
(import hashlib
from django import template
from django.db.models import Count
from ..models import Post, Category, Tag, Link)
and context including class names, function names, or small code snippets from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
. Output only the next line. | tags = Tag.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('tag') |
Predict the next line after this snippet: <|code_start|>
register = template.Library()
@register.inclusion_tag('_navbar.html')
def show_navbar(active, user):
return {'active': active, 'user': user}
@register.inclusion_tag('_sidebar.html')
def show_sidebar():
categories = Category.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('category')
tags = Tag.objects.annotate(Count('post')).filter(post__count__gt=0).order_by('tag')
archives = Post.objects.extra(select={
'year': 'strftime("%Y", creation_time)',
'month': 'strftime("%m", creation_time)'
}).values('year', 'month').annotate(Count('id')).order_by('-year', '-month')
<|code_end|>
using the current file's imports:
import hashlib
from django import template
from django.db.models import Count
from ..models import Post, Category, Tag, Link
and any relevant context from other files:
# Path: blog/models.py
# class Post(models.Model):
# """文章的数据模型"""
# title = models.CharField(max_length=128)
# slug = models.SlugField(unique=True)
# creation_time = models.DateTimeField(auto_now_add=True)
# modification_time = models.DateTimeField(auto_now=True)
# body_markdown = models.TextField()
# body_html = models.TextField()
# author = models.ForeignKey('auth.User')
# categories = models.ManyToManyField(Category)
# tags = models.ManyToManyField(Tag)
#
# def save(self, force_insert=False, force_update=False, using=None,
# update_fields=None):
# super(Post, self).save(force_insert, force_update, using, update_fields)
# try:
# ping_google()
# except Exception:
# pass
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('post', args=[self.slug])
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# """分类的数据模型"""
# category = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.category
#
# class Tag(models.Model):
# """标签的数据模型"""
# tag = models.CharField(max_length=256, unique=True)
#
# def __str__(self):
# return self.tag
#
# class Link(models.Model):
# """链接的数据模型"""
# name = models.CharField(max_length=128)
# description = models.CharField(max_length=128)
# link = models.URLField()
#
# def __str__(self):
# return self.name
. Output only the next line. | links = Link.objects.all() |
Based on the snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
"""
The class storing all the information for the connection to the FNAC API
"""
def check_credentials_validity(credentials):
invalid_credentials = []
for k, v in credentials.items():
if v is None:
invalid_credentials.append(k)
if len(invalid_credentials):
msg = "These credentials are invalid: "
msg += ", ".join(invalid_credentials)
<|code_end|>
, predict the immediate next line with the help of imports:
from fnapy.exceptions import FnapyConnectionError
from fnapy.utils import get_credentials
and context (classes, functions, sometimes code) from other files:
# Path: fnapy/exceptions.py
# class FnapyConnectionError(FnapyException):
# """Raised when the connection is incorrect"""
#
# Path: fnapy/utils.py
# def get_credentials(sandbox=True):
# """Return the credentials for the sandbox or the real account
#
# Usage::
# credentials = get_credentials(sandbox=sandbox)
#
# :type sandbox: bool
# :param sandbox: determines whether you get the credentials for the sandbox
# account (True) or the real account (False).
#
# :rtype: dict
# :returns: the credentials for the selected account type
#
# """
# credentials = {
# "sandbox": {
# "partner_id": os.getenv("FNAC_SANDBOX_PARTNER_ID"),
# "shop_id": os.getenv("FNAC_SANDBOX_SHOP_ID"),
# "key": os.getenv("FNAC_SANDBOX_KEY"),
# },
# "real": {
# "partner_id": os.getenv("FNAC_PARTNER_ID"),
# "shop_id": os.getenv("FNAC_SHOP_ID"),
# "key": os.getenv("FNAC_KEY"),
# },
# }
# use_sandbox = {True: "sandbox", False: "real"}
# account_type = use_sandbox[sandbox]
# return credentials[account_type]
. Output only the next line. | raise FnapyConnectionError(msg) |
Based on the snippet: <|code_start|> * Create a connection using the environment variables for a given account
type (the sandbox account is used if sandbox True. If sandbox is False, the
real account is used)::
connection = FnapyConnection(sandbox=True)
.. note:: You must have previously defined the following environment
variables:
* for the sandbox: FNAC_SANDBOX_PARTNER_ID, FNAC_SANDBOX_SHOP_ID,
FNAC_SANDBOX_KEY
* for the real account: FNAC_PARTNER_ID, FNAC_SHOP_ID, FNAC_KEY
"""
def __init__(self, credentials={}, sandbox=None):
# credentials
if len(credentials) > 0:
expecteds = ("partner_id", "shop_id", "key", "sandbox")
for expected in expecteds:
if credentials.get(expected) is None:
msg = "You didn't provide the {}."
msg += "You must provide the following keys in credentials: "
msg += ", ".join(expecteds)
raise FnapyConnectionError(msg.format(expected))
# sandbox
else:
if sandbox is not None:
<|code_end|>
, predict the immediate next line with the help of imports:
from fnapy.exceptions import FnapyConnectionError
from fnapy.utils import get_credentials
and context (classes, functions, sometimes code) from other files:
# Path: fnapy/exceptions.py
# class FnapyConnectionError(FnapyException):
# """Raised when the connection is incorrect"""
#
# Path: fnapy/utils.py
# def get_credentials(sandbox=True):
# """Return the credentials for the sandbox or the real account
#
# Usage::
# credentials = get_credentials(sandbox=sandbox)
#
# :type sandbox: bool
# :param sandbox: determines whether you get the credentials for the sandbox
# account (True) or the real account (False).
#
# :rtype: dict
# :returns: the credentials for the selected account type
#
# """
# credentials = {
# "sandbox": {
# "partner_id": os.getenv("FNAC_SANDBOX_PARTNER_ID"),
# "shop_id": os.getenv("FNAC_SANDBOX_SHOP_ID"),
# "key": os.getenv("FNAC_SANDBOX_KEY"),
# },
# "real": {
# "partner_id": os.getenv("FNAC_PARTNER_ID"),
# "shop_id": os.getenv("FNAC_SHOP_ID"),
# "key": os.getenv("FNAC_KEY"),
# },
# }
# use_sandbox = {True: "sandbox", False: "real"}
# account_type = use_sandbox[sandbox]
# return credentials[account_type]
. Output only the next line. | credentials = get_credentials(sandbox) |
Predict the next line for this snippet: <|code_start|>
NAMESPACES = {'ns': XHTML_NAMESPACE}
def test_response_with_empty_content():
"""Response should not crash when its content is an empty string"""
response = Response('')
# The dict should be empty
assert len(response.dict) == 0
# The tag should be empty_content
assert response.tag == 'empty_content'
def parse_xml_file(filename):
return etree.parse(os.path.join(os.path.dirname(__file__), 'assets',
filename))
def test_response():
"""Response should not crash with an empty string"""
response = Response(b'')
def test_extract_text():
"""findall should return a list unique elements"""
messages = parse_xml_file('messages_sample.xml')
message_elements = messages.getroot().getchildren()
# All the messages should have a different message_id
<|code_end|>
with the help of current file imports:
import os
from lxml import etree
from fnapy.utils import extract_text, findall, find, Response
from fnapy.config import XHTML_NAMESPACE
and context from other files:
# Path: fnapy/utils.py
# def extract_text(element, node_name):
# """Extract the text from the selected node
#
# If no text is found, the empty string is returned.
#
# """
# inner_element = find(element, node_name)
# return inner_element.text if inner_element is not None else ""
#
# def findall(element, node_name):
# """A convenient function to look for nodes in the XML
#
# >>> nodes = findall(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.findall(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# def find(element, node_name):
# """Look for a node in the XML
#
# >>> node = find(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.find(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# class Response(HttpMessage):
# """A handy class to handle the response"""
#
# def __init__(self, content):
# super(Response, self).__init__(content)
#
# Path: fnapy/config.py
# XHTML_NAMESPACE = "http://www.fnac.com/schemas/mp-dialog.xsd"
, which may contain function names, class names, or code. Output only the next line. | message_ids = [extract_text(message_element, 'message_id') for |
Using the snippet: <|code_start|>
def test_response():
"""Response should not crash with an empty string"""
response = Response(b'')
def test_extract_text():
"""findall should return a list unique elements"""
messages = parse_xml_file('messages_sample.xml')
message_elements = messages.getroot().getchildren()
# All the messages should have a different message_id
message_ids = [extract_text(message_element, 'message_id') for
message_element in message_elements]
assert len(set(message_ids)) == len(message_ids)
def test_find():
"""find should return an element"""
messages = parse_xml_file('messages_sample.xml')
message_id = find(messages, 'message/message_id').text
first_message = messages.getroot().getchildren()[0]
first_message_id = first_message.find('.//ns:message_id',
namespaces=NAMESPACES).text
assert message_id == first_message_id
def test_findall():
"""findall should return a list unique elements"""
messages = parse_xml_file('messages_sample.xml')
<|code_end|>
, determine the next line of code. You have imports:
import os
from lxml import etree
from fnapy.utils import extract_text, findall, find, Response
from fnapy.config import XHTML_NAMESPACE
and context (class names, function names, or code) available:
# Path: fnapy/utils.py
# def extract_text(element, node_name):
# """Extract the text from the selected node
#
# If no text is found, the empty string is returned.
#
# """
# inner_element = find(element, node_name)
# return inner_element.text if inner_element is not None else ""
#
# def findall(element, node_name):
# """A convenient function to look for nodes in the XML
#
# >>> nodes = findall(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.findall(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# def find(element, node_name):
# """Look for a node in the XML
#
# >>> node = find(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.find(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# class Response(HttpMessage):
# """A handy class to handle the response"""
#
# def __init__(self, content):
# super(Response, self).__init__(content)
#
# Path: fnapy/config.py
# XHTML_NAMESPACE = "http://www.fnac.com/schemas/mp-dialog.xsd"
. Output only the next line. | message_elements = findall(messages, 'message') |
Here is a snippet: <|code_start|> # The dict should be empty
assert len(response.dict) == 0
# The tag should be empty_content
assert response.tag == 'empty_content'
def parse_xml_file(filename):
return etree.parse(os.path.join(os.path.dirname(__file__), 'assets',
filename))
def test_response():
"""Response should not crash with an empty string"""
response = Response(b'')
def test_extract_text():
"""findall should return a list unique elements"""
messages = parse_xml_file('messages_sample.xml')
message_elements = messages.getroot().getchildren()
# All the messages should have a different message_id
message_ids = [extract_text(message_element, 'message_id') for
message_element in message_elements]
assert len(set(message_ids)) == len(message_ids)
def test_find():
"""find should return an element"""
messages = parse_xml_file('messages_sample.xml')
<|code_end|>
. Write the next line using the current file imports:
import os
from lxml import etree
from fnapy.utils import extract_text, findall, find, Response
from fnapy.config import XHTML_NAMESPACE
and context from other files:
# Path: fnapy/utils.py
# def extract_text(element, node_name):
# """Extract the text from the selected node
#
# If no text is found, the empty string is returned.
#
# """
# inner_element = find(element, node_name)
# return inner_element.text if inner_element is not None else ""
#
# def findall(element, node_name):
# """A convenient function to look for nodes in the XML
#
# >>> nodes = findall(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.findall(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# def find(element, node_name):
# """Look for a node in the XML
#
# >>> node = find(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.find(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# class Response(HttpMessage):
# """A handy class to handle the response"""
#
# def __init__(self, content):
# super(Response, self).__init__(content)
#
# Path: fnapy/config.py
# XHTML_NAMESPACE = "http://www.fnac.com/schemas/mp-dialog.xsd"
, which may include functions, classes, or code. Output only the next line. | message_id = find(messages, 'message/message_id').text |
Given snippet: <|code_start|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
"""
Tests for fnappy.utils module
"""
NAMESPACES = {'ns': XHTML_NAMESPACE}
def test_response_with_empty_content():
"""Response should not crash when its content is an empty string"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from lxml import etree
from fnapy.utils import extract_text, findall, find, Response
from fnapy.config import XHTML_NAMESPACE
and context:
# Path: fnapy/utils.py
# def extract_text(element, node_name):
# """Extract the text from the selected node
#
# If no text is found, the empty string is returned.
#
# """
# inner_element = find(element, node_name)
# return inner_element.text if inner_element is not None else ""
#
# def findall(element, node_name):
# """A convenient function to look for nodes in the XML
#
# >>> nodes = findall(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.findall(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# def find(element, node_name):
# """Look for a node in the XML
#
# >>> node = find(response.element, node_name)
#
# """
# if "/" in node_name:
# node_name = "//ns:".join(node_name.split("/"))
# return element.find(
# ".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
# )
#
# class Response(HttpMessage):
# """A handy class to handle the response"""
#
# def __init__(self, content):
# super(Response, self).__init__(content)
#
# Path: fnapy/config.py
# XHTML_NAMESPACE = "http://www.fnac.com/schemas/mp-dialog.xsd"
which might include code, classes, or functions. Output only the next line. | response = Response('') |
Continue the code snippet: <|code_start|># Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
"""
Tests for FnapyConnection
"""
# Python imports
# Third-party imports
# fnapy imports
def mock_get_env_vars(env_vars_exists):
"""Mock the call to os.getenv in get_credentials"""
expecteds = ('partner_id', 'shop_id', 'key', 'sandbox')
credentials = dict().fromkeys(expecteds)
if env_vars_exists:
for expected in expecteds:
credentials.update({expected: 'XXX'})
return credentials
def test_connection_with_available_env_vars_for_sandbox(monkeypatch):
"""FnapyConnection should be able to accept the keyword sandbox=True when env vars exist"""
monkeypatch.setattr('fnapy.connection.get_credentials', lambda x: mock_get_env_vars(True))
<|code_end|>
. Use current file imports:
import os
import pytest
from fnapy.connection import FnapyConnection
from fnapy.exceptions import FnapyConnectionError
and context (classes, functions, or code) from other files:
# Path: fnapy/connection.py
# class FnapyConnection(object):
# """The connection class of fnapy
#
# Usage::
# connection = FnapyConnection(credentials=credentials, sandbox=sandbox)
#
# Example:
#
# * Create a connection with a credentials dictionary::
#
# credentials = {'partner_id': 'my_partner_id', 'shop_id': 'my_shop_id',
# 'key': 'my_key', 'sandbox': False}
#
# * Create a connection using the environment variables for a given account
# type (the sandbox account is used if sandbox True. If sandbox is False, the
# real account is used)::
#
# connection = FnapyConnection(sandbox=True)
#
# .. note:: You must have previously defined the following environment
# variables:
#
# * for the sandbox: FNAC_SANDBOX_PARTNER_ID, FNAC_SANDBOX_SHOP_ID,
# FNAC_SANDBOX_KEY
#
# * for the real account: FNAC_PARTNER_ID, FNAC_SHOP_ID, FNAC_KEY
#
# """
#
# def __init__(self, credentials={}, sandbox=None):
# # credentials
# if len(credentials) > 0:
# expecteds = ("partner_id", "shop_id", "key", "sandbox")
# for expected in expecteds:
# if credentials.get(expected) is None:
# msg = "You didn't provide the {}."
# msg += "You must provide the following keys in credentials: "
# msg += ", ".join(expecteds)
# raise FnapyConnectionError(msg.format(expected))
#
# # sandbox
# else:
# if sandbox is not None:
# credentials = get_credentials(sandbox)
# credentials.update({"sandbox": sandbox})
# else:
# msg = "You must either specify credentials or sandbox as arguments."
# raise FnapyConnectionError(msg)
#
# check_credentials_validity(credentials)
# self.partner_id = credentials["partner_id"]
# self.shop_id = credentials["shop_id"]
# self.key = credentials["key"]
# self.sandbox = credentials["sandbox"]
#
# Path: fnapy/exceptions.py
# class FnapyConnectionError(FnapyException):
# """Raised when the connection is incorrect"""
. Output only the next line. | connection = FnapyConnection(sandbox=True) |
Here is a snippet: <|code_start|># fnapy imports
def mock_get_env_vars(env_vars_exists):
"""Mock the call to os.getenv in get_credentials"""
expecteds = ('partner_id', 'shop_id', 'key', 'sandbox')
credentials = dict().fromkeys(expecteds)
if env_vars_exists:
for expected in expecteds:
credentials.update({expected: 'XXX'})
return credentials
def test_connection_with_available_env_vars_for_sandbox(monkeypatch):
"""FnapyConnection should be able to accept the keyword sandbox=True when env vars exist"""
monkeypatch.setattr('fnapy.connection.get_credentials', lambda x: mock_get_env_vars(True))
connection = FnapyConnection(sandbox=True)
def test_connection_with_available_env_vars_for_real_account(monkeypatch):
"""FnapyConnection should be able to accept the keyword sandbox=False when env vars exist"""
monkeypatch.setattr('fnapy.connection.get_credentials', lambda x: mock_get_env_vars(True))
connection = FnapyConnection(sandbox=False)
def test_connection_with_unavailable_env_vars_for_sandbox(monkeypatch):
"""FnapyConnection should raise a FnapyConnectionError when sandbox=True and env vars don't exist"""
monkeypatch.setattr('fnapy.connection.get_credentials', lambda x: mock_get_env_vars(False))
<|code_end|>
. Write the next line using the current file imports:
import os
import pytest
from fnapy.connection import FnapyConnection
from fnapy.exceptions import FnapyConnectionError
and context from other files:
# Path: fnapy/connection.py
# class FnapyConnection(object):
# """The connection class of fnapy
#
# Usage::
# connection = FnapyConnection(credentials=credentials, sandbox=sandbox)
#
# Example:
#
# * Create a connection with a credentials dictionary::
#
# credentials = {'partner_id': 'my_partner_id', 'shop_id': 'my_shop_id',
# 'key': 'my_key', 'sandbox': False}
#
# * Create a connection using the environment variables for a given account
# type (the sandbox account is used if sandbox True. If sandbox is False, the
# real account is used)::
#
# connection = FnapyConnection(sandbox=True)
#
# .. note:: You must have previously defined the following environment
# variables:
#
# * for the sandbox: FNAC_SANDBOX_PARTNER_ID, FNAC_SANDBOX_SHOP_ID,
# FNAC_SANDBOX_KEY
#
# * for the real account: FNAC_PARTNER_ID, FNAC_SHOP_ID, FNAC_KEY
#
# """
#
# def __init__(self, credentials={}, sandbox=None):
# # credentials
# if len(credentials) > 0:
# expecteds = ("partner_id", "shop_id", "key", "sandbox")
# for expected in expecteds:
# if credentials.get(expected) is None:
# msg = "You didn't provide the {}."
# msg += "You must provide the following keys in credentials: "
# msg += ", ".join(expecteds)
# raise FnapyConnectionError(msg.format(expected))
#
# # sandbox
# else:
# if sandbox is not None:
# credentials = get_credentials(sandbox)
# credentials.update({"sandbox": sandbox})
# else:
# msg = "You must either specify credentials or sandbox as arguments."
# raise FnapyConnectionError(msg)
#
# check_credentials_validity(credentials)
# self.partner_id = credentials["partner_id"]
# self.shop_id = credentials["shop_id"]
# self.key = credentials["key"]
# self.sandbox = credentials["sandbox"]
#
# Path: fnapy/exceptions.py
# class FnapyConnectionError(FnapyException):
# """Raised when the connection is incorrect"""
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(FnapyConnectionError): |
Given the code snippet: <|code_start|>
>>> node = find(response.element, node_name)
"""
if "/" in node_name:
node_name = "//ns:".join(node_name.split("/"))
return element.find(
".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
)
def extract_text(element, node_name):
"""Extract the text from the selected node
If no text is found, the empty string is returned.
"""
inner_element = find(element, node_name)
return inner_element.text if inner_element is not None else ""
def xml2dict(xml):
"""Returns a dictionary from the input XML
:type xml: unicode
:param xml: The XML
:rtype: dict
:returns: the dictionary correspoding to the input XML
"""
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import xmltodict
import requests
from codecs import open
from collections import OrderedDict
from xml.parsers.expat import ExpatError
from lxml import etree
from fnapy.config import *
from fnapy.compat import to_unicode
from fnapy.exceptions import FnapyUpdateOfferError, FnapyResponseError
and context (functions, classes, or occasionally code) from other files:
# Path: fnapy/compat.py
# def to_unicode(obj, encoding="utf-8"):
# """
# Convert ``obj`` to unicode"""
# # unicode support
# if isinstance(obj, str):
# return obj
#
# # bytes support
# if is_bytes(obj):
# if hasattr(obj, "tobytes"):
# return str(obj.tobytes(), encoding)
# return str(obj, encoding)
#
# # string support
# if isinstance(obj, basestring):
# if hasattr(obj, "decode"):
# # ignoring utf8 errors, as fnac send us malformed
# # utf8 xml sometimes ...
# return obj.decode(encoding, errors="ignore")
# else:
# return str(obj, encoding)
#
# return str(obj)
#
# Path: fnapy/exceptions.py
# class FnapyUpdateOfferError(FnapyException):
# """Raised when the update of an offer is not valid"""
#
# class FnapyResponseError(FnapyException):
# """Raised when the response is incorrect"""
. Output only the next line. | xmlepured = remove_namespace(to_unicode(xml)) |
Based on the snippet: <|code_start|> """Get the text contained in the tag of the response
:param response: the Response
:param tag_name: the name of the tag
:returns: the text enclosed in the tag
"""
xml = etree.XML(response.content)
elements = xml.xpath("//ns:{}".format(tag_name), namespaces={"ns": XHTML_NAMESPACE})
return elements[0].text if len(elements) else ""
def check_offer_data(offer_data):
"""Check the offer_data passed to update_offers is valid
:type offer_data: dict
:param offer_data: the parameters used to update an offer
:returns: None
offer_data must be a dictionary with at least 2 keys:
- offer_reference (the sku)
- any other parameter allowed by the service (price, quantity,
product_state, ...)
Raises a FnapyUpdateOfferError if the offer_data is not valid.
"""
if not isinstance(offer_data, dict):
msg = "The argument must be a dictionary."
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import xmltodict
import requests
from codecs import open
from collections import OrderedDict
from xml.parsers.expat import ExpatError
from lxml import etree
from fnapy.config import *
from fnapy.compat import to_unicode
from fnapy.exceptions import FnapyUpdateOfferError, FnapyResponseError
and context (classes, functions, sometimes code) from other files:
# Path: fnapy/compat.py
# def to_unicode(obj, encoding="utf-8"):
# """
# Convert ``obj`` to unicode"""
# # unicode support
# if isinstance(obj, str):
# return obj
#
# # bytes support
# if is_bytes(obj):
# if hasattr(obj, "tobytes"):
# return str(obj.tobytes(), encoding)
# return str(obj, encoding)
#
# # string support
# if isinstance(obj, basestring):
# if hasattr(obj, "decode"):
# # ignoring utf8 errors, as fnac send us malformed
# # utf8 xml sometimes ...
# return obj.decode(encoding, errors="ignore")
# else:
# return str(obj, encoding)
#
# return str(obj)
#
# Path: fnapy/exceptions.py
# class FnapyUpdateOfferError(FnapyException):
# """Raised when the update of an offer is not valid"""
#
# class FnapyResponseError(FnapyException):
# """Raised when the response is incorrect"""
. Output only the next line. | raise FnapyUpdateOfferError(msg) |
Using the snippet: <|code_start|> if "/" in node_name:
node_name = "//ns:".join(node_name.split("/"))
return element.find(
".//ns:{0}".format(node_name), namespaces={"ns": XHTML_NAMESPACE}
)
def extract_text(element, node_name):
"""Extract the text from the selected node
If no text is found, the empty string is returned.
"""
inner_element = find(element, node_name)
return inner_element.text if inner_element is not None else ""
def xml2dict(xml):
"""Returns a dictionary from the input XML
:type xml: unicode
:param xml: The XML
:rtype: dict
:returns: the dictionary correspoding to the input XML
"""
xmlepured = remove_namespace(to_unicode(xml))
try:
return xmltodict.parse(xmlepured)
except ExpatError as e:
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import xmltodict
import requests
from codecs import open
from collections import OrderedDict
from xml.parsers.expat import ExpatError
from lxml import etree
from fnapy.config import *
from fnapy.compat import to_unicode
from fnapy.exceptions import FnapyUpdateOfferError, FnapyResponseError
and context (class names, function names, or code) available:
# Path: fnapy/compat.py
# def to_unicode(obj, encoding="utf-8"):
# """
# Convert ``obj`` to unicode"""
# # unicode support
# if isinstance(obj, str):
# return obj
#
# # bytes support
# if is_bytes(obj):
# if hasattr(obj, "tobytes"):
# return str(obj.tobytes(), encoding)
# return str(obj, encoding)
#
# # string support
# if isinstance(obj, basestring):
# if hasattr(obj, "decode"):
# # ignoring utf8 errors, as fnac send us malformed
# # utf8 xml sometimes ...
# return obj.decode(encoding, errors="ignore")
# else:
# return str(obj, encoding)
#
# return str(obj)
#
# Path: fnapy/exceptions.py
# class FnapyUpdateOfferError(FnapyException):
# """Raised when the update of an offer is not valid"""
#
# class FnapyResponseError(FnapyException):
# """Raised when the response is incorrect"""
. Output only the next line. | raise FnapyResponseError(e) |
Next line prediction: <|code_start|>
_ = Translator("Audio", pathlib.Path(__file__))
log = logging.getLogger("red.Audio.manager")
JAR_VERSION: Final[str] = "3.4.0"
JAR_BUILD: Final[int] = 1275
LAVALINK_DOWNLOAD_URL: Final[str] = (
"https://github.com/Cog-Creators/Lavalink-Jars/releases/download/"
f"{JAR_VERSION}_{JAR_BUILD}/"
"Lavalink.jar"
)
<|code_end|>
. Use current file imports:
(import asyncio
import asyncio.subprocess # disables for # https://github.com/PyCQA/pylint/issues/1469
import itertools
import json
import logging
import pathlib
import platform
import re
import shutil
import sys
import tempfile
import time
import aiohttp
import rich.progress
from typing import ClassVar, Final, List, Optional, Pattern, Tuple
from redbot.core import data_manager
from redbot.core.i18n import Translator
from .errors import LavalinkDownloadFailed
from .utils import task_callback)
and context including class names, function names, or small code snippets from other files:
# Path: redbot/core/data_manager.py
# def load_existing_config():
# def create_temp_config():
# def load_basic_configuration(instance_name_: str):
# def _base_data_path() -> Path:
# def cog_data_path(cog_instance=None, raw_name: str = None) -> Path:
# def core_data_path() -> Path:
# def load_bundled_data(cog_instance, init_location: str):
# def bundled_data_path(cog_instance: commands.Cog) -> Path:
# def storage_type() -> str:
# def storage_details() -> dict:
. Output only the next line. | LAVALINK_DOWNLOAD_DIR: Final[pathlib.Path] = data_manager.cog_data_path(raw_name="Audio") |
Next line prediction: <|code_start|> ram_string = "{used}/{total} ({percent}%)".format(
used=_datasize(memory_ram.used),
total=_datasize(memory_ram.total),
percent=memory_ram.percent,
)
owners = []
for uid in self.bot.owner_ids:
try:
u = await self.bot.get_or_fetch_user(uid)
owners.append(f"{u.id} ({u})")
except discord.HTTPException:
owners.append(f"{uid} (Unresolvable)")
owners_string = ", ".join(owners) or "None"
resp_intro = "# Debug Info for Red:"
resp_system_intro = "## System Metadata:"
resp_system = (
f"CPU Cores: {psutil.cpu_count()} ({platform.machine()})\nRAM: {ram_string}\n"
)
resp_os_intro = "## OS Variables:"
resp_os = f"OS version: {osver}\nUser: {user_who_ran}\n" # Ran where off to?!
resp_py_metadata = (
f"Python executable: {sys.executable}\n"
f"Python version: {pyver}\n"
f"Pip version: {pipver}\n"
)
resp_red_metadata = f"Red version: {redver}\nDiscord.py version: {dpy_version}\n"
resp_red_vars_intro = "## Red variables:"
resp_red_vars = (
<|code_end|>
. Use current file imports:
(import asyncio
import contextlib
import datetime
import importlib
import itertools
import keyword
import logging
import io
import random
import markdown
import os
import re
import sys
import platform
import psutil
import getpass
import pip
import traceback
import aiohttp
import discord
import distro # pylint: disable=import-error
from pathlib import Path
from redbot.core import data_manager
from redbot.core.utils.menus import menu, DEFAULT_CONTROLS
from redbot.core.commands import GuildConverter, RawUserIdConverter
from string import ascii_letters, digits
from typing import TYPE_CHECKING, Union, Tuple, List, Optional, Iterable, Sequence, Dict, Set
from babel import Locale as BabelLocale, UnknownLocaleError
from redbot.core.data_manager import storage_type
from . import (
__version__,
version_info as red_version_info,
checks,
commands,
errors,
i18n,
bank,
modlog,
)
from ._diagnoser import IssueDiagnoser
from .utils import AsyncIter
from .utils._internal_utils import fetch_latest_red_version_info
from .utils.predicates import MessagePredicate
from .utils.chat_formatting import (
box,
escape,
humanize_list,
humanize_number,
humanize_timedelta,
inline,
pagify,
)
from .commands import CommandConverter, CogConverter
from .commands.requires import PrivilegeLevel
from redbot.core.bot import Red
from redbot.core.data_manager import basic_config
from redbot.core.data_manager import basic_config, config_file)
and context including class names, function names, or small code snippets from other files:
# Path: redbot/core/data_manager.py
# def load_existing_config():
# def create_temp_config():
# def load_basic_configuration(instance_name_: str):
# def _base_data_path() -> Path:
# def cog_data_path(cog_instance=None, raw_name: str = None) -> Path:
# def core_data_path() -> Path:
# def load_bundled_data(cog_instance, init_location: str):
# def bundled_data_path(cog_instance: commands.Cog) -> Path:
# def storage_type() -> str:
# def storage_details() -> dict:
#
# Path: redbot/core/data_manager.py
# def storage_type() -> str:
# """Gets the storage type as a string.
#
# Returns
# -------
# str
# Storage type.
# """
# try:
# return basic_config["STORAGE_TYPE"]
# except KeyError as e:
# raise RuntimeError("Bot basic config has not been loaded yet.") from e
. Output only the next line. | f"Instance name: {data_manager.instance_name}\n" |
Given snippet: <|code_start|> msg = _("Data path: {path}").format(path=data_dir)
await ctx.send(box(msg))
@commands.command(hidden=True)
@checks.is_owner()
async def debuginfo(self, ctx: commands.Context):
"""Shows debug information useful for debugging."""
if sys.platform == "linux":
IS_WINDOWS = os.name == "nt"
IS_MAC = sys.platform == "darwin"
IS_LINUX = sys.platform == "linux"
python_version = ".".join(map(str, sys.version_info[:3]))
pyver = f"{python_version} ({platform.architecture()[0]})"
pipver = pip.__version__
redver = red_version_info
dpy_version = discord.__version__
if IS_WINDOWS:
os_info = platform.uname()
osver = f"{os_info.system} {os_info.release} (version {os_info.version})"
elif IS_MAC:
os_info = platform.mac_ver()
osver = f"Mac OSX {os_info[0]} {os_info[2]}"
elif IS_LINUX:
osver = f"{distro.name()} {distro.version()}".strip()
else:
osver = "Could not parse OS, report this on Github."
user_who_ran = getpass.getuser()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import contextlib
import datetime
import importlib
import itertools
import keyword
import logging
import io
import random
import markdown
import os
import re
import sys
import platform
import psutil
import getpass
import pip
import traceback
import aiohttp
import discord
import distro # pylint: disable=import-error
from pathlib import Path
from redbot.core import data_manager
from redbot.core.utils.menus import menu, DEFAULT_CONTROLS
from redbot.core.commands import GuildConverter, RawUserIdConverter
from string import ascii_letters, digits
from typing import TYPE_CHECKING, Union, Tuple, List, Optional, Iterable, Sequence, Dict, Set
from babel import Locale as BabelLocale, UnknownLocaleError
from redbot.core.data_manager import storage_type
from . import (
__version__,
version_info as red_version_info,
checks,
commands,
errors,
i18n,
bank,
modlog,
)
from ._diagnoser import IssueDiagnoser
from .utils import AsyncIter
from .utils._internal_utils import fetch_latest_red_version_info
from .utils.predicates import MessagePredicate
from .utils.chat_formatting import (
box,
escape,
humanize_list,
humanize_number,
humanize_timedelta,
inline,
pagify,
)
from .commands import CommandConverter, CogConverter
from .commands.requires import PrivilegeLevel
from redbot.core.bot import Red
from redbot.core.data_manager import basic_config
from redbot.core.data_manager import basic_config, config_file
and context:
# Path: redbot/core/data_manager.py
# def load_existing_config():
# def create_temp_config():
# def load_basic_configuration(instance_name_: str):
# def _base_data_path() -> Path:
# def cog_data_path(cog_instance=None, raw_name: str = None) -> Path:
# def core_data_path() -> Path:
# def load_bundled_data(cog_instance, init_location: str):
# def bundled_data_path(cog_instance: commands.Cog) -> Path:
# def storage_type() -> str:
# def storage_details() -> dict:
#
# Path: redbot/core/data_manager.py
# def storage_type() -> str:
# """Gets the storage type as a string.
#
# Returns
# -------
# str
# Storage type.
# """
# try:
# return basic_config["STORAGE_TYPE"]
# except KeyError as e:
# raise RuntimeError("Bot basic config has not been loaded yet.") from e
which might include code, classes, or functions. Output only the next line. | driver = storage_type() |
Predict the next line for this snippet: <|code_start|>"""Unit tests for sciunit utility functions and classes"""
class CacheTestCase(unittest.TestCase):
def test_basic_cache(self):
class dummy_test(sciunit.Test):
# The name of the cache key param determines the cache key location
<|code_end|>
with the help of current file imports:
import tempfile
import unittest
import sciunit
import numpy as np
import quantities as pq
from sciunit.utils import use_backend_cache
from sciunit.utils import set_warnings_traceback, warn_with_traceback
from sciunit.utils import NotebookTools
from sciunit.base import log, strip_html
from sciunit.utils import html_log
from sciunit.utils import assert_dimensionless
from sciunit.utils import dict_hash
from sciunit.utils import import_module_from_path
from sciunit.models.examples import ConstModel
from io import StringIO
from sciunit.utils import MockDevice
from random import randint
from sciunit.utils import memoize
from sciunit.utils import class_intern
and context from other files:
# Path: sciunit/utils.py
# def use_backend_cache(original_function=None, cache_key_param=None):
# """
# Decorator for test functions (in particular `generate_prediction`) to cache
# the function output on the first execution and return the output from the
# cache without recomputing on any subsequent execution.
# The function needs to take a model as an argument, and the caching relies on
# the model's backend. If it doesn't have a backend the caching step is
# skipped.
# Per default, a test instance specific hash is used to link the model to the
# test's function output. However, optionally, a custom hash key name can be
# passed to the decorator to use the hash stored in
# `self.params[<hash key name>]` instead (e.g. for using a shared cache for
# redundant calculations on the same model across tests).
# """
#
# def _decorate(function):
#
# @functools.wraps(function)
# def wrapper(self, *args, **kwargs):
# sig = inspect.signature(function)
# if 'model' in kwargs:
# model = kwargs['model']
# elif 'model' in sig.parameters.keys():
# model = args[list(sig.parameters.keys()).index('model')-1]
# else:
# model = None
# warnings.warn("The decorator `use_backend_cache` can only "
# "be used for test class functions that get "
# "'model' as an argument! Caching is skipped.")
#
# cache_key = None
# if cache_key_param:
# if cache_key_param in self.params:
# cache_key = self.params[cache_key_param]
# else:
# model = None
# warnings.warn("The value for the decorator arguement "
# "cache_key_param value can not be found in "
# "self.params! Caching is skipped.")
#
# function_output = self.get_backend_cache(model=model,
# key=cache_key)
#
# if function_output is None:
# function_output = function(self, *args, **kwargs)
# self.set_backend_cache(model=model,
# function_output=function_output,
# key=cache_key)
#
# return function_output
#
# return wrapper
#
# if original_function:
# return _decorate(original_function)
# else:
# return _decorate
, which may contain function names, class names, or code. Output only the next line. | @use_backend_cache(cache_key_param='dummy_cache_key') |
Next line prediction: <|code_start|>
def set_warnings_traceback(tb: bool = True) -> None:
"""Set to `True` to give tracebacks for all warnings, or `False` to restore
default behavior.
Args:
tb (bool, optional): Defaults to True.
"""
if tb:
warnings._showwarning = warnings.showwarning
warnings.showwarning = warn_with_traceback
warnings.simplefilter("always")
else:
warnings.showwarning = warnings._showwarning
warnings.simplefilter("default")
def dict_combine(*dict_list) -> dict:
"""Return the union of several dictionaries.
Uses the values from later dictionaries in the argument list when
duplicate keys are encountered.
In Python 3 this can simply be {**d1, **d2, ...}
but Python 2 does not support this dict unpacking syntax.
Returns:
dict: the dict from combining the dicts
"""
return {k: v for d in dict_list for k, v in d.items()}
<|code_end|>
. Use current file imports:
(import contextlib
import functools
import hashlib
import importlib
import inspect
import os
import pkgutil
import re
import sys
import traceback
import unittest.mock
import warnings
import jsonpickle
import nbconvert
import nbformat
import sciunit
import matplotlib as mpl
import shutil
from datetime import datetime
from io import StringIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
from typing import Any, Callable, List, TextIO, Tuple, Type, Union
from urllib.request import urlopen
from IPython.display import HTML, display
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
from quantities.dimensionality import Dimensionality
from quantities.quantity import Quantity
from .base import ( # noqa
PLATFORM,
PYTHON_MAJOR_VERSION,
SciUnit,
__version__,
config,
ipy,
tkinter,
)
from importlib.machinery import SourceFileLoader
from importlib import import_module)
and context including class names, function names, or small code snippets from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
. Output only the next line. | if PYTHON_MAJOR_VERSION == 3: |
Next line prediction: <|code_start|> if isinstance(file, str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
print("Incorrect path specified")
return -1
def get_path(self, file: Path) -> Path:
"""Get the full path of the notebook found in the directory
specified by self.path.
Args:
file (Path): the path to the notebook file.
Returns:
Path: The fully resolved path to the notebook file.
"""
class_path = Path(inspect.getfile(self.__class__))
parent_path = class_path.parent
path = parent_path / self.path / file
return path.resolve()
def fix_display(self) -> None:
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
<|code_end|>
. Use current file imports:
(import contextlib
import functools
import hashlib
import importlib
import inspect
import os
import pkgutil
import re
import sys
import traceback
import unittest.mock
import warnings
import jsonpickle
import nbconvert
import nbformat
import sciunit
import matplotlib as mpl
import shutil
from datetime import datetime
from io import StringIO, TextIOWrapper
from pathlib import Path
from types import ModuleType
from typing import Any, Callable, List, TextIO, Tuple, Type, Union
from urllib.request import urlopen
from IPython.display import HTML, display
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
from quantities.dimensionality import Dimensionality
from quantities.quantity import Quantity
from .base import ( # noqa
PLATFORM,
PYTHON_MAJOR_VERSION,
SciUnit,
__version__,
config,
ipy,
tkinter,
)
from importlib.machinery import SourceFileLoader
from importlib import import_module)
and context including class names, function names, or small code snippets from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
. Output only the next line. | tkinter.Tk() |
Given the following code snippet before the placeholder: <|code_start|>"""The base class for SciUnit capabilities.
By inheriting a capability class, a model tells the test that it implements
that capability and that all of its methods are safe to call.
The capability must then be implemented by the modeler (i.e. all of the
capabilty's methods must implemented in the model class).
"""
# from sciunit.models.examples import ConstModel, UniformModel
<|code_end|>
, predict the next line using imports from the current file:
import dis
import inspect
import io
import re
import sys
import warnings
from .base import SciUnit, log, logger
from .errors import CapabilityNotImplementedError
from sciunit import Model
and context including class names, function names, and sometimes code from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class CapabilityNotImplementedError(CapabilityError):
# """Error raised when a required capability is not *implemented* by a model.
# Do not use for capabilities that are not provided at all."""
#
# action = "implement"
. Output only the next line. | class Capability(SciUnit): |
Here is a snippet: <|code_start|> Args:
model (Model): A sciunit model instance
require_extra (bool, optional): Requiring that an instance check be present in
`model.extra_capability_checks`. Defaults to False.
Returns:
bool: Whether the provided model has this capability.
"""
class_capable = isinstance(model, cls)
source_capable = None
if class_capable:
source_capable = cls.source_check(model)
f_name = (
model.extra_capability_checks.get(cls, None)
if model.extra_capability_checks is not None
else False
)
if f_name:
f = getattr(model, f_name)
instance_capable = f()
elif not require_extra:
instance_capable = True
else:
instance_capable = False
if not class_capable:
<|code_end|>
. Write the next line using the current file imports:
import dis
import inspect
import io
import re
import sys
import warnings
from .base import SciUnit, log, logger
from .errors import CapabilityNotImplementedError
from sciunit import Model
and context from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class CapabilityNotImplementedError(CapabilityError):
# """Error raised when a required capability is not *implemented* by a model.
# Do not use for capabilities that are not provided at all."""
#
# action = "implement"
, which may include functions, classes, or code. Output only the next line. | log( |
Using the snippet: <|code_start|> """
class_capable = isinstance(model, cls)
source_capable = None
if class_capable:
source_capable = cls.source_check(model)
f_name = (
model.extra_capability_checks.get(cls, None)
if model.extra_capability_checks is not None
else False
)
if f_name:
f = getattr(model, f_name)
instance_capable = f()
elif not require_extra:
instance_capable = True
else:
instance_capable = False
if not class_capable:
log(
(
"The Model class does not claim at least one Capability required by "
"the Test class, so the Score is likely to be unavailable."
)
)
elif not source_capable:
<|code_end|>
, determine the next line of code. You have imports:
import dis
import inspect
import io
import re
import sys
import warnings
from .base import SciUnit, log, logger
from .errors import CapabilityNotImplementedError
from sciunit import Model
and context (class names, function names, or code) available:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class CapabilityNotImplementedError(CapabilityError):
# """Error raised when a required capability is not *implemented* by a model.
# Do not use for capabilities that are not provided at all."""
#
# action = "implement"
. Output only the next line. | logger.warning( |
Given the code snippet: <|code_start|> )
)
elif not source_capable:
logger.warning(
(
"The model class claimed to implement all methods required by "
"the Test class, but at least one was left unimplemented, "
"so this model will be skipped."
)
)
return class_capable and instance_capable and source_capable
def unimplemented(self, message: str = "") -> None:
"""Raise a `CapabilityNotImplementedError` with details.
Args:
message (str, optional): Message for not implemented exception. Defaults to ''.
Raises:
CapabilityNotImplementedError: Raise a `CapabilityNotImplementedError` with details.
"""
capabilities = [
obj
for obj in self.__class__.mro()
if issubclass(obj, Capability) and not issubclass(obj, Model)
]
model = self if isinstance(self, Model) else None
capability = None if not capabilities else capabilities[0]
<|code_end|>
, generate the next line using the imports in this file:
import dis
import inspect
import io
import re
import sys
import warnings
from .base import SciUnit, log, logger
from .errors import CapabilityNotImplementedError
from sciunit import Model
and context (functions, classes, or occasionally code) from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class CapabilityNotImplementedError(CapabilityError):
# """Error raised when a required capability is not *implemented* by a model.
# Do not use for capabilities that are not provided at all."""
#
# action = "implement"
. Output only the next line. | raise CapabilityNotImplementedError(model, capability, message) |
Using the snippet: <|code_start|>"""Base class for SciUnit scores."""
# Set up score logger
score_logger = logging.getLogger("sciunit_scores")
if ipy:
imp.reload(logging)
sl_handler = logging.StreamHandler(sys.stdout)
score_logger.addHandler(sl_handler)
score_log_level = config.get("score_log_level", 1)
score_logger.setLevel(score_log_level)
<|code_end|>
, determine the next line of code. You have imports:
import imp
import logging
import math
import sys
import numpy as np
import matplotlib.cm as cm
from copy import copy
from typing import Tuple, Union
from quantities import Quantity
from sciunit.base import SciUnit, config, ipy, log
from sciunit.errors import InvalidScoreError
and context (class names, function names, or code) available:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class InvalidScoreError(Error):
# """Error raised when a score is invalid."""
. Output only the next line. | class Score(SciUnit): |
Here is a snippet: <|code_start|>"""Base class for SciUnit scores."""
# Set up score logger
score_logger = logging.getLogger("sciunit_scores")
if ipy:
imp.reload(logging)
sl_handler = logging.StreamHandler(sys.stdout)
score_logger.addHandler(sl_handler)
<|code_end|>
. Write the next line using the current file imports:
import imp
import logging
import math
import sys
import numpy as np
import matplotlib.cm as cm
from copy import copy
from typing import Tuple, Union
from quantities import Quantity
from sciunit.base import SciUnit, config, ipy, log
from sciunit.errors import InvalidScoreError
and context from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class InvalidScoreError(Error):
# """Error raised when a score is invalid."""
, which may include functions, classes, or code. Output only the next line. | score_log_level = config.get("score_log_level", 1) |
Predict the next line for this snippet: <|code_start|> """Compute whether the observation equals the prediction.
Args:
observation (dict): The observation from the real world.
prediction (dict): The prediction generated by a model.
Returns:
NotImplementedError: Not implemented error.
"""
return NotImplementedError("")
@property
def norm_score(self) -> "Score":
"""A floating point version of the score used for sorting.
If normalized = True, this must be in the range 0.0 to 1.0,
where larger is better (used for sorting and coloring tables).
Returns:
Score: The [0-1] normalized score.
"""
return self.score
@property
def log_norm_score(self) -> float:
"""The natural logarithm of the `norm_score`.
This is useful for guaranteeing convexity in an error surface.
Returns:
float: The natural logarithm of the `norm_score`.
"""
<|code_end|>
with the help of current file imports:
import imp
import logging
import math
import sys
import numpy as np
import matplotlib.cm as cm
from copy import copy
from typing import Tuple, Union
from quantities import Quantity
from sciunit.base import SciUnit, config, ipy, log
from sciunit.errors import InvalidScoreError
and context from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class InvalidScoreError(Error):
# """Error raised when a score is invalid."""
, which may contain function names, class names, or code. Output only the next line. | return math.log(self.norm_score) if self.norm_score is not None else None |
Continue the code snippet: <|code_start|> test = None
"""The test taken. Set automatically by Test.judge."""
model = None
"""The model judged. Set automatically by Test.judge."""
observation_schema = None
state_hide = ["related_data"]
@classmethod
def observation_preprocess(cls, observation: dict) -> dict:
return observation
@classmethod
def observation_postprocess(cls, observation: dict) -> dict:
return observation
def check_score(self, score: "Score") -> None:
"""Check the score with imposed additional constraints in the subclass on the score, e.g. the range of the allowed score.
Args:
score (Score): A sciunit score instance.
Raises:
InvalidScoreError: Exception raised if `score` is not a instance of sciunit score.
"""
if self._allowed_types and not isinstance(
score, self._allowed_types + (Exception,)
):
<|code_end|>
. Use current file imports:
import imp
import logging
import math
import sys
import numpy as np
import matplotlib.cm as cm
from copy import copy
from typing import Tuple, Union
from quantities import Quantity
from sciunit.base import SciUnit, config, ipy, log
from sciunit.errors import InvalidScoreError
and context (classes, functions, or code) from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
#
# Path: sciunit/errors.py
# class InvalidScoreError(Error):
# """Error raised when a score is invalid."""
. Output only the next line. | raise InvalidScoreError( |
Predict the next line for this snippet: <|code_start|>"""Base class for simulator backends for SciUnit models."""
available_backends = {}
def register_backends(vars: dict) -> None:
"""Register backends for use with models.
Args:
vars (dict): a dictionary of variables obtained from e.g. `locals()`,
at least some of which are Backend classes, e.g. from imports.
"""
new_backends = {
x if x is None else x.replace("Backend", ""): cls
for x, cls in vars.items()
if inspect.isclass(cls) and issubclass(cls, Backend)
}
available_backends.update(new_backends)
<|code_end|>
with the help of current file imports:
import inspect
import pickle
import shelve
import tempfile
from pathlib import Path
from typing import Any, Union
from sciunit.base import SciUnit, config
and context from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
, which may contain function names, class names, or code. Output only the next line. | class Backend(SciUnit): |
Predict the next line for this snippet: <|code_start|> if self.use_disk_cache:
self.init_disk_cache(location=self.use_disk_cache)
self.load_model()
#: Name of the backend
name = None
#: The function that handles running the simulation
f = None
#: Optional list of state variables for a backend to record.
recorded_variables = None
state_hide = ["memory_cache", "_results", "stdout", "exec_in_dir", "model"]
def init_cache(self) -> None:
"""Initialize the cache."""
self.init_memory_cache()
self.init_disk_cache()
def init_memory_cache(self) -> None:
"""Initialize the in-memory version of the cache."""
self.memory_cache = {}
def init_disk_cache(self, location: Union[str, Path, bool, None] = None) -> None:
"""Initialize the on-disk version of the cache."""
if isinstance(location, (str, Path)):
location = str(location)
else:
# => "~/.sciunit/cache"
<|code_end|>
with the help of current file imports:
import inspect
import pickle
import shelve
import tempfile
from pathlib import Path
from typing import Any, Union
from sciunit.base import SciUnit, config
and context from other files:
# Path: sciunit/base.py
# PLATFORM = sys.platform
# PYTHON_MAJOR_VERSION = sys.version_info.major
# class Config(dict):
# class Versioned(object):
# class SciUnit(Versioned):
# class TestWeighted(object):
# class SciUnitHandler(BaseHandler):
# class QuantitiesHandler(BaseHandler):
# class UnitQuantitiesHandler(BaseHandler):
# def __init__(self, *args, **kwargs):
# def path(self):
# def path(self, val):
# def __getitem__(self, key):
# def get(self, key, default=None, update_from_disk=True):
# def set(self, key, val):
# def __setitem__(self, key, val):
# def get_from_disk(self):
# def create(self, data: dict = None) -> bool:
# def load(self):
# def save(self):
# def get_repo(self, cached: bool = True) -> Repo:
# def get_version(self, cached: bool = True) -> str:
# def get_remote(self, remote_name: str = "origin", **kwargs) -> Remote:
# def get_remote_url(self, remote: str = "origin", cached: bool = True) -> str:
# def __init__(self):
# def __getstate__(self) -> dict:
# def properties(self, keys: list = None, exclude: list = None) -> dict:
# def property_names(self) -> list:
# def json(
# self, add_props: bool = True, string: bool = True, unpicklable: bool = False, make_refs: bool = False) -> str:
# def diff(self, other, add_props=False):
# def hash(self, serialization: str = None) -> str:
# def _class(self) -> dict:
# def url(self) -> str:
# def get_list_attr_with_bases(self, attr: str) -> list:
# def weights(self) -> List[float]:
# def deep_exclude(state: dict, exclude: list) -> dict:
# def log(*args, **kwargs):
# def strip_html(html):
# def flatten(self, obj, data):
# def restore(self, data):
# def simplify(self, d):
# def flatten(self, obj, data):
# def restore(self, data):
# def flatten(self, obj, data):
# def restore(self, data):
, which may contain function names, class names, or code. Output only the next line. | location = str(config.path.parent / "cache") |
Using the snippet: <|code_start|> default = models.Manager()
objects = TopicManager()
# for topic subscriptions
subscribers = models.ManyToManyField(User, related_name='subscribers')
class Meta:
ordering = ('-is_sticky', '-last_reply_on',)
get_latest_by = ('created_on')
verbose_name = "Topic"
verbose_name_plural = "Topics"
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.subject)
slug = slug[:198]
same_slug_count = Ftopics.objects.filter(slug__startswith = slug).count()
if same_slug_count:
slug = slug + str(same_slug_count)
self.slug = slug
super(Ftopics, self).save(*args, **kwargs)
def __unicode__(self):
return self.subject
def get_absolute_url(self):
return reverse('dinette_topic_detail', kwargs={'categoryslug':self.category.slug, 'topic_slug': self.slug})
def htmlfrombbcode(self):
if(len(self.message.raw.strip()) > 0):
<|code_end|>
, determine the next line of code. You have imports:
from django.db import models
from django.contrib.auth.models import User, Group
from django.conf import settings
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
from django.db.models.signals import post_save
from django.template.defaultfilters import truncatewords
from django.core.urlresolvers import reverse
from BeautifulSoup import BeautifulSoup
from dinette.libs.postmarkup import render_bbcode
from markupfield.fields import MarkupField
from django.conf import settings
import hashlib
import datetime
and context (class names, function names, or code) available:
# Path: dinette/libs/postmarkup.py
# def render_bbcode(bbcode,
# encoding="ascii",
# exclude_tags=None,
# auto_urls=True,
# paragraphs=False,
# clean=True,
# tag_data=None):
#
# """ Renders a bbcode string in to XHTML. This is a shortcut if you don't
# need to customize any tags.
#
# post_markup -- String containing bbcode.
# encoding -- Encoding of string, defaults to "ascii" if the string is not
# already unicode.
# exclude_tags -- A collection of tag names to ignore.
# auto_urls -- If True, then urls will be wrapped with url bbcode tags.
# paragraphs -- If True then line breaks will be replaces with paragraph
# tags, rather than break tags.
# clean -- If True, html will be run through a cleanup_html method.
# tag_data -- An optional dictionary to store tag data in. The default of
# None will create a dictionary internally.
#
# """
# return _postmarkup(bbcode,
# encoding,
# exclude_tags=exclude_tags,
# auto_urls=auto_urls,
# paragraphs=paragraphs,
# clean=clean,
# tag_data=tag_data)
. Output only the next line. | return render_bbcode(self.message.raw) |
Predict the next line after this snippet: <|code_start|> 'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'django.contrib.staticfiles',
'dinette',
'compressor',
'sorl.thumbnail',
'pagination'
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dev.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
COMPRESS = False
<|code_end|>
using the current file's imports:
from dinette.extra_settings import *
from subprocess import call
from markupfield.markup import DEFAULT_MARKUP_TYPES
from dinette.libs.postmarkup import render_bbcode
from settings import STATIC_ROOT
import os
and any relevant context from other files:
# Path: dinette/libs/postmarkup.py
# def render_bbcode(bbcode,
# encoding="ascii",
# exclude_tags=None,
# auto_urls=True,
# paragraphs=False,
# clean=True,
# tag_data=None):
#
# """ Renders a bbcode string in to XHTML. This is a shortcut if you don't
# need to customize any tags.
#
# post_markup -- String containing bbcode.
# encoding -- Encoding of string, defaults to "ascii" if the string is not
# already unicode.
# exclude_tags -- A collection of tag names to ignore.
# auto_urls -- If True, then urls will be wrapped with url bbcode tags.
# paragraphs -- If True then line breaks will be replaces with paragraph
# tags, rather than break tags.
# clean -- If True, html will be run through a cleanup_html method.
# tag_data -- An optional dictionary to store tag data in. The default of
# None will create a dictionary internally.
#
# """
# return _postmarkup(bbcode,
# encoding,
# exclude_tags=exclude_tags,
# auto_urls=auto_urls,
# paragraphs=paragraphs,
# clean=clean,
# tag_data=tag_data)
. Output only the next line. | DEFAULT_MARKUP_TYPES.append(('bbcode', render_bbcode)) |
Given snippet: <|code_start|>
register = template.Library()
class BaseDinetteNode(template.Node):
@classmethod
def handle_token(cls, parser, token):
tokens = token.contents.split()
if len(tokens) == 3:
if tokens[1] != "as":
raise template.TemplateSyntaxError("Second argument in %r must be 'as'" % tokens[0])
return cls(
as_varname=tokens[2]
)
else:
return cls()
class GetAnnouncementNode(BaseDinetteNode):
def __init__(self, as_varname='announcement'):
self.as_varname = as_varname
def render(self, context):
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import template
from django.contrib.sites.models import Site
from django.conf import settings
from dinette.models import Ftopics, SiteConfig, NavLink
and context:
# Path: dinette/models.py
# class Ftopics(models.Model):
# category = models.ForeignKey(Category)
# posted_by = models.ForeignKey(User)
# subject = models.CharField(max_length=999)
# slug = models.SlugField(max_length = 200, db_index = True)
# message = MarkupField(default_markup_type=getattr(settings,
# 'DEFAULT_MARKUP_TYPE',
# 'markdown'),
# markup_choices=settings.MARKUP_RENDERERS,
# escape_html=True,
# )
# file = models.FileField(upload_to='dinette/files',default='',null=True,blank=True)
# attachment_type = models.CharField(max_length=20,default='nofile')
# filename = models.CharField(max_length=100,default="dummyname.txt")
# viewcount = models.IntegerField(default=0)
# replies = models.IntegerField(default=0)
# created_on = models.DateTimeField(auto_now_add=True)
# updated_on = models.DateTimeField(auto_now=True)
# last_reply_on = models.DateTimeField(auto_now_add=True)
# num_replies = models.PositiveSmallIntegerField(default = 0)
#
# #Moderation features
# announcement_flag = models.BooleanField(default=False)
# is_closed = models.BooleanField(default=False)
# is_sticky = models.BooleanField(default=False)
# is_hidden = models.BooleanField(default=False)
#
# # use TopicManager as default, prevent leaking of hidden topics
# default = models.Manager()
# objects = TopicManager()
#
# # for topic subscriptions
# subscribers = models.ManyToManyField(User, related_name='subscribers')
#
# class Meta:
# ordering = ('-is_sticky', '-last_reply_on',)
# get_latest_by = ('created_on')
# verbose_name = "Topic"
# verbose_name_plural = "Topics"
#
# def save(self, *args, **kwargs):
# if not self.slug:
# slug = slugify(self.subject)
# slug = slug[:198]
# same_slug_count = Ftopics.objects.filter(slug__startswith = slug).count()
# if same_slug_count:
# slug = slug + str(same_slug_count)
# self.slug = slug
# super(Ftopics, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('dinette_topic_detail', kwargs={'categoryslug':self.category.slug, 'topic_slug': self.slug})
#
# def htmlfrombbcode(self):
# if(len(self.message.raw.strip()) > 0):
# return render_bbcode(self.message.raw)
# else :
# return ""
#
# def search_snippet(self):
# msg = "%s %s"% (self.subject, self.message.rendered)
# return truncatewords(msg, 50)
#
# def getTopicString(self):
# #which is helpful for doing reverse lookup of an feed url for a topic
# return "topic/%s" % self.slug
#
# def lastPostDatetime(self):
# return self.lastPost().created_on
#
# def lastPostedUser(self):
# return self.lastPost().posted_by.username
#
# def lastPost(self):
# if (self.reply_set.count() == 0):
# return self
# return self.reply_set.order_by('-created_on')[0]
#
# def classname(self):
# return self.__class__.__name__
#
# class SiteConfig(models.Model):
# name = models.CharField(max_length = 100)
# tag_line = models.TextField(max_length = 100)
#
# class NavLink(models.Model):
# title = models.CharField(max_length = 100)
# url = models.URLField()
#
# class Meta:
# verbose_name = "Navigation Link"
# verbose_name_plural = "Navigation Links"
#
# def __unicode__(self):
# return self.title
which might include code, classes, or functions. Output only the next line. | ancount = Ftopics.objects.filter(announcement_flag=True).count() |
Here is a snippet: <|code_start|>
def render(self, context):
try:
ancount = Ftopics.objects.filter(announcement_flag=True).count()
if(ancount > 0):
announcement = Ftopics.objects.filter(announcement_flag=True).latest()
context[self.as_varname] = announcement
return ''
except Ftopics.DoesNotExist:
return ''
@register.tag
def get_announcement(parser, token):
return GetAnnouncementNode.handle_token(parser, token)
class GetNavLinksNode(BaseDinetteNode):
def __init__(self, as_varname='nav_links'):
self.as_varname = as_varname
def render(self, context):
context[self.as_varname] = NavLink.objects.all()
return ''
@register.tag
def get_forumwide_links(parser, token):
return GetNavLinksNode.handle_token(parser, token)
@register.simple_tag
def get_site_name():
try:
<|code_end|>
. Write the next line using the current file imports:
from django import template
from django.contrib.sites.models import Site
from django.conf import settings
from dinette.models import Ftopics, SiteConfig, NavLink
and context from other files:
# Path: dinette/models.py
# class Ftopics(models.Model):
# category = models.ForeignKey(Category)
# posted_by = models.ForeignKey(User)
# subject = models.CharField(max_length=999)
# slug = models.SlugField(max_length = 200, db_index = True)
# message = MarkupField(default_markup_type=getattr(settings,
# 'DEFAULT_MARKUP_TYPE',
# 'markdown'),
# markup_choices=settings.MARKUP_RENDERERS,
# escape_html=True,
# )
# file = models.FileField(upload_to='dinette/files',default='',null=True,blank=True)
# attachment_type = models.CharField(max_length=20,default='nofile')
# filename = models.CharField(max_length=100,default="dummyname.txt")
# viewcount = models.IntegerField(default=0)
# replies = models.IntegerField(default=0)
# created_on = models.DateTimeField(auto_now_add=True)
# updated_on = models.DateTimeField(auto_now=True)
# last_reply_on = models.DateTimeField(auto_now_add=True)
# num_replies = models.PositiveSmallIntegerField(default = 0)
#
# #Moderation features
# announcement_flag = models.BooleanField(default=False)
# is_closed = models.BooleanField(default=False)
# is_sticky = models.BooleanField(default=False)
# is_hidden = models.BooleanField(default=False)
#
# # use TopicManager as default, prevent leaking of hidden topics
# default = models.Manager()
# objects = TopicManager()
#
# # for topic subscriptions
# subscribers = models.ManyToManyField(User, related_name='subscribers')
#
# class Meta:
# ordering = ('-is_sticky', '-last_reply_on',)
# get_latest_by = ('created_on')
# verbose_name = "Topic"
# verbose_name_plural = "Topics"
#
# def save(self, *args, **kwargs):
# if not self.slug:
# slug = slugify(self.subject)
# slug = slug[:198]
# same_slug_count = Ftopics.objects.filter(slug__startswith = slug).count()
# if same_slug_count:
# slug = slug + str(same_slug_count)
# self.slug = slug
# super(Ftopics, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('dinette_topic_detail', kwargs={'categoryslug':self.category.slug, 'topic_slug': self.slug})
#
# def htmlfrombbcode(self):
# if(len(self.message.raw.strip()) > 0):
# return render_bbcode(self.message.raw)
# else :
# return ""
#
# def search_snippet(self):
# msg = "%s %s"% (self.subject, self.message.rendered)
# return truncatewords(msg, 50)
#
# def getTopicString(self):
# #which is helpful for doing reverse lookup of an feed url for a topic
# return "topic/%s" % self.slug
#
# def lastPostDatetime(self):
# return self.lastPost().created_on
#
# def lastPostedUser(self):
# return self.lastPost().posted_by.username
#
# def lastPost(self):
# if (self.reply_set.count() == 0):
# return self
# return self.reply_set.order_by('-created_on')[0]
#
# def classname(self):
# return self.__class__.__name__
#
# class SiteConfig(models.Model):
# name = models.CharField(max_length = 100)
# tag_line = models.TextField(max_length = 100)
#
# class NavLink(models.Model):
# title = models.CharField(max_length = 100)
# url = models.URLField()
#
# class Meta:
# verbose_name = "Navigation Link"
# verbose_name_plural = "Navigation Links"
#
# def __unicode__(self):
# return self.title
, which may include functions, classes, or code. Output only the next line. | config = SiteConfig.objects.get(id=1) |
Here is a snippet: <|code_start|> raise template.TemplateSyntaxError("Second argument in %r must be 'as'" % tokens[0])
return cls(
as_varname=tokens[2]
)
else:
return cls()
class GetAnnouncementNode(BaseDinetteNode):
def __init__(self, as_varname='announcement'):
self.as_varname = as_varname
def render(self, context):
try:
ancount = Ftopics.objects.filter(announcement_flag=True).count()
if(ancount > 0):
announcement = Ftopics.objects.filter(announcement_flag=True).latest()
context[self.as_varname] = announcement
return ''
except Ftopics.DoesNotExist:
return ''
@register.tag
def get_announcement(parser, token):
return GetAnnouncementNode.handle_token(parser, token)
class GetNavLinksNode(BaseDinetteNode):
def __init__(self, as_varname='nav_links'):
self.as_varname = as_varname
def render(self, context):
<|code_end|>
. Write the next line using the current file imports:
from django import template
from django.contrib.sites.models import Site
from django.conf import settings
from dinette.models import Ftopics, SiteConfig, NavLink
and context from other files:
# Path: dinette/models.py
# class Ftopics(models.Model):
# category = models.ForeignKey(Category)
# posted_by = models.ForeignKey(User)
# subject = models.CharField(max_length=999)
# slug = models.SlugField(max_length = 200, db_index = True)
# message = MarkupField(default_markup_type=getattr(settings,
# 'DEFAULT_MARKUP_TYPE',
# 'markdown'),
# markup_choices=settings.MARKUP_RENDERERS,
# escape_html=True,
# )
# file = models.FileField(upload_to='dinette/files',default='',null=True,blank=True)
# attachment_type = models.CharField(max_length=20,default='nofile')
# filename = models.CharField(max_length=100,default="dummyname.txt")
# viewcount = models.IntegerField(default=0)
# replies = models.IntegerField(default=0)
# created_on = models.DateTimeField(auto_now_add=True)
# updated_on = models.DateTimeField(auto_now=True)
# last_reply_on = models.DateTimeField(auto_now_add=True)
# num_replies = models.PositiveSmallIntegerField(default = 0)
#
# #Moderation features
# announcement_flag = models.BooleanField(default=False)
# is_closed = models.BooleanField(default=False)
# is_sticky = models.BooleanField(default=False)
# is_hidden = models.BooleanField(default=False)
#
# # use TopicManager as default, prevent leaking of hidden topics
# default = models.Manager()
# objects = TopicManager()
#
# # for topic subscriptions
# subscribers = models.ManyToManyField(User, related_name='subscribers')
#
# class Meta:
# ordering = ('-is_sticky', '-last_reply_on',)
# get_latest_by = ('created_on')
# verbose_name = "Topic"
# verbose_name_plural = "Topics"
#
# def save(self, *args, **kwargs):
# if not self.slug:
# slug = slugify(self.subject)
# slug = slug[:198]
# same_slug_count = Ftopics.objects.filter(slug__startswith = slug).count()
# if same_slug_count:
# slug = slug + str(same_slug_count)
# self.slug = slug
# super(Ftopics, self).save(*args, **kwargs)
#
# def __unicode__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('dinette_topic_detail', kwargs={'categoryslug':self.category.slug, 'topic_slug': self.slug})
#
# def htmlfrombbcode(self):
# if(len(self.message.raw.strip()) > 0):
# return render_bbcode(self.message.raw)
# else :
# return ""
#
# def search_snippet(self):
# msg = "%s %s"% (self.subject, self.message.rendered)
# return truncatewords(msg, 50)
#
# def getTopicString(self):
# #which is helpful for doing reverse lookup of an feed url for a topic
# return "topic/%s" % self.slug
#
# def lastPostDatetime(self):
# return self.lastPost().created_on
#
# def lastPostedUser(self):
# return self.lastPost().posted_by.username
#
# def lastPost(self):
# if (self.reply_set.count() == 0):
# return self
# return self.reply_set.order_by('-created_on')[0]
#
# def classname(self):
# return self.__class__.__name__
#
# class SiteConfig(models.Model):
# name = models.CharField(max_length = 100)
# tag_line = models.TextField(max_length = 100)
#
# class NavLink(models.Model):
# title = models.CharField(max_length = 100)
# url = models.URLField()
#
# class Meta:
# verbose_name = "Navigation Link"
# verbose_name_plural = "Navigation Links"
#
# def __unicode__(self):
# return self.title
, which may include functions, classes, or code. Output only the next line. | context[self.as_varname] = NavLink.objects.all() |
Using the snippet: <|code_start|># encoding: utf-8
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for reply in orm.Reply.objects.all():
# migrate older bbcode replies to markup
<|code_end|>
, determine the next line of code. You have imports:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from dinette.libs.postmarkup import render_bbcode
and context (class names, function names, or code) available:
# Path: dinette/libs/postmarkup.py
# def render_bbcode(bbcode,
# encoding="ascii",
# exclude_tags=None,
# auto_urls=True,
# paragraphs=False,
# clean=True,
# tag_data=None):
#
# """ Renders a bbcode string in to XHTML. This is a shortcut if you don't
# need to customize any tags.
#
# post_markup -- String containing bbcode.
# encoding -- Encoding of string, defaults to "ascii" if the string is not
# already unicode.
# exclude_tags -- A collection of tag names to ignore.
# auto_urls -- If True, then urls will be wrapped with url bbcode tags.
# paragraphs -- If True then line breaks will be replaces with paragraph
# tags, rather than break tags.
# clean -- If True, html will be run through a cleanup_html method.
# tag_data -- An optional dictionary to store tag data in. The default of
# None will create a dictionary internally.
#
# """
# return _postmarkup(bbcode,
# encoding,
# exclude_tags=exclude_tags,
# auto_urls=auto_urls,
# paragraphs=paragraphs,
# clean=clean,
# tag_data=tag_data)
. Output only the next line. | reply._message_rendered = render_bbcode(reply.message.raw) |
Here is a snippet: <|code_start|>
class UserActivity:
def process_request(self, req):
if req.user.is_authenticated():
#last = req.user.get_profile().last_activity
try:
try:
user_profile = req.user.dinetteuserprofile
<|code_end|>
. Write the next line using the current file imports:
import datetime
from dinette.models import DinetteUserProfile
from django.conf import settings
from copy import deepcopy
and context from other files:
# Path: dinette/models.py
# class DinetteUserProfile(models.Model):
# user = models.OneToOneField(User)
# last_activity = models.DateTimeField(auto_now_add=True)
# #When was the last session. Used in page activity since last session.
# last_session_activity = models.DateTimeField(auto_now_add=True)
# userrank = models.CharField(max_length=30, default="Junior Member")
# last_posttime = models.DateTimeField(auto_now_add=True)
# photo = models.ImageField(upload_to='dinette/files', null=True, blank=True)
# signature = models.CharField(max_length = 1000, null = True, blank = True)
# slug = models.SlugField(max_length=200, db_index=True, unique=True)
# is_subscribed_to_digest = models.BooleanField(default=False)
#
# def __unicode__(self):
# return self.user.username
#
# #Populate the user fields for easy access
# @property
# def username(self):
# return self.user.username
#
# @property
# def first_name(self):
# return self.user.first_name
#
# @property
# def last_name(self):
# return self.user.last_name
#
# def get_total_posts(self):
# print self.user.ftopics_set.count() + self.user.reply_set.count()
# return self.user.ftopics_set.count() + self.user.reply_set.count()
#
# def is_online(self):
# from django.conf import settings
# last_online_duration = getattr(settings, 'LAST_ONLINE_DURATION', 900)
# now = datetime.datetime.now()
# if (now - self.last_activity).seconds < last_online_duration:
# return True
# return False
#
# def getMD5(self):
# m = hashlib.md5()
# m.update(self.user.email)
# return m.hexdigest()
#
# def get_since_last_visit(self):
# "Topics with new relies since last visit"
# return Ftopics.objects.get_new_since(self.last_session_activity)
#
# @models.permalink
# def get_absolute_url(self):
# return ('dinette_user_profile', [self.slug])
#
# def save(self, *args, **kwargs):
# if not self.slug:
# slug = slugify(self.user.username)
# if slug:
# same_slug_count = self._default_manager.filter(slug__startswith=slug).count()
# if same_slug_count:
# slug = slug + str(same_slug_count)
# self.slug = slug
# else:
# #fallback to user id
# slug = self.user.id
# super(DinetteUserProfile, self).save(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | except DinetteUserProfile.DoesNotExist: |
Given snippet: <|code_start|> url(r'^users/(?P<slug>[\w-]+)$', 'user_profile', name='dinette_user_profile'),
# subscribe to digest
url(r'^digest/subscribe/$', 'subscribeDigest', name='dinette_subscribe_to_digest'),
url(r'^digest/unsubscribe/$', 'unsubscribeDigest', name='dinette_unsubscribe_from_digest'),
url(r'^(?P<categoryslug>[\w-]+)/$','category_details', name='dinette_index'),
url(r'^(?P<categoryslug>[\w-]+)/page(?P<pageno>\d+)/$','category_details', name='dinette_index2'),
url(r'^post/topic/$','postTopic', name='dinette_posttopic'),
url(r'^post/reply/$','postReply', name='dinette_postreply'),
url(r'^(?P<categoryslug>[\w-]+)/(?P<topic_slug>[\w-]+)/$','topic_detail', name='dinette_topic_detail'),
url(r'^(?P<categoryslug>[\w-]+)/(?P<topic_slug>[\w-]+)/page(?P<pageno>\d+)/$','topic_detail', name='dinette_reply_detail_paged'),
#moderation views - Hence dont bother with SEF urls
url(r'^moderate/topic/(?P<topic_id>\d+)/close/$','moderate_topic', {'action':'close'}, name='dinette_moderate_close'),
url(r'^moderate/topic/(?P<topic_id>\d+)/stickyfy/$','moderate_topic', {'action':'sticky'}, name='dinette_moderate_sticky'),
url(r'^moderate/topic/(?P<topic_id>\d+)/annoucement/$','moderate_topic', {'action':'announce'}, name='dinette_moderate_announce'),
url(r'^moderate/topic/(?P<topic_id>\d+)/hide/$','moderate_topic', {'action':'hide'}, name='dinette_moderate_hide'),
# post actions, permitted to OP and mods
url(r'^delete/reply/(?P<reply_id>\d+)$','deleteReply', name='dinette_deletereply'),
url(r'^edit/reply/(?P<reply_id>\d+)$','editReply', name='dinette_editreply'),
# subscribe to topic
url(r'^subscribe/topic/(?P<topic_id>\d+)', 'subscribeTopic', name='dinette_subscribe_to_topic'),
url(r'^unsubscribe/topic/(?P<topic_id>\d+)', 'unsubscribeTopic', name='dinette_unsubscribe_from_topic'),
)
urlpatterns += patterns('',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import *
from dinette.views import LatestTopicsByCategory,LatestRepliesOfTopic
and context:
# Path: dinette/views.py
# class LatestTopicsByCategory(Feed):
# title_template = 'dinette/feeds/title.html'
# description_template = 'dinette/feeds/description.html'
#
# def get_object(self, request, whichcategory):
# mlogger.debug("Feed for category %s " % whichcategory)
# return get_object_or_404(Category, slug=whichcategory)
#
# def title(self, obj):
# return "Latest topics in category %s" % obj.name
#
# def link(self, obj):
# return settings.SITE_URL
#
# def items(self, obj):
# return obj.ftopics_set.all()[:10]
#
# #construct these links by means of reverse lookup by
# #using permalink decorator
# def item_link(self,obj):
# return obj.get_absolute_url()
#
# def item_pubdate(self,obj):
# return obj.created_on
#
# class LatestRepliesOfTopic(Feed):
# title_template = 'dinette/feeds/title.html'
# description_template = 'dinette/feeds/description.html'
#
# def get_object(self, request, whichtopic):
# mlogger.debug("Feed for category %s " % whichtopic)
# return get_object_or_404(Ftopics, slug=whichtopic)
#
# def title(self, obj):
# return "Latest replies in topic %s" % obj.subject
#
# def link(self, obj):
# return settings.SITE_URL
#
# def items(self, obj):
# list = []
# list.insert(0,obj)
# for obj in obj.reply_set.all()[:10] :
# list.append(obj)
# return list
#
# #construct these links by means of reverse lookup by
# #using permalink decorator
# def item_link(self,obj):
# return obj.get_absolute_url()
#
# def item_pubdate(self,obj):
# return obj.created_on
which might include code, classes, or functions. Output only the next line. | url(r'^feeds/category/(?P<whichcategory>[\w/-]+)/$', LatestTopicsByCategory(), name='dinette_feed_url'), |
Given snippet: <|code_start|>
# subscribe to digest
url(r'^digest/subscribe/$', 'subscribeDigest', name='dinette_subscribe_to_digest'),
url(r'^digest/unsubscribe/$', 'unsubscribeDigest', name='dinette_unsubscribe_from_digest'),
url(r'^(?P<categoryslug>[\w-]+)/$','category_details', name='dinette_index'),
url(r'^(?P<categoryslug>[\w-]+)/page(?P<pageno>\d+)/$','category_details', name='dinette_index2'),
url(r'^post/topic/$','postTopic', name='dinette_posttopic'),
url(r'^post/reply/$','postReply', name='dinette_postreply'),
url(r'^(?P<categoryslug>[\w-]+)/(?P<topic_slug>[\w-]+)/$','topic_detail', name='dinette_topic_detail'),
url(r'^(?P<categoryslug>[\w-]+)/(?P<topic_slug>[\w-]+)/page(?P<pageno>\d+)/$','topic_detail', name='dinette_reply_detail_paged'),
#moderation views - Hence dont bother with SEF urls
url(r'^moderate/topic/(?P<topic_id>\d+)/close/$','moderate_topic', {'action':'close'}, name='dinette_moderate_close'),
url(r'^moderate/topic/(?P<topic_id>\d+)/stickyfy/$','moderate_topic', {'action':'sticky'}, name='dinette_moderate_sticky'),
url(r'^moderate/topic/(?P<topic_id>\d+)/annoucement/$','moderate_topic', {'action':'announce'}, name='dinette_moderate_announce'),
url(r'^moderate/topic/(?P<topic_id>\d+)/hide/$','moderate_topic', {'action':'hide'}, name='dinette_moderate_hide'),
# post actions, permitted to OP and mods
url(r'^delete/reply/(?P<reply_id>\d+)$','deleteReply', name='dinette_deletereply'),
url(r'^edit/reply/(?P<reply_id>\d+)$','editReply', name='dinette_editreply'),
# subscribe to topic
url(r'^subscribe/topic/(?P<topic_id>\d+)', 'subscribeTopic', name='dinette_subscribe_to_topic'),
url(r'^unsubscribe/topic/(?P<topic_id>\d+)', 'unsubscribeTopic', name='dinette_unsubscribe_from_topic'),
)
urlpatterns += patterns('',
url(r'^feeds/category/(?P<whichcategory>[\w/-]+)/$', LatestTopicsByCategory(), name='dinette_feed_url'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import *
from dinette.views import LatestTopicsByCategory,LatestRepliesOfTopic
and context:
# Path: dinette/views.py
# class LatestTopicsByCategory(Feed):
# title_template = 'dinette/feeds/title.html'
# description_template = 'dinette/feeds/description.html'
#
# def get_object(self, request, whichcategory):
# mlogger.debug("Feed for category %s " % whichcategory)
# return get_object_or_404(Category, slug=whichcategory)
#
# def title(self, obj):
# return "Latest topics in category %s" % obj.name
#
# def link(self, obj):
# return settings.SITE_URL
#
# def items(self, obj):
# return obj.ftopics_set.all()[:10]
#
# #construct these links by means of reverse lookup by
# #using permalink decorator
# def item_link(self,obj):
# return obj.get_absolute_url()
#
# def item_pubdate(self,obj):
# return obj.created_on
#
# class LatestRepliesOfTopic(Feed):
# title_template = 'dinette/feeds/title.html'
# description_template = 'dinette/feeds/description.html'
#
# def get_object(self, request, whichtopic):
# mlogger.debug("Feed for category %s " % whichtopic)
# return get_object_or_404(Ftopics, slug=whichtopic)
#
# def title(self, obj):
# return "Latest replies in topic %s" % obj.subject
#
# def link(self, obj):
# return settings.SITE_URL
#
# def items(self, obj):
# list = []
# list.insert(0,obj)
# for obj in obj.reply_set.all()[:10] :
# list.append(obj)
# return list
#
# #construct these links by means of reverse lookup by
# #using permalink decorator
# def item_link(self,obj):
# return obj.get_absolute_url()
#
# def item_pubdate(self,obj):
# return obj.created_on
which might include code, classes, or functions. Output only the next line. | url(r'^feeds/topic/(?P<whichtopic>[\w/-]+)/$', LatestRepliesOfTopic() ,name='dinette_topic_url'), |
Given snippet: <|code_start|> uid = uid_tag.text
else:
uid = None
if text_tag is not None and text_tag.text:
raw_text = text_tag.text
else:
raw_text = None
# TODO: factor this out and reuse fix_agents
db_refs = {}
# Save raw text if available
if raw_text:
db_refs['TEXT'] = raw_text
agent_name = raw_text
# If we have a proper UID then we try to reconstruct an Agent from that
if uid is not None and len(uid.split(':')) == 2:
db_ns, db_id = uid.split(':')
be_id = famplex_map.get((db_ns, db_id))
if be_id:
db_refs[db_ns] = db_id
db_refs['FPLX'] = be_id
agent_name = be_id
elif db_ns in ['UP', 'Uniprot']:
id_from_mnemonic = uniprot_client.get_id_from_mnemonic(db_id)
if id_from_mnemonic:
db_id = id_from_mnemonic
db_refs['UP'] = db_id
hgnc_id = uniprot_client.get_hgnc_id(db_id)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from collections import defaultdict
from indra.statements import *
from indra.literature import id_lookup
from indra.databases import uniprot_client, hgnc_client
from .processor import ncit_map, famplex_map
and context:
# Path: indra/databases/hgnc_client.py
# def get_uniprot_id(hgnc_id):
# def get_entrez_id(hgnc_id):
# def get_hgnc_from_entrez(entrez_id):
# def get_ensembl_id(hgnc_id):
# def get_hgnc_from_ensembl(ensembl_id):
# def get_hgnc_name(hgnc_id):
# def get_hgnc_id(hgnc_name):
# def get_current_hgnc_id(hgnc_name):
# def get_hgnc_from_mouse(mgi_id):
# def get_hgnc_from_rat(rgd_id):
# def get_rat_id(hgnc_id):
# def get_mouse_id(hgnc_id):
# def get_hgnc_entry(hgnc_id):
# def get_gene_type(hgnc_id: str) -> Union[str, None]:
# def is_kinase(gene_name):
# def is_transcription_factor(gene_name):
# def is_phosphatase(gene_name):
# def get_enzymes(hgnc_id: str) -> Set[str]:
# def get_hgncs_from_enzyme(ec_code: str) -> Set[str]:
# def _read_hgnc_maps():
# def _read_kinases():
# def _read_phosphatases():
# def _read_tfs():
#
# Path: indra/sources/sparser/processor.py
# class SparserJSONProcessor(object):
# class SparserError(ValueError):
# class InvalidAgent(SparserError):
# class TranslocationWithoutLocations(SparserError):
# class MissingSubj(SparserError):
# class MissingObj(SparserError):
# class UnaryComplex(SparserError):
# class NoAgents(SparserError):
# class MissingEvidenceText(SparserError):
# class InvalidEvidence(SparserError):
# def __init__(self, json_dict):
# def get_statements(self):
# def set_statements_pmid(self, pmid):
# def get_error_stats(self):
# def fix_agent(agent):
# def fix_json_stmt(json_stmt):
# def fix_json_agent(ag_obj):
# def check_statement_sanity(stmt):
# def _read_ncit_map():
# def _read_famplex_map():
which might include code, classes, or functions. Output only the next line. | agent_name = hgnc_client.get_hgnc_name(hgnc_id) |
Next line prediction: <|code_start|>
# TODO: factor this out and reuse fix_agents
db_refs = {}
# Save raw text if available
if raw_text:
db_refs['TEXT'] = raw_text
agent_name = raw_text
# If we have a proper UID then we try to reconstruct an Agent from that
if uid is not None and len(uid.split(':')) == 2:
db_ns, db_id = uid.split(':')
be_id = famplex_map.get((db_ns, db_id))
if be_id:
db_refs[db_ns] = db_id
db_refs['FPLX'] = be_id
agent_name = be_id
elif db_ns in ['UP', 'Uniprot']:
id_from_mnemonic = uniprot_client.get_id_from_mnemonic(db_id)
if id_from_mnemonic:
db_id = id_from_mnemonic
db_refs['UP'] = db_id
hgnc_id = uniprot_client.get_hgnc_id(db_id)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
agent_name = hgnc_client.get_hgnc_name(hgnc_id)
else:
gene_name = uniprot_client.get_gene_name(db_id)
if gene_name:
agent_name = gene_name
elif db_ns == 'NCIT':
db_refs['NCIT'] = db_id
<|code_end|>
. Use current file imports:
(import logging
from collections import defaultdict
from indra.statements import *
from indra.literature import id_lookup
from indra.databases import uniprot_client, hgnc_client
from .processor import ncit_map, famplex_map)
and context including class names, function names, or small code snippets from other files:
# Path: indra/databases/hgnc_client.py
# def get_uniprot_id(hgnc_id):
# def get_entrez_id(hgnc_id):
# def get_hgnc_from_entrez(entrez_id):
# def get_ensembl_id(hgnc_id):
# def get_hgnc_from_ensembl(ensembl_id):
# def get_hgnc_name(hgnc_id):
# def get_hgnc_id(hgnc_name):
# def get_current_hgnc_id(hgnc_name):
# def get_hgnc_from_mouse(mgi_id):
# def get_hgnc_from_rat(rgd_id):
# def get_rat_id(hgnc_id):
# def get_mouse_id(hgnc_id):
# def get_hgnc_entry(hgnc_id):
# def get_gene_type(hgnc_id: str) -> Union[str, None]:
# def is_kinase(gene_name):
# def is_transcription_factor(gene_name):
# def is_phosphatase(gene_name):
# def get_enzymes(hgnc_id: str) -> Set[str]:
# def get_hgncs_from_enzyme(ec_code: str) -> Set[str]:
# def _read_hgnc_maps():
# def _read_kinases():
# def _read_phosphatases():
# def _read_tfs():
#
# Path: indra/sources/sparser/processor.py
# class SparserJSONProcessor(object):
# class SparserError(ValueError):
# class InvalidAgent(SparserError):
# class TranslocationWithoutLocations(SparserError):
# class MissingSubj(SparserError):
# class MissingObj(SparserError):
# class UnaryComplex(SparserError):
# class NoAgents(SparserError):
# class MissingEvidenceText(SparserError):
# class InvalidEvidence(SparserError):
# def __init__(self, json_dict):
# def get_statements(self):
# def set_statements_pmid(self, pmid):
# def get_error_stats(self):
# def fix_agent(agent):
# def fix_json_stmt(json_stmt):
# def fix_json_agent(ag_obj):
# def check_statement_sanity(stmt):
# def _read_ncit_map():
# def _read_famplex_map():
. Output only the next line. | target = ncit_map.get(db_id) |
Given snippet: <|code_start|> #logger.warning('Skipping collection Agent.')
return None
# Find the name, uid and raw-text tags first and get their text
# content if available
uid_tag = ref.find("var/[@name='uid']")
name_tag = ref.find("var/[@name='name']")
text_tag = ref.find("var/[@name='raw-text']")
if name_tag is not None and name_tag.text:
name = name_tag.text
else:
name = None
if uid_tag is not None and uid_tag.text:
uid = uid_tag.text
else:
uid = None
if text_tag is not None and text_tag.text:
raw_text = text_tag.text
else:
raw_text = None
# TODO: factor this out and reuse fix_agents
db_refs = {}
# Save raw text if available
if raw_text:
db_refs['TEXT'] = raw_text
agent_name = raw_text
# If we have a proper UID then we try to reconstruct an Agent from that
if uid is not None and len(uid.split(':')) == 2:
db_ns, db_id = uid.split(':')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from collections import defaultdict
from indra.statements import *
from indra.literature import id_lookup
from indra.databases import uniprot_client, hgnc_client
from .processor import ncit_map, famplex_map
and context:
# Path: indra/databases/hgnc_client.py
# def get_uniprot_id(hgnc_id):
# def get_entrez_id(hgnc_id):
# def get_hgnc_from_entrez(entrez_id):
# def get_ensembl_id(hgnc_id):
# def get_hgnc_from_ensembl(ensembl_id):
# def get_hgnc_name(hgnc_id):
# def get_hgnc_id(hgnc_name):
# def get_current_hgnc_id(hgnc_name):
# def get_hgnc_from_mouse(mgi_id):
# def get_hgnc_from_rat(rgd_id):
# def get_rat_id(hgnc_id):
# def get_mouse_id(hgnc_id):
# def get_hgnc_entry(hgnc_id):
# def get_gene_type(hgnc_id: str) -> Union[str, None]:
# def is_kinase(gene_name):
# def is_transcription_factor(gene_name):
# def is_phosphatase(gene_name):
# def get_enzymes(hgnc_id: str) -> Set[str]:
# def get_hgncs_from_enzyme(ec_code: str) -> Set[str]:
# def _read_hgnc_maps():
# def _read_kinases():
# def _read_phosphatases():
# def _read_tfs():
#
# Path: indra/sources/sparser/processor.py
# class SparserJSONProcessor(object):
# class SparserError(ValueError):
# class InvalidAgent(SparserError):
# class TranslocationWithoutLocations(SparserError):
# class MissingSubj(SparserError):
# class MissingObj(SparserError):
# class UnaryComplex(SparserError):
# class NoAgents(SparserError):
# class MissingEvidenceText(SparserError):
# class InvalidEvidence(SparserError):
# def __init__(self, json_dict):
# def get_statements(self):
# def set_statements_pmid(self, pmid):
# def get_error_stats(self):
# def fix_agent(agent):
# def fix_json_stmt(json_stmt):
# def fix_json_agent(ag_obj):
# def check_statement_sanity(stmt):
# def _read_ncit_map():
# def _read_famplex_map():
which might include code, classes, or functions. Output only the next line. | be_id = famplex_map.get((db_ns, db_id)) |
Using the snippet: <|code_start|> @staticmethod
def _get_drug_agent(drug_element):
name_tag = db_find(drug_element, 'db:name')
name = name_tag.text
db_refs = {}
# Extract the DrugBank ID
drugbank_id_tags = db_findall(drug_element, 'db:drugbank-id')
# We do a sort here because sometimes there's more than one
# DrugBank ID and we choose the "smaller" one here
drugbank_id = sorted([di.text for di in drugbank_id_tags
if di.text.startswith('DB')])[0]
db_refs['DRUGBANK'] = drugbank_id
# Extract CAS ID
cas_tag = db_find(drug_element, 'db:cas-number')
if cas_tag is not None and cas_tag.text is not None:
db_refs['CAS'] = cas_tag.text
# Extract other xrefs
for xref_tag in db_findall(drug_element, 'db:external-identifiers/'
'db:external-identifier'):
resource = db_find(xref_tag, 'db:resource').text
identifier = db_find(xref_tag, 'db:identifier').text
if resource == 'ChEMBL':
db_refs['CHEMBL'] = ensure_chembl_prefix(identifier)
elif resource == 'PubChem Compound':
db_refs['PUBCHEM'] = identifier
elif resource == 'ChEBI':
<|code_end|>
, determine the next line of code. You have imports:
import logging
from xml.etree import ElementTree
from indra.statements import *
from indra.databases.identifiers import ensure_chebi_prefix, \
ensure_chembl_prefix
from indra.statements.validate import assert_valid_db_refs
from indra.ontology.standardize import standardize_name_db_refs, \
get_standard_agent
and context (class names, function names, or code) available:
# Path: indra/databases/identifiers.py
# def ensure_chebi_prefix(chebi_id):
# """Return a valid CHEBI ID that has the appropriate CHEBI: prefix."""
# return ensure_prefix('CHEBI', chebi_id)
#
# def ensure_chembl_prefix(chembl_id):
# """Return a valid CHEMBL ID that has the appropriate CHEMBL prefix."""
# return ensure_prefix('CHEMBL', chembl_id, with_colon=False)
#
# Path: indra/ontology/standardize.py
# def standardize_name_db_refs(db_refs, ontology=None, ns_order=None):
# """Return a standardized name and db refs dict for a given db refs dict.
#
# Parameters
# ----------
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
#
# Returns
# -------
# str or None
# The standard name based on the db refs, None if not available.
# dict
# The db_refs dict with standardized entries.
# """
# db_refs = standardize_db_refs(db_refs, ontology=ontology,
# ns_order=ns_order)
# name = get_standard_name(db_refs, ontology=ontology, ns_order=ns_order)
# return name, db_refs
#
# def get_standard_agent(name, db_refs, ontology=None, ns_order=None, **kwargs):
# """Get a standard agent based on the name, db_refs, and a any other kwargs.
#
# name : str
# The name of the agent that may not be standardized.
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
# kwargs :
# Keyword arguments to pass to :func:`Agent.__init__`.
#
# Returns
# -------
# Agent
# A standard agent
# """
# standard_name, db_refs = standardize_name_db_refs(db_refs,
# ontology=ontology,
# ns_order=ns_order)
# if standard_name:
# name = standard_name
# assert_valid_db_refs(db_refs)
# return Agent(name, db_refs=db_refs, **kwargs)
. Output only the next line. | db_refs['CHEBI'] = ensure_chebi_prefix(identifier) |
Given snippet: <|code_start|> elif resource == 'UniProtKB':
db_refs['UP'] = identifier
return get_standard_agent(name, db_refs=db_refs)
@staticmethod
def _get_drug_agent(drug_element):
name_tag = db_find(drug_element, 'db:name')
name = name_tag.text
db_refs = {}
# Extract the DrugBank ID
drugbank_id_tags = db_findall(drug_element, 'db:drugbank-id')
# We do a sort here because sometimes there's more than one
# DrugBank ID and we choose the "smaller" one here
drugbank_id = sorted([di.text for di in drugbank_id_tags
if di.text.startswith('DB')])[0]
db_refs['DRUGBANK'] = drugbank_id
# Extract CAS ID
cas_tag = db_find(drug_element, 'db:cas-number')
if cas_tag is not None and cas_tag.text is not None:
db_refs['CAS'] = cas_tag.text
# Extract other xrefs
for xref_tag in db_findall(drug_element, 'db:external-identifiers/'
'db:external-identifier'):
resource = db_find(xref_tag, 'db:resource').text
identifier = db_find(xref_tag, 'db:identifier').text
if resource == 'ChEMBL':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from xml.etree import ElementTree
from indra.statements import *
from indra.databases.identifiers import ensure_chebi_prefix, \
ensure_chembl_prefix
from indra.statements.validate import assert_valid_db_refs
from indra.ontology.standardize import standardize_name_db_refs, \
get_standard_agent
and context:
# Path: indra/databases/identifiers.py
# def ensure_chebi_prefix(chebi_id):
# """Return a valid CHEBI ID that has the appropriate CHEBI: prefix."""
# return ensure_prefix('CHEBI', chebi_id)
#
# def ensure_chembl_prefix(chembl_id):
# """Return a valid CHEMBL ID that has the appropriate CHEMBL prefix."""
# return ensure_prefix('CHEMBL', chembl_id, with_colon=False)
#
# Path: indra/ontology/standardize.py
# def standardize_name_db_refs(db_refs, ontology=None, ns_order=None):
# """Return a standardized name and db refs dict for a given db refs dict.
#
# Parameters
# ----------
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
#
# Returns
# -------
# str or None
# The standard name based on the db refs, None if not available.
# dict
# The db_refs dict with standardized entries.
# """
# db_refs = standardize_db_refs(db_refs, ontology=ontology,
# ns_order=ns_order)
# name = get_standard_name(db_refs, ontology=ontology, ns_order=ns_order)
# return name, db_refs
#
# def get_standard_agent(name, db_refs, ontology=None, ns_order=None, **kwargs):
# """Get a standard agent based on the name, db_refs, and a any other kwargs.
#
# name : str
# The name of the agent that may not be standardized.
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
# kwargs :
# Keyword arguments to pass to :func:`Agent.__init__`.
#
# Returns
# -------
# Agent
# A standard agent
# """
# standard_name, db_refs = standardize_name_db_refs(db_refs,
# ontology=ontology,
# ns_order=ns_order)
# if standard_name:
# name = standard_name
# assert_valid_db_refs(db_refs)
# return Agent(name, db_refs=db_refs, **kwargs)
which might include code, classes, or functions. Output only the next line. | db_refs['CHEMBL'] = ensure_chembl_prefix(identifier) |
Predict the next line for this snippet: <|code_start|> elif action in decrease_amount_actions:
return DecreaseAmount
elif action in increase_amount_actions:
return IncreaseAmount
elif action == 'N/A':
return Inhibition
else:
return None
@staticmethod
def _get_target_agent(target_element):
name_tag = db_find(target_element, 'db:name')
name = name_tag.text
db_refs = {}
# Get Drugbank target ID
target_id = db_find(target_element, 'db:id').text
db_refs['DRUGBANKV4.TARGET'] = target_id
# Extract other xrefs
for xref_tag in db_findall(target_element, 'db:polypeptide/'
'db:external-identifiers/'
'db:external-identifier'):
resource = db_find(xref_tag, 'db:resource').text
identifier = db_find(xref_tag, 'db:identifier').text
if resource == 'HUGO Gene Nomenclature Committee (HGNC)':
db_refs['HGNC'] = identifier[5:]
elif resource == 'UniProtKB':
db_refs['UP'] = identifier
<|code_end|>
with the help of current file imports:
import logging
from xml.etree import ElementTree
from indra.statements import *
from indra.databases.identifiers import ensure_chebi_prefix, \
ensure_chembl_prefix
from indra.statements.validate import assert_valid_db_refs
from indra.ontology.standardize import standardize_name_db_refs, \
get_standard_agent
and context from other files:
# Path: indra/databases/identifiers.py
# def ensure_chebi_prefix(chebi_id):
# """Return a valid CHEBI ID that has the appropriate CHEBI: prefix."""
# return ensure_prefix('CHEBI', chebi_id)
#
# def ensure_chembl_prefix(chembl_id):
# """Return a valid CHEMBL ID that has the appropriate CHEMBL prefix."""
# return ensure_prefix('CHEMBL', chembl_id, with_colon=False)
#
# Path: indra/ontology/standardize.py
# def standardize_name_db_refs(db_refs, ontology=None, ns_order=None):
# """Return a standardized name and db refs dict for a given db refs dict.
#
# Parameters
# ----------
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
#
# Returns
# -------
# str or None
# The standard name based on the db refs, None if not available.
# dict
# The db_refs dict with standardized entries.
# """
# db_refs = standardize_db_refs(db_refs, ontology=ontology,
# ns_order=ns_order)
# name = get_standard_name(db_refs, ontology=ontology, ns_order=ns_order)
# return name, db_refs
#
# def get_standard_agent(name, db_refs, ontology=None, ns_order=None, **kwargs):
# """Get a standard agent based on the name, db_refs, and a any other kwargs.
#
# name : str
# The name of the agent that may not be standardized.
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
# kwargs :
# Keyword arguments to pass to :func:`Agent.__init__`.
#
# Returns
# -------
# Agent
# A standard agent
# """
# standard_name, db_refs = standardize_name_db_refs(db_refs,
# ontology=ontology,
# ns_order=ns_order)
# if standard_name:
# name = standard_name
# assert_valid_db_refs(db_refs)
# return Agent(name, db_refs=db_refs, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | return get_standard_agent(name, db_refs=db_refs) |
Based on the snippet: <|code_start|> source,
interaction,
drug_name,
drug_curie,
pmids,
) in self.df.values:
if source in self.skip_databases:
continue
self.statements.extend(self.row_to_statements(
gene_name,
ncbigene_id,
source,
interaction,
drug_name,
drug_curie,
pmids,
))
return self.statements
def row_to_statements(
self,
gene_name,
ncbigene_id,
source,
interactions,
drug_name,
drug_curie,
pmids,
) -> Iterable[Statement]:
"""Convert a row in the DGI dataframe to a statement."""
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import pandas as pd
from typing import Iterable, List, Optional, Set, Type
from ...ontology.standardize import get_standard_agent
from ...statements import (
default_ns_order,
Activation,
Complex,
DecreaseAmount,
Evidence,
IncreaseAmount,
Inhibition,
Statement,
)
from .api import get_version_df
and context (classes, functions, sometimes code) from other files:
# Path: indra/ontology/standardize.py
# def get_standard_agent(name, db_refs, ontology=None, ns_order=None, **kwargs):
# """Get a standard agent based on the name, db_refs, and a any other kwargs.
#
# name : str
# The name of the agent that may not be standardized.
# db_refs : dict
# A dict of db refs that may not be standardized, i.e., may be
# missing an available UP ID corresponding to an existing HGNC ID.
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
# kwargs :
# Keyword arguments to pass to :func:`Agent.__init__`.
#
# Returns
# -------
# Agent
# A standard agent
# """
# standard_name, db_refs = standardize_name_db_refs(db_refs,
# ontology=ontology,
# ns_order=ns_order)
# if standard_name:
# name = standard_name
# assert_valid_db_refs(db_refs)
# return Agent(name, db_refs=db_refs, **kwargs)
. Output only the next line. | gene_agent = get_standard_agent(gene_name, {"EGID": ncbigene_id}) |
Next line prediction: <|code_start|>
def extract_statements(self):
"""Process the table to extract Statements."""
for _, (tf, target, effect, refs) in self.df.iterrows():
tf_agent = get_grounded_agent(tf)
target_agent = get_grounded_agent(target)
if effect == 'Activation':
stmt_cls = IncreaseAmount
elif effect == 'Repression':
stmt_cls = DecreaseAmount
else:
continue
pmids = refs.split(';')
for pmid in pmids:
stmt = make_stmt(stmt_cls, tf_agent, target_agent, pmid)
self.statements.append(stmt)
def make_stmt(stmt_cls, tf_agent, target_agent, pmid):
"""Return a Statement based on its type, agents, and PMID."""
ev = Evidence(source_api='trrust', pmid=pmid)
return stmt_cls(deepcopy(tf_agent), deepcopy(target_agent),
evidence=[ev])
def get_grounded_agent(gene_name):
"""Return a grounded Agent based on an HGNC symbol."""
db_refs = {'TEXT': gene_name}
if gene_name in hgnc_map:
gene_name = hgnc_map[gene_name]
<|code_end|>
. Use current file imports:
(from copy import deepcopy
from indra.databases import hgnc_client
from indra.statements import Agent, IncreaseAmount, DecreaseAmount, Evidence)
and context including class names, function names, or small code snippets from other files:
# Path: indra/databases/hgnc_client.py
# def get_uniprot_id(hgnc_id):
# def get_entrez_id(hgnc_id):
# def get_hgnc_from_entrez(entrez_id):
# def get_ensembl_id(hgnc_id):
# def get_hgnc_from_ensembl(ensembl_id):
# def get_hgnc_name(hgnc_id):
# def get_hgnc_id(hgnc_name):
# def get_current_hgnc_id(hgnc_name):
# def get_hgnc_from_mouse(mgi_id):
# def get_hgnc_from_rat(rgd_id):
# def get_rat_id(hgnc_id):
# def get_mouse_id(hgnc_id):
# def get_hgnc_entry(hgnc_id):
# def get_gene_type(hgnc_id: str) -> Union[str, None]:
# def is_kinase(gene_name):
# def is_transcription_factor(gene_name):
# def is_phosphatase(gene_name):
# def get_enzymes(hgnc_id: str) -> Set[str]:
# def get_hgncs_from_enzyme(ec_code: str) -> Set[str]:
# def _read_hgnc_maps():
# def _read_kinases():
# def _read_phosphatases():
# def _read_tfs():
. Output only the next line. | hgnc_id = hgnc_client.get_hgnc_id(gene_name) |
Predict the next line for this snippet: <|code_start|>__all__ = ['process_from_web', 'process_files', 'process_df']
ACSN_URL = 'https://acsn.curie.fr/ACSN2/downloads/'
ACSN_RELATIONS_URL = ACSN_URL + \
'ACSN2_binary_relations_between_proteins_with_PMID.txt'
ACSN_CORRESPONDENCE_URL = ACSN_URL + 'ACSN2_HUGO_Correspondence.gmt'
<|code_end|>
with the help of current file imports:
from typing import Mapping
from .processor import AcsnProcessor
import pandas
import requests
and context from other files:
# Path: indra/sources/acsn/processor.py
# class AcsnProcessor:
# """Processes Atlas of cancer signalling network (ACSN) relationships
# into INDRA statements
#
# Attributes
# ----------
# relations_df : pandas.DataFrame
# A tab-separated data frame which consists of binary relationship between
# proteins with PMIDs.
# correspondence_dict : dict
# A dictionary with correspondences between ACSN entities and their
# HGNC symbols.
# """
# def __init__(self, relations_df, correspondence_dict):
# """Constructor for AcsnProcessor class"""
# self.relations_df = relations_df
# self.correspondence_dict = correspondence_dict
# self.fplx_lookup = _make_famplex_lookup()
# self.statements = []
#
# def extract_statements(self):
# """Return INDRA Statements Extracted from ACSN relations."""
# for _, row in self.relations_df.iterrows():
# acsn_agent_a, stmt_types, acsn_agent_b, pmids = list(row)
# stmt_type = get_stmt_type(stmt_types)
# if stmt_type:
# agent_a = self.get_agent(acsn_agent_a)
# agent_b = self.get_agent(acsn_agent_b)
# if agent_a and agent_b:
# if str(pmids) == 'nan':
# evs = [Evidence(source_api='acsn')]
#
# else:
# evs = [Evidence(source_api='acsn', pmid=pmid)
# for pmid in pmids.split(';')]
#
# if stmt_type == Complex:
# stmt = stmt_type([agent_a, agent_b], evidence=evs)
# else:
# stmt = stmt_type(agent_a, agent_b, evidence=evs)
#
# self.statements.append(stmt)
#
# def get_agent(self, acsn_agent: str) -> Union[Agent, None]:
# """Return an INDRA Agent corresponding to an ACSN agent.
#
# Parameters
# ----------
# acsn_agent :
# Agent extracted from the relations statement data frame
#
# Returns
# -------
# :
# Returns INDRA agent with HGNC or FamPlex ID in db_refs. If there
# are no groundings available, we return None.
# """
# mapping = self.correspondence_dict.get(acsn_agent)
# if not mapping:
# return None
# if len(mapping) == 1:
# hgnc_id = get_hgnc_id(mapping[0])
# if hgnc_id:
# db_refs = {'HGNC': hgnc_id}
# return get_standard_agent(mapping[0], db_refs=db_refs)
# else:
# fplx_rel = self.fplx_lookup.get(tuple(sorted(
# self.correspondence_dict[acsn_agent])))
# if fplx_rel:
# db_refs = {'FPLX': fplx_rel}
# return get_standard_agent(fplx_rel, db_refs=db_refs)
# return None
, which may contain function names, class names, or code. Output only the next line. | def process_from_web() -> AcsnProcessor: |
Next line prediction: <|code_start|>from __future__ import absolute_import, print_function, unicode_literals
def test_get_uniprot_id():
hgnc_id = '6840'
<|code_end|>
. Use current file imports:
(from builtins import dict, str
from indra.databases import hgnc_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr)
and context including class names, function names, or small code snippets from other files:
# Path: indra/databases/hgnc_client.py
# def get_uniprot_id(hgnc_id):
# def get_entrez_id(hgnc_id):
# def get_hgnc_from_entrez(entrez_id):
# def get_ensembl_id(hgnc_id):
# def get_hgnc_from_ensembl(ensembl_id):
# def get_hgnc_name(hgnc_id):
# def get_hgnc_id(hgnc_name):
# def get_current_hgnc_id(hgnc_name):
# def get_hgnc_from_mouse(mgi_id):
# def get_hgnc_from_rat(rgd_id):
# def get_rat_id(hgnc_id):
# def get_mouse_id(hgnc_id):
# def get_hgnc_entry(hgnc_id):
# def get_gene_type(hgnc_id: str) -> Union[str, None]:
# def is_kinase(gene_name):
# def is_transcription_factor(gene_name):
# def is_phosphatase(gene_name):
# def get_enzymes(hgnc_id: str) -> Set[str]:
# def get_hgncs_from_enzyme(ec_code: str) -> Set[str]:
# def _read_hgnc_maps():
# def _read_kinases():
# def _read_phosphatases():
# def _read_tfs():
. Output only the next line. | uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) |
Given snippet: <|code_start|> otherwise. Reasons for a False response can be the lack of
evidence as well as failure to obtain text for grounding
disambiguation.
"""
success = False
# If the Statement doesn't have evidence for some reason, then there is
# no text to disambiguate by
# NOTE: we might want to try disambiguating by other agents in the
# Statement
if not stmt.evidence:
return False
# Initialize annotations if needed so Adeft predicted
# probabilities can be added to Agent annotations
annots = stmt.evidence[0].annotations
if 'agents' in annots:
if 'adeft' not in annots['agents']:
annots['agents']['adeft'] = \
{'adeft': [None for _ in stmt.agent_list()]}
else:
annots['agents'] = {'adeft': [None for _ in stmt.agent_list()]}
grounding_text = self._get_text_for_grounding(stmt, agent_txt)
def apply_grounding(agent, agent_txt, ns_and_id):
db_ns, db_id = ns_and_id.split(':', maxsplit=1)
if db_ns == 'CHEBI' and not db_id.startswith('CHEBI:'):
db_id = 'CHEBI:%s' % db_id
agent.db_refs = {'TEXT': agent_txt, db_ns: db_id}
agent.name = standard_name
logger.debug('Disambiguated %s to: %s, %s:%s' %
(agent_txt, standard_name, db_ns, db_id))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from indra.ontology.standardize \
import standardize_agent_name
from .gilda import ground_agent
from adeft import available_shortforms as available_adeft_models
from adeft.disambiguate import load_disambiguator
from indra_db.util.content_scripts import TextContentSessionHandler
from indra.literature.adeft_tools import universal_extract_text
from indra.literature import pubmed_client
and context:
# Path: indra/ontology/standardize.py
# def standardize_agent_name(agent, standardize_refs=True, ontology=None,
# ns_order=None):
# """Standardize the name of an Agent based on grounding information.
#
# The priority of which namespace is used as the bases for the
# standard name depends on
#
# Parameters
# ----------
# agent : indra.statements.Agent
# An INDRA Agent whose name attribute should be standardized based
# on grounding information.
# standardize_refs : Optional[bool]
# If True, this function assumes that the Agent's db_refs need to
# be standardized, e.g., HGNC mapped to UP.
# Default: True
# ontology : Optional[indra.ontology.IndraOntology]
# An IndraOntology object, if not provided, the default BioOntology
# is used.
# ns_order : Optional[list]
# A list of namespaces which are in order of priority with higher
# priority namespaces appearing earlier in the list.
#
# Returns
# -------
# bool
# True if a new name was set, False otherwise.
# """
# # If the Agent is None, we return immediately
# if agent is None:
# return False
# # If we want to standardize the Agent's db_refs, we call this now
# if standardize_refs:
# agent.db_refs = standardize_db_refs(agent.db_refs, ontology=ontology)
# # We next try to get a standard name based on the Agent's grounding
# standard_name = get_standard_name(agent.db_refs, ontology=ontology,
# ns_order=ns_order)
# # If we got a proper standard name, we apply it
# if standard_name:
# agent.name = standard_name
# return True
# return False
#
# Path: indra/preassembler/grounding_mapper/gilda.py
# def ground_agent(agent, txt, context=None, mode='web'):
# """Set the grounding of a given agent, by re-grounding with Gilda.
#
# This function changes the agent in place without returning a value.
#
# Parameters
# ----------
# agent : indra.statements.Agent
# The Agent whose db_refs shuld be changed.
# txt : str
# The text by which the Agent should be grounded.
# context : Optional[str]
# Any additional text context to help disambiguate the sense
# associated with txt.
# mode : Optional[str]
# If 'web', the web service given in the GILDA_URL config setting or
# environmental variable is used. Otherwise, the gilda package is
# attempted to be imported and used. Default: web
# """
# gr, results = get_grounding(txt, context, mode)
# if gr:
# db_refs = {'TEXT': txt}
# db_refs.update(gr)
# agent.db_refs = db_refs
# standardize_agent_name(agent, standardize_refs=True)
# return results
which might include code, classes, or functions. Output only the next line. | standardize_agent_name(agent, standardize_refs=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.