Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> variable_id = self.variable_id
variable_definition = self.variable_definition
data_uri = b.get_data_uri(variable_definition, x)
body_text = (
f'<table id="{x.id}" '
f'class="{self.mode_name} {self.view_name} {variable_id}">'
'<thead/><tbody/></table>')
js_texts = [
TABLE_JS_TEMPLATE.substitute({
'element_id': x.id,
'data_uri': data_uri,
}),
]
return {
'css_uris': [],
'js_uris': [],
'body_text': body_text,
'js_texts': js_texts,
}
def save_variable_data(target_path, data_by_id, variable_definitions):
variable_data_by_id = get_variable_data_by_id(
variable_definitions, data_by_id)
if target_path.suffix == '.dictionary':
with open(target_path, 'wt') as input_file:
variable_value_by_id = get_variable_value_by_id(
variable_data_by_id)
json.dump(variable_value_by_id, input_file)
elif len(variable_data_by_id) > 1:
<|code_end|>
. Write the next line using the current file imports:
import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch
and context from other files:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
, which may include functions, classes, or code. Output only the next line. | raise CrossComputeConfigurationError( |
Given the following code snippet before the placeholder: <|code_start|> }
def render_output(self, b: Batch, x: Element):
value = self.get_value(b)
try:
value = apply_functions(
value, x.function_names, self.function_by_name)
except KeyError as e:
L.error('%s function not supported for string', e)
body_text = (
f'<span id="{x.id}" '
f'class="{self.mode_name} {self.view_name} {self.variable_id}">'
f'{value}</span>')
return {
'css_uris': [],
'js_uris': [],
'body_text': body_text,
'js_texts': [],
}
class NumberView(StringView):
view_name = 'number'
input_type = 'number'
def parse(self, value):
try:
value = float(value)
except ValueError:
<|code_end|>
, predict the next line using imports from the current file:
import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch
and context including class names, function names, and sometimes code from other files:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
. Output only the next line. | raise CrossComputeDataError(f'{value} is not a number') |
Given snippet: <|code_start|> const thead = nodes[0], tbody = nodes[1];
let tr = document.createElement('tr');
for (let i = 0; i < columnCount; i++) {
const column = columns[i];
const th = document.createElement('th');
th.innerText = column;
tr.append(th);
}
thead.append(tr);
for (let i = 0; i < rowCount; i++) {
const row = rows[i];
tr = document.createElement('tr');
for (let j = 0; j < columnCount; j++) {
const td = document.createElement('td');
td.innerText = row[j];
tr.append(td);
}
tbody.append(tr);
}
})();''')
VARIABLE_VIEW_BY_NAME = {_.name: import_attribute(
_.value) for _ in entry_points().select(group='crosscompute.views')}
YIELD_DATA_BY_ID_BY_EXTENSION = {
'.csv': yield_data_by_id_from_csv,
'.txt': yield_data_by_id_from_txt,
}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch
and context:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
which might include code, classes, or functions. Output only the next line. | FILE_DATA_CACHE = FileCache( |
Using the snippet: <|code_start|># IMAGE_JS_TEMPLATE = Template('''''')
TABLE_JS_TEMPLATE = Template('''\
(async function () {
const response = await fetch('$data_uri');
const d = await response.json();
const columns = d['columns'], columnCount = columns.length;
const rows = d['data'], rowCount = rows.length;
const nodes = document.getElementById('$element_id').children;
const thead = nodes[0], tbody = nodes[1];
let tr = document.createElement('tr');
for (let i = 0; i < columnCount; i++) {
const column = columns[i];
const th = document.createElement('th');
th.innerText = column;
tr.append(th);
}
thead.append(tr);
for (let i = 0; i < rowCount; i++) {
const row = rows[i];
tr = document.createElement('tr');
for (let j = 0; j < columnCount; j++) {
const td = document.createElement('td');
td.innerText = row[j];
tr.append(td);
}
tbody.append(tr);
}
})();''')
<|code_end|>
, determine the next line of code. You have imports:
import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch
and context (class names, function names, or code) available:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
. Output only the next line. | VARIABLE_VIEW_BY_NAME = {_.name: import_attribute( |
Predict the next line for this snippet: <|code_start|> view_name = 'text'
def render_input(self, b: Batch, x: Element):
view_name = self.view_name
variable_id = self.variable_id
value = self.get_value(b)
body_text = (
f'<textarea id="{x.id}" '
f'class="{self.mode_name} {view_name} {variable_id}" '
f'data-view="{view_name}" data-id="{variable_id}">'
f'{value}</textarea>')
js_texts = [
STRING_JS_TEMPLATE.substitute({
'view_name': view_name,
}),
]
return {
'css_uris': [],
'js_uris': [],
'body_text': body_text,
'js_texts': js_texts,
}
class MarkdownView(TextView):
view_name = 'markdown'
def render_output(self, b: Batch, x: Element):
value = self.get_value(b)
<|code_end|>
with the help of current file imports:
import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch
and context from other files:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
, which may contain function names, class names, or code. Output only the next line. | data = get_html_from_markdown(value) |
Next line prediction: <|code_start|> base_uri: str
mode_name: str
for_print: bool
function_names: list[str]
class VariableView():
view_name = 'variable'
environment_variable_definitions = []
def __init__(self, variable_definition):
self.variable_definition = variable_definition
self.variable_id = variable_definition.id
self.variable_path = variable_definition.path
self.mode_name = variable_definition.mode_name
@classmethod
def get_from(Class, variable_definition):
view_name = variable_definition.view_name
try:
View = VARIABLE_VIEW_BY_NAME[view_name]
except KeyError:
L.error('%s view not installed', view_name)
View = Class
return View(variable_definition)
def parse(self, data):
return data
<|code_end|>
. Use current file imports:
(import csv
import json
import shutil
from dataclasses import dataclass
from importlib_metadata import entry_points
from invisibleroads_macros_log import format_path
from logging import getLogger
from os.path import basename, exists
from string import Template
from ..constants import (
FUNCTION_BY_NAME,
MAXIMUM_FILE_CACHE_LENGTH,
VARIABLE_ID_PATTERN)
from ..exceptions import (
CrossComputeConfigurationError,
CrossComputeDataError)
from ..macros.disk import FileCache
from ..macros.package import import_attribute
from ..macros.web import get_html_from_markdown
from .interface import Batch)
and context including class names, function names, or small code snippets from other files:
# Path: crosscompute/constants.py
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
#
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
#
# Path: crosscompute/exceptions.py
# class CrossComputeConfigurationError(CrossComputeError):
# pass
#
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/macros/disk.py
# class FileCache(LRUDict):
#
# def __init__(self, *args, load_file_data, maximum_length: int, **kwargs):
# super().__init__(*args, maximum_length=maximum_length, **kwargs)
# self._load_file_data = load_file_data
#
# def __getitem__(self, path):
# if path in self:
# file_time, file_data = super().__getitem__(path)
# if getmtime(path) == file_time:
# return file_data
# file_data = self._load_file_data(path)
# self.__setitem__(path, file_data)
# return file_data
#
# def __setitem__(self, path, data):
# value = (getmtime(path), data)
# super().__setitem__(path, value)
#
# Path: crosscompute/macros/package.py
# def import_attribute(attribute_string):
# module_string, attribute_name = attribute_string.rsplit('.', maxsplit=1)
# return getattr(import_module(module_string), attribute_name)
#
# Path: crosscompute/macros/web.py
# def get_html_from_markdown(text):
# html = markdown(text)
# if '</p>\n<p>' not in html:
# html = html.removeprefix('<p>')
# html = html.removesuffix('</p>')
# return html
#
# Path: crosscompute/routines/interface.py
# class Batch(ABC):
#
# def get_data(self, variable_definition):
# '''
# Get the data of the variable in one of the following formats:
# {}
# {'value': 1}
# {'path': '/a/b/c.png'}
# {'uri': 'upload:xyz'}
# {'error': 'message'}
# '''
# return {}
#
# def get_data_uri(self, variable_definition):
# 'Get the resolved variable data uri'
# return ''
#
# def get_data_configuration(self, variable_definition):
# 'Get the resolved variable configuration'
# return {}
. Output only the next line. | def render(self, b: Batch, x: Element): |
Predict the next line after this snippet: <|code_start|>
def test_update_variable_data(tmp_path):
target_path = tmp_path / 'variables.dictionary'
update_variable_data(target_path, {'a': 1})
with target_path.open('r') as f:
d = json.load(f)
assert d['a'] == 1
update_variable_data(target_path, {'b': 2})
with target_path.open('r') as f:
d = json.load(f)
assert d['a'] == 1
assert d['b'] == 2
with target_path.open('w') as f:
f.write('')
<|code_end|>
using the current file's imports:
import json
from crosscompute.exceptions import CrossComputeDataError
from crosscompute.routines.variable import (
update_variable_data)
from pytest import raises
and any relevant context from other files:
# Path: crosscompute/exceptions.py
# class CrossComputeDataError(CrossComputeError):
# pass
#
# Path: crosscompute/routines/variable.py
# def update_variable_data(target_path, data_by_id):
# try:
# if exists(target_path):
# with open(target_path, 'r+t') as f:
# d = json.load(f)
# d.update(data_by_id)
# f.seek(0)
# f.truncate()
# json.dump(d, f)
# else:
# with open(target_path, 'wt') as f:
# d = data_by_id
# json.dump(d, f)
# except (json.JSONDecodeError, OSError) as e:
# raise CrossComputeDataError(e)
. Output only the next line. | with raises(CrossComputeDataError): |
Predict the next line for this snippet: <|code_start|># TODO: Define /mutations/{path}
# TODO: Trigger reload intelligently only if relevant
class MutationRoutes():
def __init__(self, server_timestamp_object):
self._server_timestamp_object = server_timestamp_object
def includeme(self, config):
<|code_end|>
with the help of current file imports:
from ..constants import (
MUTATIONS_ROUTE)
and context from other files:
# Path: crosscompute/constants.py
# MUTATIONS_ROUTE = '/mutations'
, which may contain function names, class names, or code. Output only the next line. | config.add_route('mutations', MUTATIONS_ROUTE) |
Given the code snippet: <|code_start|>
class FetchResourceRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/a.json':
self.send_response(500)
elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self.send_response(400)
else:
self.send_response(200)
self.end_headers()
try:
length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
<|code_end|>
, generate the next line using the imports in this file:
from crosscompute.constants import CLIENT_URL, SERVER_URL
from crosscompute.exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError)
from crosscompute.routines import (
fetch_resource,
get_bash_configuration_text,
get_echoes_client,
get_resource_url)
from http.server import BaseHTTPRequestHandler
from os import environ
from pytest import raises
from conftest import start_server
and context (functions, classes, or occasionally code) from other files:
# Path: crosscompute/constants.py
# class Error(IntEnum):
# CONFIGURATION_NOT_FOUND = -100
# COMMAND_NOT_FOUND = -10
# PACKAGE_FOLDER = Path(__file__).parent
# TEMPLATES_FOLDER = PACKAGE_FOLDER / 'templates'
# ID_LENGTH = 16
# AUTOMATION_NAME = 'Automation X'
# AUTOMATION_VERSION = '0.0.0'
# AUTOMATION_PATH = Path('automate.yml')
# HOST = '127.0.0.1'
# PORT = 7000
# DISK_POLL_IN_MILLISECONDS = 1000
# DISK_DEBOUNCE_IN_MILLISECONDS = 1000
# AUTOMATION_ROUTE = '/a/{automation_slug}'
# BATCH_ROUTE = '/b/{batch_slug}'
# VARIABLE_ROUTE = '/{variable_id}'
# MODE_ROUTE = '/{mode_code}'
# RUN_ROUTE = '/r/{run_slug}'
# STYLE_ROUTE = '/s/{style_name}.css'
# MUTATIONS_ROUTE = '/mutations'
# MODE_NAMES = 'input', 'output', 'log', 'debug'
# MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
# MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
# PING_INTERVAL_IN_SECONDS = 1
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
. Output only the next line. | environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL |
Next line prediction: <|code_start|>
class FetchResourceRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/a.json':
self.send_response(500)
elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self.send_response(400)
else:
self.send_response(200)
self.end_headers()
try:
length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL
<|code_end|>
. Use current file imports:
(from crosscompute.constants import CLIENT_URL, SERVER_URL
from crosscompute.exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError)
from crosscompute.routines import (
fetch_resource,
get_bash_configuration_text,
get_echoes_client,
get_resource_url)
from http.server import BaseHTTPRequestHandler
from os import environ
from pytest import raises
from conftest import start_server)
and context including class names, function names, or small code snippets from other files:
# Path: crosscompute/constants.py
# class Error(IntEnum):
# CONFIGURATION_NOT_FOUND = -100
# COMMAND_NOT_FOUND = -10
# PACKAGE_FOLDER = Path(__file__).parent
# TEMPLATES_FOLDER = PACKAGE_FOLDER / 'templates'
# ID_LENGTH = 16
# AUTOMATION_NAME = 'Automation X'
# AUTOMATION_VERSION = '0.0.0'
# AUTOMATION_PATH = Path('automate.yml')
# HOST = '127.0.0.1'
# PORT = 7000
# DISK_POLL_IN_MILLISECONDS = 1000
# DISK_DEBOUNCE_IN_MILLISECONDS = 1000
# AUTOMATION_ROUTE = '/a/{automation_slug}'
# BATCH_ROUTE = '/b/{batch_slug}'
# VARIABLE_ROUTE = '/{variable_id}'
# MODE_ROUTE = '/{mode_code}'
# RUN_ROUTE = '/r/{run_slug}'
# STYLE_ROUTE = '/s/{style_name}.css'
# MUTATIONS_ROUTE = '/mutations'
# MODE_NAMES = 'input', 'output', 'log', 'debug'
# MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
# MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
# PING_INTERVAL_IN_SECONDS = 1
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
. Output only the next line. | environ['CROSSCOMPUTE_SERVER'] = SERVER_URL |
Given the following code snippet before the placeholder: <|code_start|> elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self.send_response(400)
else:
self.send_response(200)
self.end_headers()
try:
length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL
environ['CROSSCOMPUTE_SERVER'] = SERVER_URL
try:
del environ['CROSSCOMPUTE_TOKEN']
except KeyError:
pass
bash_configuration_text = get_bash_configuration_text()
assert CLIENT_URL in bash_configuration_text
assert SERVER_URL in bash_configuration_text
assert 'YOUR-TOKEN' in bash_configuration_text
def test_fetch_resource():
server_url = 'http://localhost:9999'
<|code_end|>
, predict the next line using imports from the current file:
from crosscompute.constants import CLIENT_URL, SERVER_URL
from crosscompute.exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError)
from crosscompute.routines import (
fetch_resource,
get_bash_configuration_text,
get_echoes_client,
get_resource_url)
from http.server import BaseHTTPRequestHandler
from os import environ
from pytest import raises
from conftest import start_server
and context including class names, function names, and sometimes code from other files:
# Path: crosscompute/constants.py
# class Error(IntEnum):
# CONFIGURATION_NOT_FOUND = -100
# COMMAND_NOT_FOUND = -10
# PACKAGE_FOLDER = Path(__file__).parent
# TEMPLATES_FOLDER = PACKAGE_FOLDER / 'templates'
# ID_LENGTH = 16
# AUTOMATION_NAME = 'Automation X'
# AUTOMATION_VERSION = '0.0.0'
# AUTOMATION_PATH = Path('automate.yml')
# HOST = '127.0.0.1'
# PORT = 7000
# DISK_POLL_IN_MILLISECONDS = 1000
# DISK_DEBOUNCE_IN_MILLISECONDS = 1000
# AUTOMATION_ROUTE = '/a/{automation_slug}'
# BATCH_ROUTE = '/b/{batch_slug}'
# VARIABLE_ROUTE = '/{variable_id}'
# MODE_ROUTE = '/{mode_code}'
# RUN_ROUTE = '/r/{run_slug}'
# STYLE_ROUTE = '/s/{style_name}.css'
# MUTATIONS_ROUTE = '/mutations'
# MODE_NAMES = 'input', 'output', 'log', 'debug'
# MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
# MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
# PING_INTERVAL_IN_SECONDS = 1
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
. Output only the next line. | with raises(CrossComputeConnectionError): |
Given snippet: <|code_start|> length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL
environ['CROSSCOMPUTE_SERVER'] = SERVER_URL
try:
del environ['CROSSCOMPUTE_TOKEN']
except KeyError:
pass
bash_configuration_text = get_bash_configuration_text()
assert CLIENT_URL in bash_configuration_text
assert SERVER_URL in bash_configuration_text
assert 'YOUR-TOKEN' in bash_configuration_text
def test_fetch_resource():
server_url = 'http://localhost:9999'
with raises(CrossComputeConnectionError):
fetch_resource('tools', server_url=server_url, token='a')
server_url = start_server(FetchResourceRequestHandler)
with raises(CrossComputeImplementationError):
fetch_resource('a', data={}, server_url=server_url, token='a')
with raises(CrossComputeConnectionError):
fetch_resource('b', server_url=server_url, token='a')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from crosscompute.constants import CLIENT_URL, SERVER_URL
from crosscompute.exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError)
from crosscompute.routines import (
fetch_resource,
get_bash_configuration_text,
get_echoes_client,
get_resource_url)
from http.server import BaseHTTPRequestHandler
from os import environ
from pytest import raises
from conftest import start_server
and context:
# Path: crosscompute/constants.py
# class Error(IntEnum):
# CONFIGURATION_NOT_FOUND = -100
# COMMAND_NOT_FOUND = -10
# PACKAGE_FOLDER = Path(__file__).parent
# TEMPLATES_FOLDER = PACKAGE_FOLDER / 'templates'
# ID_LENGTH = 16
# AUTOMATION_NAME = 'Automation X'
# AUTOMATION_VERSION = '0.0.0'
# AUTOMATION_PATH = Path('automate.yml')
# HOST = '127.0.0.1'
# PORT = 7000
# DISK_POLL_IN_MILLISECONDS = 1000
# DISK_DEBOUNCE_IN_MILLISECONDS = 1000
# AUTOMATION_ROUTE = '/a/{automation_slug}'
# BATCH_ROUTE = '/b/{batch_slug}'
# VARIABLE_ROUTE = '/{variable_id}'
# MODE_ROUTE = '/{mode_code}'
# RUN_ROUTE = '/r/{run_slug}'
# STYLE_ROUTE = '/s/{style_name}.css'
# MUTATIONS_ROUTE = '/mutations'
# MODE_NAMES = 'input', 'output', 'log', 'debug'
# MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
# MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
# PING_INTERVAL_IN_SECONDS = 1
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
which might include code, classes, or functions. Output only the next line. | with raises(CrossComputeExecutionError): |
Given the code snippet: <|code_start|> else:
self.send_response(200)
self.end_headers()
try:
length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL
environ['CROSSCOMPUTE_SERVER'] = SERVER_URL
try:
del environ['CROSSCOMPUTE_TOKEN']
except KeyError:
pass
bash_configuration_text = get_bash_configuration_text()
assert CLIENT_URL in bash_configuration_text
assert SERVER_URL in bash_configuration_text
assert 'YOUR-TOKEN' in bash_configuration_text
def test_fetch_resource():
server_url = 'http://localhost:9999'
with raises(CrossComputeConnectionError):
fetch_resource('tools', server_url=server_url, token='a')
server_url = start_server(FetchResourceRequestHandler)
<|code_end|>
, generate the next line using the imports in this file:
from crosscompute.constants import CLIENT_URL, SERVER_URL
from crosscompute.exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError)
from crosscompute.routines import (
fetch_resource,
get_bash_configuration_text,
get_echoes_client,
get_resource_url)
from http.server import BaseHTTPRequestHandler
from os import environ
from pytest import raises
from conftest import start_server
and context (functions, classes, or occasionally code) from other files:
# Path: crosscompute/constants.py
# class Error(IntEnum):
# CONFIGURATION_NOT_FOUND = -100
# COMMAND_NOT_FOUND = -10
# PACKAGE_FOLDER = Path(__file__).parent
# TEMPLATES_FOLDER = PACKAGE_FOLDER / 'templates'
# ID_LENGTH = 16
# AUTOMATION_NAME = 'Automation X'
# AUTOMATION_VERSION = '0.0.0'
# AUTOMATION_PATH = Path('automate.yml')
# HOST = '127.0.0.1'
# PORT = 7000
# DISK_POLL_IN_MILLISECONDS = 1000
# DISK_DEBOUNCE_IN_MILLISECONDS = 1000
# AUTOMATION_ROUTE = '/a/{automation_slug}'
# BATCH_ROUTE = '/b/{batch_slug}'
# VARIABLE_ROUTE = '/{variable_id}'
# MODE_ROUTE = '/{mode_code}'
# RUN_ROUTE = '/r/{run_slug}'
# STYLE_ROUTE = '/s/{style_name}.css'
# MUTATIONS_ROUTE = '/mutations'
# MODE_NAMES = 'input', 'output', 'log', 'debug'
# MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
# MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
# PING_INTERVAL_IN_SECONDS = 1
# FUNCTION_BY_NAME = {
# 'slug': format_slug,
# 'title': str.title,
# }
# VARIABLE_ID_PATTERN = re.compile(r'{\s*([^}]+?)\s*}')
# MAXIMUM_FILE_CACHE_LENGTH = 256
#
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
. Output only the next line. | with raises(CrossComputeImplementationError): |
Given the following code snippet before the placeholder: <|code_start|> server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = response.status_code
d = {'url': url, 'token': token, 'statusCode': status_code}
if status_code in [401, 403]:
d['statusHelp'] = 'please check your server url and token'
raise CrossComputeConnectionError(d)
try:
response_json = response.json()
except ValueError:
d['statusHelp'] = 'could not parse response as json'
d['responseContent'] = response.content.decode('utf-8')
raise CrossComputeConnectionError(d)
if status_code != 200:
if response_json:
d.update(response_json)
raise (
CrossComputeExecutionError if status_code == 400 else
CrossComputeImplementationError)(d)
return response_json
def get_client_url():
<|code_end|>
, predict the next line using imports from the current file:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context including class names, function names, and sometimes code from other files:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
. Output only the next line. | return get_environment_value('CROSSCOMPUTE_CLIENT', CLIENT_URL) |
Given the following code snippet before the placeholder: <|code_start|> try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = response.status_code
d = {'url': url, 'token': token, 'statusCode': status_code}
if status_code in [401, 403]:
d['statusHelp'] = 'please check your server url and token'
raise CrossComputeConnectionError(d)
try:
response_json = response.json()
except ValueError:
d['statusHelp'] = 'could not parse response as json'
d['responseContent'] = response.content.decode('utf-8')
raise CrossComputeConnectionError(d)
if status_code != 200:
if response_json:
d.update(response_json)
raise (
CrossComputeExecutionError if status_code == 400 else
CrossComputeImplementationError)(d)
return response_json
def get_client_url():
return get_environment_value('CROSSCOMPUTE_CLIENT', CLIENT_URL)
def get_server_url():
<|code_end|>
, predict the next line using imports from the current file:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context including class names, function names, and sometimes code from other files:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
. Output only the next line. | return get_environment_value('CROSSCOMPUTE_SERVER', SERVER_URL) |
Given snippet: <|code_start|>
def get_bash_configuration_text():
return BASH_CONFIGURATION_TEXT.format(
client_url=get_client_url(),
server_url=get_server_url(),
token=get_token('YOUR-TOKEN'))
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
server_url=None, token=None):
f = getattr(requests, method.lower())
server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
which might include code, classes, or functions. Output only the next line. | raise CrossComputeConnectionError({ |
Given the following code snippet before the placeholder: <|code_start|>
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
server_url=None, token=None):
f = getattr(requests, method.lower())
server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = response.status_code
d = {'url': url, 'token': token, 'statusCode': status_code}
if status_code in [401, 403]:
d['statusHelp'] = 'please check your server url and token'
raise CrossComputeConnectionError(d)
try:
response_json = response.json()
except ValueError:
d['statusHelp'] = 'could not parse response as json'
d['responseContent'] = response.content.decode('utf-8')
raise CrossComputeConnectionError(d)
if status_code != 200:
if response_json:
d.update(response_json)
raise (
<|code_end|>
, predict the next line using imports from the current file:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context including class names, function names, and sometimes code from other files:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
. Output only the next line. | CrossComputeExecutionError if status_code == 400 else |
Using the snippet: <|code_start|>
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
server_url=None, token=None):
f = getattr(requests, method.lower())
server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = response.status_code
d = {'url': url, 'token': token, 'statusCode': status_code}
if status_code in [401, 403]:
d['statusHelp'] = 'please check your server url and token'
raise CrossComputeConnectionError(d)
try:
response_json = response.json()
except ValueError:
d['statusHelp'] = 'could not parse response as json'
d['responseContent'] = response.content.decode('utf-8')
raise CrossComputeConnectionError(d)
if status_code != 200:
if response_json:
d.update(response_json)
raise (
CrossComputeExecutionError if status_code == 400 else
<|code_end|>
, determine the next line of code. You have imports:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context (class names, function names, or code) available:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
. Output only the next line. | CrossComputeImplementationError)(d) |
Given snippet: <|code_start|> if resource_id:
url += '/' + resource_id
return url + '.json'
def get_echoes_client():
echoes_url = get_echoes_url()
try:
client = SSEClient(echoes_url)
except Exception:
raise CrossComputeConnectionError({
'url': 'could not connect to echoes ' + echoes_url})
return client
def yield_echo(statistics_dictionary, is_quiet=False, as_json=False):
statistics_dictionary['ping count'] = 0
try:
for echo_message in get_echoes_client():
event_name = echo_message.event
if event_name == 'message':
if not is_quiet and not as_json:
print('.', end='', flush=True)
statistics_dictionary['ping count'] += 1
continue
elif not is_quiet:
print('$', end='', flush=True)
event_dictionary = json.loads(echo_message.data)
yield event_name, event_dictionary
except KeyboardInterrupt:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
which might include code, classes, or functions. Output only the next line. | raise CrossComputeKeyboardInterrupt |
Given snippet: <|code_start|> server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = response.status_code
d = {'url': url, 'token': token, 'statusCode': status_code}
if status_code in [401, 403]:
d['statusHelp'] = 'please check your server url and token'
raise CrossComputeConnectionError(d)
try:
response_json = response.json()
except ValueError:
d['statusHelp'] = 'could not parse response as json'
d['responseContent'] = response.content.decode('utf-8')
raise CrossComputeConnectionError(d)
if status_code != 200:
if response_json:
d.update(response_json)
raise (
CrossComputeExecutionError if status_code == 400 else
CrossComputeImplementationError)(d)
return response_json
def get_client_url():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import requests
from sseclient import SSEClient
from ..constants import (
BASH_CONFIGURATION_TEXT,
CLIENT_URL,
SERVER_URL)
from ..exceptions import (
CrossComputeConnectionError,
CrossComputeExecutionError,
CrossComputeImplementationError,
CrossComputeKeyboardInterrupt)
from ..macros import (
get_environment_value)
and context:
# Path: experiments/0.8/crosscompute/constants.py
# VIEW_NAMES = [
# 'text',
# 'number',
# 'markdown',
# 'table',
# 'image',
# 'map',
# 'electricity-network',
# 'file',
# ]
# DEFAULT_VIEW_NAME = 'text'
# PRINT_FORMAT_NAMES = [
# 'pdf'
# ]
# DEBUG_VARIABLE_DEFINITIONS = [{
# 'id': 'stdout',
# 'name': 'Standard Output',
# 'view': 'text',
# 'path': 'stdout.txt',
# }, {
# 'id': 'stderr',
# 'name': 'Standard Error',
# 'view': 'text',
# 'path': 'stderr.txt',
# }]
#
# Path: experiments/0.8/crosscompute/exceptions.py
# class CrossComputeConnectionError(HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeExecutionError(HTTPBadRequest, CrossComputeError):
# pass
#
# class CrossComputeImplementationError(
# HTTPInternalServerError, CrossComputeError):
# pass
#
# class CrossComputeKeyboardInterrupt(KeyboardInterrupt, CrossComputeError):
# pass
#
# Path: experiments/0.8/crosscompute/macros.py
# def sanitize_name(name):
# def is_valid_name_character(x):
# def sanitize_json_value(value):
# def parse_number_safely(raw_value):
# def parse_number(raw_value):
# def split_path(path):
# def is_compatible_version(target_version_name, source_version_name):
# def get_plain_value(x):
which might include code, classes, or functions. Output only the next line. | return get_environment_value('CROSSCOMPUTE_CLIENT', CLIENT_URL) |
Next line prediction: <|code_start|>
class WheeType(StringType):
@classmethod
def parse(Class, x, default_value=None):
if x != 'whee':
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from invisibleroads_macros.disk import copy_folder
from os.path import dirname, join
from pytest import fixture
from crosscompute.exceptions import DataTypeError
from crosscompute.models import Result
from crosscompute.scripts.serve import ResultRequest
from crosscompute.types import StringType, DATA_TYPE_BY_SUFFIX)
and context including class names, function names, or small code snippets from other files:
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
#
# Path: crosscompute/scripts/serve.py
# def do(arguments=None):
# def configure_argument_parser_for_serving(a):
# def serve_with(automation, args):
# def serve(
# automation, host=HOST, port=PORT, with_browser=True,
# is_static=False, is_production=False,
# base_uri='', allowed_origins=None,
# disk_poll_in_milliseconds=DISK_POLL_IN_MILLISECONDS,
# disk_debounce_in_milliseconds=DISK_DEBOUNCE_IN_MILLISECONDS):
# L = getLogger(__name__)
. Output only the next line. | raise DataTypeError('whee expected') |
Given the following code snippet before the placeholder: <|code_start|>
@classmethod
def parse(Class, x, default_value=None):
if x != 'whee':
raise DataTypeError('whee expected')
return x
@fixture
def tool_definition():
return OrderedDict([
('argument_names', ()),
('configuration_folder', TOOL_FOLDER),
('a_path', 1),
('a', 2),
('x.a_path', 3),
('x.a', 4)
])
@fixture
def result(data_folder):
result = Result(id=1)
result_folder = result.get_folder(data_folder)
copy_folder(result_folder, RESULT_FOLDER)
return result
@fixture
def result_request(posts_request):
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from invisibleroads_macros.disk import copy_folder
from os.path import dirname, join
from pytest import fixture
from crosscompute.exceptions import DataTypeError
from crosscompute.models import Result
from crosscompute.scripts.serve import ResultRequest
from crosscompute.types import StringType, DATA_TYPE_BY_SUFFIX
and context including class names, function names, and sometimes code from other files:
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
#
# Path: crosscompute/scripts/serve.py
# def do(arguments=None):
# def configure_argument_parser_for_serving(a):
# def serve_with(automation, args):
# def serve(
# automation, host=HOST, port=PORT, with_browser=True,
# is_static=False, is_production=False,
# base_uri='', allowed_origins=None,
# disk_poll_in_milliseconds=DISK_POLL_IN_MILLISECONDS,
# disk_debounce_in_milliseconds=DISK_DEBOUNCE_IN_MILLISECONDS):
# L = getLogger(__name__)
. Output only the next line. | return ResultRequest(posts_request) |
Using the snippet: <|code_start|>
class ADataType(DataType):
@classmethod
def load(Class, path):
if path == 'x':
raise Exception
instance = Class()
instance.path = path
return instance
@classmethod
def parse(Class, x, default_value=None):
if x == 'd':
<|code_end|>
, determine the next line of code. You have imports:
from crosscompute.exceptions import DataTypeError
from crosscompute.types import DataType
from pytest import raises
and context (class names, function names, or code) available:
# Path: crosscompute/exceptions.py
# class CrossComputeError(Exception):
# class CrossComputeConfigurationError(CrossComputeError):
# class CrossComputeConfigurationNotFoundError(CrossComputeConfigurationError):
# class CrossComputeConfigurationFormatError(CrossComputeError):
# class CrossComputeDataError(CrossComputeError):
# class CrossComputeExecutionError(CrossComputeError):
# def __str__(self):
. Output only the next line. | raise DataTypeError |
Predict the next line after this snippet: <|code_start|>ID_LENGTH = 16
AUTOMATION_NAME = 'Automation X'
AUTOMATION_VERSION = '0.0.0'
AUTOMATION_PATH = Path('automate.yml')
HOST = '127.0.0.1'
PORT = 7000
DISK_POLL_IN_MILLISECONDS = 1000
DISK_DEBOUNCE_IN_MILLISECONDS = 1000
AUTOMATION_ROUTE = '/a/{automation_slug}'
BATCH_ROUTE = '/b/{batch_slug}'
VARIABLE_ROUTE = '/{variable_id}'
MODE_ROUTE = '/{mode_code}'
RUN_ROUTE = '/r/{run_slug}'
STYLE_ROUTE = '/s/{style_name}.css'
MUTATIONS_ROUTE = '/mutations'
MODE_NAMES = 'input', 'output', 'log', 'debug'
MODE_NAME_BY_CODE = {_[0]: _ for _ in MODE_NAMES}
MODE_CODE_BY_NAME = {k: v for v, k in MODE_NAME_BY_CODE.items()}
PING_INTERVAL_IN_SECONDS = 1
FUNCTION_BY_NAME = {
<|code_end|>
using the current file's imports:
import re
from enum import IntEnum
from pathlib import Path
from .macros.web import format_slug
and any relevant context from other files:
# Path: crosscompute/macros/web.py
# def format_slug(text):
# return normalize_key(text, word_separator='-')
. Output only the next line. | 'slug': format_slug, |
Based on the snippet: <|code_start|> if self._has_duplicates(self.data):
raise ValueError("Time sequence has duplicate entries")
super(Time, self).__init__(*args, **kwargs)
@classmethod
def from_netCDF(cls,
filename=None,
dataset=None,
varname=None,
datavar=None,
tz_offset=None,
**kwargs):
"""
construct a Time object from a netcdf file
:param filename=None: name of netcddf file
:param dataset=None: netcdf dataset object (one or the other)
:param varname=None: name of the netcdf variable
:param datavar=None: Either the time variable name, or
A netcdf variable that needs a Time object.
It will try to find the time variable that
corresponds to the passed in variable.
:param tz_offset=None: offset to adjust for timezone, in hours.
"""
if dataset is None:
<|code_end|>
, predict the immediate next line with the help of imports:
from textwrap import dedent
from datetime import datetime, timedelta
from gridded.utilities import get_dataset
import netCDF4 as nc4
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: gridded/utilities.py
# def get_dataset(ncfile, dataset=None):
# """
# Utility to create a netCDF4 Dataset from a filename, list of filenames,
# or just pass it through if it's already a netCDF4.Dataset
#
# if dataset is not None, it should be a valid netCDF4 Dataset object,
# and it will simply be returned
# """
# if dataset is not None:
# return dataset
# if isinstance(ncfile, nc4.Dataset):
# return ncfile
# elif isinstance(ncfile, Iterable) and len(ncfile) == 1:
# return nc4.Dataset(ncfile[0])
# elif isstring(ncfile):
# return nc4.Dataset(ncfile)
# else:
# return nc4.MFDataset(ncfile)
. Output only the next line. | dataset = get_dataset(filename) |
Predict the next line for this snippet: <|code_start|>
# used to parametrize tests for both methods
try:
methods = ['simple', 'celltree']
except ImportError:
# no cell tree -- only test simple
methods = ['simple']
@pytest.mark.parametrize("method", methods)
<|code_end|>
with the help of current file imports:
import numpy as np
import pytest
import cell_tree2d # noqa: ignore=F401
from .utilities import twenty_one_triangles
and context from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @pytest.fixture
# def twenty_one_triangles():
# """
# Returns a basic triangular grid: 21 triangles, a hole, and a tail.
#
# """
# nodes = [(5, 1),
# (10, 1),
# (3, 3),
# (7, 3),
# (9, 4),
# (12, 4),
# (5, 5),
# (3, 7),
# (5, 7),
# (7, 7),
# (9, 7),
# (11, 7),
# (5, 9),
# (8, 9),
# (11, 9),
# (9, 11),
# (11, 11),
# (7, 13),
# (9, 13),
# (7, 15), ]
#
# faces = [(0, 1, 3),
# (0, 6, 2),
# (0, 3, 6),
# (1, 4, 3),
# (1, 5, 4),
# (2, 6, 7),
# (6, 8, 7),
# (7, 8, 12),
# (6, 9, 8),
# (8, 9, 12),
# (9, 13, 12),
# (4, 5, 11),
# (4, 11, 10),
# (9, 10, 13),
# (10, 11, 14),
# (10, 14, 13),
# (13, 14, 15),
# (14, 16, 15),
# (15, 16, 18),
# (15, 18, 17),
# (17, 18, 19), ]
#
# # We may want to use this later to define just the outer boundary.
# boundaries = [(0, 1),
# (1, 5),
# (5, 11),
# (11, 14),
# (14, 16),
# (16, 18),
# (18, 19),
# (19, 17),
# (17, 15),
# (15, 13),
# (13, 12),
# (12, 7),
# (7, 2),
# (2, 0),
# (3, 4),
# (4, 10),
# (10, 9),
# (9, 6),
# (6, 3), ]
#
# grid = ugrid.UGrid(nodes=nodes, faces=faces, boundaries=boundaries)
# grid.build_edges()
# return grid
, which may contain function names, class names, or code. Output only the next line. | def test_single(method, twenty_one_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# py2/3 compatibility
from __future__ import absolute_import, division, print_function, unicode_literals
data_dir = os.path.join(os.path.split(__file__)[0], 'test_data')
def test_gen_celltree_mask_from_center_mask():
center_mask = np.array(([True, True, True, True, True],
[True, False, True, True, True],
[True, False, False, False, True],
[True, True, True, True, True]))
center_sl = np.s_[1:-1,1:-1] #'both' padding
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import netCDF4 as nc
from gridded import utilities
from gridded.tests.test_depth import get_s_depth
from gridded.variable import Variable
from gridded.time import Time
from gridded.grids import Grid_S
from gridded.variable import Variable
from gridded.time import Time
from gridded.grids import Grid_S
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/utilities.py
# def gen_celltree_mask_from_center_mask(center_mask, sl):
# def regrid_variable(grid, o_var, location='node'):
# def _regrid_s_depth(grid, o_depth):
# def _reorganize_spatial_data(points):
# def _align_results_to_spatial_data(result, points):
# def isarraylike(obj):
# def asarraylike(obj):
# def isstring(obj):
# def get_dataset(ncfile, dataset=None):
# def get_writable_dataset(ncfile, format="netcdf4"):
# def get_dataset_attrs(ds):
#
# Path: gridded/tests/test_depth.py
# @pytest.fixture(scope="module")
# def get_s_depth():
# """
# This is setup for a ROMS S-level Depth that is on a square grid with a center
# mound. Control vars: sz=xy size, center_el=height of the mound in meters,
# d0=general depth in meters, sig=steepness of mound, nz=number of z levels.
# """
# sz = 40
# center_el = 10
# d0 = 20
# sig = 0.75
# nz = 11
# node_lat, node_lon = np.mgrid[0:sz, 0:sz]
# b_data = np.empty((sz, sz))
# for x in range(0, sz):
# for y in range(0, sz):
# b_data[x, y] = d0 - center_el * np.exp(
# -0.1
# * (
# (x - (sz / 2)) ** 2 / 2.0 * ((sig) ** 2)
# + (y - (sz / 2)) ** 2
# / 2.0
# * ((sig) ** 2)
# )
# )
# z_data = np.empty((3, sz, sz))
# for t in range(0, 3):
# for x in range(0, sz):
# for y in range(0, sz):
# z_data[t, x, y] = (t - 1.0) / 2.0
# g = Grid_S(node_lon=node_lon, node_lat=node_lat)
# bathy = Variable(name="bathy", grid=g, data=b_data)
# t_data = np.array(
# [
# Time.constant_time().data[0]
# + datetime.timedelta(minutes=10 * d)
# for d in range(0, 3)
# ]
# )
# zeta = Variable(
# name="zeta",
# time=Time(data=t_data),
# grid=g,
# data=z_data,
# )
#
# s_w = np.linspace(-1, 0, nz)
# s_rho = (s_w[0:-1] + s_w[1:]) / 2
# # equidistant layers, no stretching
# Cs_w = np.linspace(-1, 0, nz)
# Cs_w = 1 - 1 / np.exp(2 * Cs_w)
# Cs_w /= -Cs_w[0]
# Cs_r = (Cs_w[0:-1] + Cs_w[1:]) / 2
# hc = np.array([0])
#
# sd = S_Depth(
# time=zeta.time,
# grid=zeta.grid,
# bathymetry=bathy,
# zeta=zeta,
# terms={
# "s_w": s_w,
# "s_rho": s_rho,
# "Cs_w": Cs_w,
# "Cs_r": Cs_r,
# "hc": hc,
# },
# )
# return sd
. Output only the next line. | m = utilities.gen_celltree_mask_from_center_mask(center_mask, center_sl) |
Continue the code snippet: <|code_start|> pts_2 = [(1,), (2,), (3,)]
pts_3 = np.array([[1, 2, 3], [4, 5, 6]])
pts_4 = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
res_1 = np.array([[1, ], ])
res_2 = np.array([[1, 2, 3, 4, 5, 6], ])
res_3 = np.array([[1, 2, 3, 4, 5, 6],
[2, 3, 4, 5, 6, 7]])
res_4 = np.array([[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24]])
res_5 = np.array([[1, ],
[2, ],
[3, ],
[4, ]])
a1 = utilities._align_results_to_spatial_data(res_1, pts_1)
assert np.all(a1 == res_1)
a2 = utilities._align_results_to_spatial_data(res_2, pts_2)
assert np.all(a2 == res_2)
a3 = utilities._align_results_to_spatial_data(res_3, pts_3)
assert np.all(a3 == res_3)
a4 = utilities._align_results_to_spatial_data(res_4, pts_4)
a5 = utilities._align_results_to_spatial_data(res_5, pts_4)
assert np.all(a4.T == res_4)
assert np.all(a5.T == res_5)
<|code_end|>
. Use current file imports:
import os
import numpy as np
import netCDF4 as nc
from gridded import utilities
from gridded.tests.test_depth import get_s_depth
from gridded.variable import Variable
from gridded.time import Time
from gridded.grids import Grid_S
from gridded.variable import Variable
from gridded.time import Time
from gridded.grids import Grid_S
and context (classes, functions, or code) from other files:
# Path: gridded/utilities.py
# def gen_celltree_mask_from_center_mask(center_mask, sl):
# def regrid_variable(grid, o_var, location='node'):
# def _regrid_s_depth(grid, o_depth):
# def _reorganize_spatial_data(points):
# def _align_results_to_spatial_data(result, points):
# def isarraylike(obj):
# def asarraylike(obj):
# def isstring(obj):
# def get_dataset(ncfile, dataset=None):
# def get_writable_dataset(ncfile, format="netcdf4"):
# def get_dataset_attrs(ds):
#
# Path: gridded/tests/test_depth.py
# @pytest.fixture(scope="module")
# def get_s_depth():
# """
# This is setup for a ROMS S-level Depth that is on a square grid with a center
# mound. Control vars: sz=xy size, center_el=height of the mound in meters,
# d0=general depth in meters, sig=steepness of mound, nz=number of z levels.
# """
# sz = 40
# center_el = 10
# d0 = 20
# sig = 0.75
# nz = 11
# node_lat, node_lon = np.mgrid[0:sz, 0:sz]
# b_data = np.empty((sz, sz))
# for x in range(0, sz):
# for y in range(0, sz):
# b_data[x, y] = d0 - center_el * np.exp(
# -0.1
# * (
# (x - (sz / 2)) ** 2 / 2.0 * ((sig) ** 2)
# + (y - (sz / 2)) ** 2
# / 2.0
# * ((sig) ** 2)
# )
# )
# z_data = np.empty((3, sz, sz))
# for t in range(0, 3):
# for x in range(0, sz):
# for y in range(0, sz):
# z_data[t, x, y] = (t - 1.0) / 2.0
# g = Grid_S(node_lon=node_lon, node_lat=node_lat)
# bathy = Variable(name="bathy", grid=g, data=b_data)
# t_data = np.array(
# [
# Time.constant_time().data[0]
# + datetime.timedelta(minutes=10 * d)
# for d in range(0, 3)
# ]
# )
# zeta = Variable(
# name="zeta",
# time=Time(data=t_data),
# grid=g,
# data=z_data,
# )
#
# s_w = np.linspace(-1, 0, nz)
# s_rho = (s_w[0:-1] + s_w[1:]) / 2
# # equidistant layers, no stretching
# Cs_w = np.linspace(-1, 0, nz)
# Cs_w = 1 - 1 / np.exp(2 * Cs_w)
# Cs_w /= -Cs_w[0]
# Cs_r = (Cs_w[0:-1] + Cs_w[1:]) / 2
# hc = np.array([0])
#
# sd = S_Depth(
# time=zeta.time,
# grid=zeta.grid,
# bathymetry=bathy,
# zeta=zeta,
# terms={
# "s_w": s_w,
# "s_rho": s_rho,
# "Cs_w": Cs_w,
# "Cs_r": Cs_r,
# "hc": hc,
# },
# )
# return sd
. Output only the next line. | def test_regrid_variable_TDStoS(get_s_depth): |
Next line prediction: <|code_start|>
Just for tests. All it does is add a few expected attributes
This will need to be updated when the function is changed.
"""
must_have = ['dtype', 'shape', 'ndim', '__len__', '__getitem__', '__getattribute__']
# pretty kludgy way to do this..
def __new__(cls):
obj = object.__new__(cls)
for attr in cls.must_have:
setattr(obj, attr, None)
return obj
def test_dummy_array_like():
dum = DummyArrayLike()
print(dum)
print(dum.dtype)
for attr in DummyArrayLike.must_have:
assert hasattr(dum, attr)
def test_asarraylike_list():
"""
Passing in a list should return a np.ndarray.
"""
lst = [1, 2, 3, 4]
<|code_end|>
. Use current file imports:
(import numpy as np
from gridded.pyugrid import util)
and context including class names, function names, or small code snippets from other files:
# Path: gridded/pyugrid/util.py
# def point_in_tri(face_points, point, return_weights=False):
# def _signed_area_tri(points):
# def isarraylike(obj):
# def asarraylike(obj):
. Output only the next line. | result = util.asarraylike(lst) |
Predict the next line after this snippet: <|code_start|> 'simple' is very, very slow for large grids.
:type simple: str
This version utilizes the CellTree data structure.
"""
points = np.asarray(points, dtype=np.float64)
just_one = (points.ndim == 1)
points.shape = (-1, 2)
if _memo:
if _hash is None:
_hash = self._hash_of_pts(points)
result = self._get_memoed(points, self._ind_memo_dict, _copy, _hash)
if result is not None:
return result
if method == 'celltree':
try:
except ImportError:
raise ImportError("the cell_tree2d package must be installed to use the celltree search:\n"
"https://github.com/NOAA-ORR-ERD/cell_tree2d/")
if self._cell_tree is None:
self.build_celltree()
indices = self._cell_tree.locate(points)
elif method == 'simple':
indices = np.zeros((points.shape[0]), dtype=IND_DT)
for n, point in enumerate(points):
for i, face in enumerate(self._faces):
f = self._nodes[face]
<|code_end|>
using the current file's imports:
import hashlib
import numpy as np
import gridded.pyugrid.read_netcdf as read_netcdf
import cell_tree2d
from collections import OrderedDict
from gridded.pyugrid.util import point_in_tri
from gridded.utilities import get_writable_dataset
from scipy.spatial import cKDTree
from cell_tree2d import CellTree
from scipy.spatial import cKDTree
and any relevant context from other files:
# Path: gridded/pyugrid/util.py
# def point_in_tri(face_points, point, return_weights=False):
# """
# Calculates whether point is internal/external
# to element by comparing summed area of sub triangles with area of triangle
# element.
#
# NOTE: this seems like a pretty expensive way to do it
# -- compared to three side of line tests..
# """
# sub_tri_areas = np.zeros(3)
# sub_tri_areas[0] = _signed_area_tri(np.vstack((face_points[(0, 1), :],
# point)))
# sub_tri_areas[1] = _signed_area_tri(np.vstack((face_points[(1, 2), :],
# point)))
# sub_tri_areas[2] = _signed_area_tri(np.vstack((face_points[(0, 2), :],
# point)))
# tri_area = _signed_area_tri(face_points)
#
# if abs(np.abs(sub_tri_areas).sum() - tri_area) / tri_area <= epsilon:
# if return_weights:
# raise NotImplementedError
# # weights = sub_tri_areas/tri_area
# # weights[1] = max(0., min(1., weights[1]))
# # weights[2] = max(0., min(1., weights[2]))
# # if (weights[0]+weights[1]>1):
# # weights[2] = 0
# # weights[1] = 1-weights[0]
# # else:
# # weights[2] = 1-weights[0]-weights[1]
# #
# # return weights
# else:
# return True
# return False
#
# Path: gridded/utilities.py
# def get_writable_dataset(ncfile, format="netcdf4"):
# """
# Utility to create a writable netCDF4 Dataset from a filename, list of filenames,
# or just pass it through if it's already a netCDF4.Dataset
#
# if dataset is not None, it should be a valid netCDF4 Dataset object,
# and it will simply be returned
# """
# if isinstance(ncfile, nc4.Dataset):
# # fixme: check for writable
# return ncfile
# elif isstring(ncfile): # Fixme: should be pathlike...
# print("filename is:", ncfile)
# return nc4.Dataset(ncfile,
# mode="w",
# clobber=True,
# format="NETCDF4")
# else:
# raise ValueError("Must be a string path or a netcdf4 Dataset")
. Output only the next line. | if point_in_tri(f, point): |
Next line prediction: <|code_start|> :param filename: full path to file to save to.
:param format: format to save -- 'netcdf3' or 'netcdf4'
are the only options at this point.
"""
self.save(filename, format='netcdf4')
def save(self, filepath, format='netcdf4', variables={}):
"""
Save the ugrid object as a netcdf file.
:param filepath: path to file you want o save to. An existing one
will be clobbered if it already exists.
:param variables: dict of gridded.Variable objects to save to file
Follows the convention established by the netcdf UGRID working group:
http://ugrid-conventions.github.io/ugrid-conventions
NOTE: Variables are saved here, because different conventions do it
differently.
"""
format_options = ('netcdf3', 'netcdf4')
if format not in format_options:
raise ValueError("format: {} not supported. Options are: {}".format(format, format_options))
mesh_name = self.mesh_name
<|code_end|>
. Use current file imports:
(import hashlib
import numpy as np
import gridded.pyugrid.read_netcdf as read_netcdf
import cell_tree2d
from collections import OrderedDict
from gridded.pyugrid.util import point_in_tri
from gridded.utilities import get_writable_dataset
from scipy.spatial import cKDTree
from cell_tree2d import CellTree
from scipy.spatial import cKDTree)
and context including class names, function names, or small code snippets from other files:
# Path: gridded/pyugrid/util.py
# def point_in_tri(face_points, point, return_weights=False):
# """
# Calculates whether point is internal/external
# to element by comparing summed area of sub triangles with area of triangle
# element.
#
# NOTE: this seems like a pretty expensive way to do it
# -- compared to three side of line tests..
# """
# sub_tri_areas = np.zeros(3)
# sub_tri_areas[0] = _signed_area_tri(np.vstack((face_points[(0, 1), :],
# point)))
# sub_tri_areas[1] = _signed_area_tri(np.vstack((face_points[(1, 2), :],
# point)))
# sub_tri_areas[2] = _signed_area_tri(np.vstack((face_points[(0, 2), :],
# point)))
# tri_area = _signed_area_tri(face_points)
#
# if abs(np.abs(sub_tri_areas).sum() - tri_area) / tri_area <= epsilon:
# if return_weights:
# raise NotImplementedError
# # weights = sub_tri_areas/tri_area
# # weights[1] = max(0., min(1., weights[1]))
# # weights[2] = max(0., min(1., weights[2]))
# # if (weights[0]+weights[1]>1):
# # weights[2] = 0
# # weights[1] = 1-weights[0]
# # else:
# # weights[2] = 1-weights[0]-weights[1]
# #
# # return weights
# else:
# return True
# return False
#
# Path: gridded/utilities.py
# def get_writable_dataset(ncfile, format="netcdf4"):
# """
# Utility to create a writable netCDF4 Dataset from a filename, list of filenames,
# or just pass it through if it's already a netCDF4.Dataset
#
# if dataset is not None, it should be a valid netCDF4 Dataset object,
# and it will simply be returned
# """
# if isinstance(ncfile, nc4.Dataset):
# # fixme: check for writable
# return ncfile
# elif isstring(ncfile): # Fixme: should be pathlike...
# print("filename is:", ncfile)
# return nc4.Dataset(ncfile,
# mode="w",
# clobber=True,
# format="NETCDF4")
# else:
# raise ValueError("Must be a string path or a netcdf4 Dataset")
. Output only the next line. | nclocal = get_writable_dataset(filepath) |
Given the code snippet: <|code_start|>"""
Created on Apr 7, 2015
@author: ayan
"""
from __future__ import (absolute_import, division, print_function)
def test_xyz_axis_parse():
xyz = 'X: NMAX Y: MMAXZ Z: KMAX'
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from gridded.pysgrid.read_netcdf import (parse_axes, parse_padding, parse_vector_axis)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/read_netcdf.py
# def parse_axes(axes_attr):
# p = re.compile('([a-zA-Z]: [a-zA-Z_]+)')
# matches = p.findall(axes_attr)
# x_axis = None
# y_axis = None
# z_axis = None
# for match in matches:
# axis_split = match.split(':')
# axis_name = axis_split[0].strip()
# axis_coordinate = axis_split[1].strip()
# if axis_name.lower() == 'x':
# x_axis = axis_coordinate
# elif axis_name.lower() == 'y':
# y_axis = axis_coordinate
# elif axis_name.lower() == 'z':
# z_axis = axis_coordinate
# return x_axis, y_axis, z_axis
#
# def parse_padding(padding_str, mesh_topology_var):
# """
# Use regex expressions to break apart an
# attribute string containing padding types
# for each variable with a cf_role of
# 'grid_topology'.
#
# Padding information is returned within a named tuple
# for each node dimension of an edge, face, or vertical
# dimension. The named tuples have the following attributes:
# mesh_topology_var, dim_name, dim_var, and padding.
# Padding information is returned as a list
# of these named tuples.
#
# :param str padding_str: string containing padding types from
# a netCDF attribute.
# :return: named tuples with padding information.
# :rtype: list.
#
# """
# p = re.compile('([a-zA-Z0-9_]+:) ([a-zA-Z0-9_]+) (\(padding: [a-zA-Z]+\))')
# padding_matches = p.findall(padding_str)
# padding_type_list = []
# for padding_match in padding_matches:
# raw_dim, raw_sub_dim, raw_padding_var = padding_match
# dim = raw_dim.split(':')[0]
# sub_dim = raw_sub_dim
# # Remove parentheses. (That is why regular expressions are bad!
# # You need a commend to explain what is going on!!)
# cleaned_padding_var = re.sub('[\(\)]', '', raw_padding_var)
# # Get the padding value and remove spaces.
# padding_type = cleaned_padding_var.split(':')[1].strip()
# grid_padding = GridPadding(mesh_topology_var=mesh_topology_var,
# face_dim=dim,
# node_dim=sub_dim,
# padding=padding_type
# )
# padding_type_list.append(grid_padding)
# if len(padding_type_list) > 0:
# final_padding_types = padding_type_list
# else:
# final_padding_types = None
# msg = ('The netCDF file appears to have conform to SGRID conventions, '
# 'but padding values cannot be found.')
# raise ValueError(msg)
# return final_padding_types
#
# def parse_vector_axis(variable_standard_name):
# p = re.compile('[a-z_]+_[xyz]_[a-z_]+')
# match = p.match(variable_standard_name)
# if match is not None:
# direction_pattern = re.compile('_[xyz]_')
# direction_substr = direction_pattern.search(match.string).group()
# vector_direction = direction_substr.replace('_', '').upper()
# else:
# vector_direction = None
# return vector_direction
. Output only the next line. | result = parse_axes(xyz) |
Given the code snippet: <|code_start|>from __future__ import (absolute_import, division, print_function)
def test_xyz_axis_parse():
xyz = 'X: NMAX Y: MMAXZ Z: KMAX'
result = parse_axes(xyz)
expected = ('NMAX', 'MMAXZ', 'KMAX')
assert result == expected
def test_xy_axis_parse():
xy = 'X: xi_psi Y: eta_psi'
result = parse_axes(xy)
expected = ('xi_psi', 'eta_psi', None)
assert result == expected
@pytest.fixture
def parse_pad():
grid_topology = 'some_grid'
pad_1 = 'xi_v: xi_psi (padding: high) eta_v: eta_psi'
pad_2 = 'xi_rho: xi_psi (padding: both) eta_rho: eta_psi (padding: low)'
pad_no = 'MMAXZ: MMAX NMAXZ: NMAX'
return grid_topology, pad_1, pad_2, pad_no
def test_mesh_name(parse_pad):
grid_topology, pad_1, pad_2, pad_no = parse_pad
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from gridded.pysgrid.read_netcdf import (parse_axes, parse_padding, parse_vector_axis)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/read_netcdf.py
# def parse_axes(axes_attr):
# p = re.compile('([a-zA-Z]: [a-zA-Z_]+)')
# matches = p.findall(axes_attr)
# x_axis = None
# y_axis = None
# z_axis = None
# for match in matches:
# axis_split = match.split(':')
# axis_name = axis_split[0].strip()
# axis_coordinate = axis_split[1].strip()
# if axis_name.lower() == 'x':
# x_axis = axis_coordinate
# elif axis_name.lower() == 'y':
# y_axis = axis_coordinate
# elif axis_name.lower() == 'z':
# z_axis = axis_coordinate
# return x_axis, y_axis, z_axis
#
# def parse_padding(padding_str, mesh_topology_var):
# """
# Use regex expressions to break apart an
# attribute string containing padding types
# for each variable with a cf_role of
# 'grid_topology'.
#
# Padding information is returned within a named tuple
# for each node dimension of an edge, face, or vertical
# dimension. The named tuples have the following attributes:
# mesh_topology_var, dim_name, dim_var, and padding.
# Padding information is returned as a list
# of these named tuples.
#
# :param str padding_str: string containing padding types from
# a netCDF attribute.
# :return: named tuples with padding information.
# :rtype: list.
#
# """
# p = re.compile('([a-zA-Z0-9_]+:) ([a-zA-Z0-9_]+) (\(padding: [a-zA-Z]+\))')
# padding_matches = p.findall(padding_str)
# padding_type_list = []
# for padding_match in padding_matches:
# raw_dim, raw_sub_dim, raw_padding_var = padding_match
# dim = raw_dim.split(':')[0]
# sub_dim = raw_sub_dim
# # Remove parentheses. (That is why regular expressions are bad!
# # You need a commend to explain what is going on!!)
# cleaned_padding_var = re.sub('[\(\)]', '', raw_padding_var)
# # Get the padding value and remove spaces.
# padding_type = cleaned_padding_var.split(':')[1].strip()
# grid_padding = GridPadding(mesh_topology_var=mesh_topology_var,
# face_dim=dim,
# node_dim=sub_dim,
# padding=padding_type
# )
# padding_type_list.append(grid_padding)
# if len(padding_type_list) > 0:
# final_padding_types = padding_type_list
# else:
# final_padding_types = None
# msg = ('The netCDF file appears to have conform to SGRID conventions, '
# 'but padding values cannot be found.')
# raise ValueError(msg)
# return final_padding_types
#
# def parse_vector_axis(variable_standard_name):
# p = re.compile('[a-z_]+_[xyz]_[a-z_]+')
# match = p.match(variable_standard_name)
# if match is not None:
# direction_pattern = re.compile('_[xyz]_')
# direction_substr = direction_pattern.search(match.string).group()
# vector_direction = direction_substr.replace('_', '').upper()
# else:
# vector_direction = None
# return vector_direction
. Output only the next line. | result = parse_padding(pad_1, grid_topology) |
Based on the snippet: <|code_start|> assert sub_dim == expected_sub_dim
assert dim == expected_dim
def test_one_padding_type(parse_pad):
grid_topology, pad_1, pad_2, pad_no = parse_pad
result = parse_padding(pad_1, grid_topology)
expected_len = 1
padding_datum_0 = result[0]
padding_type = padding_datum_0.padding
sub_dim = padding_datum_0.node_dim
dim = padding_datum_0.face_dim
expected_padding_type = 'high'
expected_sub_dim = 'xi_psi'
expected_dim = 'xi_v'
assert len(result) == expected_len
assert padding_type == expected_padding_type
assert sub_dim == expected_sub_dim
assert dim == expected_dim
def test_no_padding(parse_pad):
grid_topology, pad_1, pad_2, pad_no = parse_pad
with pytest.raises(ValueError):
parse_padding(padding_str=pad_no,
mesh_topology_var=grid_topology)
def test_std_name_with_velocity_direction():
standard_name_1 = 'sea_water_y_velocity'
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from gridded.pysgrid.read_netcdf import (parse_axes, parse_padding, parse_vector_axis)
and context (classes, functions, sometimes code) from other files:
# Path: gridded/pysgrid/read_netcdf.py
# def parse_axes(axes_attr):
# p = re.compile('([a-zA-Z]: [a-zA-Z_]+)')
# matches = p.findall(axes_attr)
# x_axis = None
# y_axis = None
# z_axis = None
# for match in matches:
# axis_split = match.split(':')
# axis_name = axis_split[0].strip()
# axis_coordinate = axis_split[1].strip()
# if axis_name.lower() == 'x':
# x_axis = axis_coordinate
# elif axis_name.lower() == 'y':
# y_axis = axis_coordinate
# elif axis_name.lower() == 'z':
# z_axis = axis_coordinate
# return x_axis, y_axis, z_axis
#
# def parse_padding(padding_str, mesh_topology_var):
# """
# Use regex expressions to break apart an
# attribute string containing padding types
# for each variable with a cf_role of
# 'grid_topology'.
#
# Padding information is returned within a named tuple
# for each node dimension of an edge, face, or vertical
# dimension. The named tuples have the following attributes:
# mesh_topology_var, dim_name, dim_var, and padding.
# Padding information is returned as a list
# of these named tuples.
#
# :param str padding_str: string containing padding types from
# a netCDF attribute.
# :return: named tuples with padding information.
# :rtype: list.
#
# """
# p = re.compile('([a-zA-Z0-9_]+:) ([a-zA-Z0-9_]+) (\(padding: [a-zA-Z]+\))')
# padding_matches = p.findall(padding_str)
# padding_type_list = []
# for padding_match in padding_matches:
# raw_dim, raw_sub_dim, raw_padding_var = padding_match
# dim = raw_dim.split(':')[0]
# sub_dim = raw_sub_dim
# # Remove parentheses. (That is why regular expressions are bad!
# # You need a commend to explain what is going on!!)
# cleaned_padding_var = re.sub('[\(\)]', '', raw_padding_var)
# # Get the padding value and remove spaces.
# padding_type = cleaned_padding_var.split(':')[1].strip()
# grid_padding = GridPadding(mesh_topology_var=mesh_topology_var,
# face_dim=dim,
# node_dim=sub_dim,
# padding=padding_type
# )
# padding_type_list.append(grid_padding)
# if len(padding_type_list) > 0:
# final_padding_types = padding_type_list
# else:
# final_padding_types = None
# msg = ('The netCDF file appears to have conform to SGRID conventions, '
# 'but padding values cannot be found.')
# raise ValueError(msg)
# return final_padding_types
#
# def parse_vector_axis(variable_standard_name):
# p = re.compile('[a-z_]+_[xyz]_[a-z_]+')
# match = p.match(variable_standard_name)
# if match is not None:
# direction_pattern = re.compile('_[xyz]_')
# direction_substr = direction_pattern.search(match.string).group()
# vector_direction = direction_substr.replace('_', '').upper()
# else:
# vector_direction = None
# return vector_direction
. Output only the next line. | direction = parse_vector_axis(standard_name_1) |
Continue the code snippet: <|code_start|># is the same as `two_triangles`. If so use that.
# Some sample grid data: about the simplest triangle grid possible.
# 4 nodes, two triangles, five edges.
nodes = [(0.1, 0.1),
(2.1, 0.1),
(1.1, 2.1),
(3.1, 2.1)]
node_lon = np.array(nodes)[:, 0]
node_lat = np.array(nodes)[:, 1]
faces = [(0, 1, 2),
(1, 3, 2)]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
boundaries = [(0, 1),
(0, 2),
(1, 3),
(2, 3)]
def test_full_set():
<|code_end|>
. Use current file imports:
import numpy as np
import pytest
from gridded.grids import Grid_U as UGrid
from gridded.pyugrid.ugrid import IND_DT, NODE_DT
and context (classes, functions, or code) from other files:
# Path: gridded/grids.py
# class Grid_U(GridBase, UGrid):
#
# @classmethod
# def _find_required_grid_attrs(cls, filename, dataset=None, grid_topology=None):
#
# gf_vars = dataset.variables if dataset is not None else get_dataset(filename).variables
# gf_vars = dict([(k.lower(), v) for k, v in gf_vars.items()])
# # Get superset attributes
# init_args, gt = super(Grid_U, cls)._find_required_grid_attrs(filename=filename,
# dataset=dataset,
# grid_topology=grid_topology)
#
# face_attrs = ['faces']
# face_var_names = ['faces', 'tris', 'nv', 'ele']
# if grid_topology is None:
# for n in face_var_names:
# if n in gf_vars:
# init_args[face_attrs[0]] = gf_vars[n][:]
# gt[face_attrs[0]] = n
# break
# if face_attrs[0] not in init_args:
# raise ValueError('Unable to find face connectivity array.')
#
# else:
# for n, v in grid_topology.items():
# if n in face_attrs:
# init_args[n] = gf_vars[v][:]
# break
# if init_args['faces'].shape[0] == 3:
# init_args['faces'] = np.ascontiguousarray(np.array(init_args['faces']).T - 1)
#
# return init_args, gt
#
# @classmethod
# def gen_from_quads(cls, nodes):
# if not len(nodes.shape) == 3:
# raise ValueError('Nodes of a quad grid must be 2 dimensional')
# lin_nodes = None
# if isinstance(nodes, np.ma.MaskedArray):
# lin_nodes = nodes.reshape(-1, 2)[nodes]
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
#
# NODE_DT = np.float64 # datatype used for node coordinates.
. Output only the next line. | grid = UGrid(nodes=nodes, |
Based on the snippet: <|code_start|>node_lat = np.array(nodes)[:, 1]
faces = [(0, 1, 2),
(1, 3, 2)]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
boundaries = [(0, 1),
(0, 2),
(1, 3),
(2, 3)]
def test_full_set():
grid = UGrid(nodes=nodes,
faces=faces,
edges=edges,
boundaries=boundaries,
)
# Check the dtype of key objects.
# Implicitly makes sure they are numpy arrays (or array-like).
assert grid.num_vertices == 3
assert grid.nodes.dtype == NODE_DT
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import pytest
from gridded.grids import Grid_U as UGrid
from gridded.pyugrid.ugrid import IND_DT, NODE_DT
and context (classes, functions, sometimes code) from other files:
# Path: gridded/grids.py
# class Grid_U(GridBase, UGrid):
#
# @classmethod
# def _find_required_grid_attrs(cls, filename, dataset=None, grid_topology=None):
#
# gf_vars = dataset.variables if dataset is not None else get_dataset(filename).variables
# gf_vars = dict([(k.lower(), v) for k, v in gf_vars.items()])
# # Get superset attributes
# init_args, gt = super(Grid_U, cls)._find_required_grid_attrs(filename=filename,
# dataset=dataset,
# grid_topology=grid_topology)
#
# face_attrs = ['faces']
# face_var_names = ['faces', 'tris', 'nv', 'ele']
# if grid_topology is None:
# for n in face_var_names:
# if n in gf_vars:
# init_args[face_attrs[0]] = gf_vars[n][:]
# gt[face_attrs[0]] = n
# break
# if face_attrs[0] not in init_args:
# raise ValueError('Unable to find face connectivity array.')
#
# else:
# for n, v in grid_topology.items():
# if n in face_attrs:
# init_args[n] = gf_vars[v][:]
# break
# if init_args['faces'].shape[0] == 3:
# init_args['faces'] = np.ascontiguousarray(np.array(init_args['faces']).T - 1)
#
# return init_args, gt
#
# @classmethod
# def gen_from_quads(cls, nodes):
# if not len(nodes.shape) == 3:
# raise ValueError('Nodes of a quad grid must be 2 dimensional')
# lin_nodes = None
# if isinstance(nodes, np.ma.MaskedArray):
# lin_nodes = nodes.reshape(-1, 2)[nodes]
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
#
# NODE_DT = np.float64 # datatype used for node coordinates.
. Output only the next line. | assert grid.faces.dtype == IND_DT |
Here is a snippet: <|code_start|>node_lon = np.array(nodes)[:, 0]
node_lat = np.array(nodes)[:, 1]
faces = [(0, 1, 2),
(1, 3, 2)]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
boundaries = [(0, 1),
(0, 2),
(1, 3),
(2, 3)]
def test_full_set():
grid = UGrid(nodes=nodes,
faces=faces,
edges=edges,
boundaries=boundaries,
)
# Check the dtype of key objects.
# Implicitly makes sure they are numpy arrays (or array-like).
assert grid.num_vertices == 3
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import pytest
from gridded.grids import Grid_U as UGrid
from gridded.pyugrid.ugrid import IND_DT, NODE_DT
and context from other files:
# Path: gridded/grids.py
# class Grid_U(GridBase, UGrid):
#
# @classmethod
# def _find_required_grid_attrs(cls, filename, dataset=None, grid_topology=None):
#
# gf_vars = dataset.variables if dataset is not None else get_dataset(filename).variables
# gf_vars = dict([(k.lower(), v) for k, v in gf_vars.items()])
# # Get superset attributes
# init_args, gt = super(Grid_U, cls)._find_required_grid_attrs(filename=filename,
# dataset=dataset,
# grid_topology=grid_topology)
#
# face_attrs = ['faces']
# face_var_names = ['faces', 'tris', 'nv', 'ele']
# if grid_topology is None:
# for n in face_var_names:
# if n in gf_vars:
# init_args[face_attrs[0]] = gf_vars[n][:]
# gt[face_attrs[0]] = n
# break
# if face_attrs[0] not in init_args:
# raise ValueError('Unable to find face connectivity array.')
#
# else:
# for n, v in grid_topology.items():
# if n in face_attrs:
# init_args[n] = gf_vars[v][:]
# break
# if init_args['faces'].shape[0] == 3:
# init_args['faces'] = np.ascontiguousarray(np.array(init_args['faces']).T - 1)
#
# return init_args, gt
#
# @classmethod
# def gen_from_quads(cls, nodes):
# if not len(nodes.shape) == 3:
# raise ValueError('Nodes of a quad grid must be 2 dimensional')
# lin_nodes = None
# if isinstance(nodes, np.ma.MaskedArray):
# lin_nodes = nodes.reshape(-1, 2)[nodes]
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
#
# NODE_DT = np.float64 # datatype used for node coordinates.
, which may include functions, classes, or code. Output only the next line. | assert grid.nodes.dtype == NODE_DT |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""
Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
UGrid = ugrid.UGrid
files = os.path.join(os.path.split(__file__)[0], 'files')
def test_simple_read():
"""Can it be read at all?"""
<|code_end|>
. Use current file imports:
(import os
import pytest
import numpy as np
import netCDF4
from .utilities import chdir
from gridded.pyugrid import ugrid
from gridded.pyugrid import read_netcdf)
and context including class names, function names, or small code snippets from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
# curdir = os.getcwd()
# try:
# if dirname is not None:
# os.chdir(dirname)
# yield
# finally:
# os.chdir(curdir)
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
# NODE_DT = np.float64 # datatype used for node coordinates.
# class UGrid(object):
# def __init__(self,
# nodes=None,
# node_lon=None,
# node_lat=None,
# faces=None,
# edges=None,
# boundaries=None,
# face_face_connectivity=None,
# face_edge_connectivity=None,
# edge_coordinates=None,
# face_coordinates=None,
# boundary_coordinates=None,
# data=None,
# mesh_name="mesh",
# ):
# def from_ncfile(klass, nc_url, mesh_name=None): # , load_data=False):
# def from_nc_dataset(klass, nc, mesh_name=None): # , load_data=False):
# def info(self):
# def check_consistent(self):
# def num_vertices(self):
# def nodes(self):
# def node_lon(self):
# def node_lat(self):
# def nodes(self, nodes_coords):
# def nodes(self):
# def faces(self):
# def faces(self, faces_indexes):
# def faces(self):
# def edges(self):
# def edges(self, edges_indexes):
# def edges(self):
# def boundaries(self):
# def boundaries(self, boundaries_indexes):
# def boundaries(self):
# def face_face_connectivity(self):
# def face_face_connectivity(self, face_face_connectivity):
# def face_face_connectivity(self):
# def face_edge_connectivity(self):
# def face_edge_connectivity(self, face_edge_connectivity):
# def face_edge_connectivity(self):
# def infer_location(self, data):
# def locate_nodes(self, points):
# def _build_kdtree(self):
# def _hash_of_pts(self, points):
# def _add_memo(self, points, item, D, _copy=False, _hash=None):
# def _get_memoed(self, points, D, _copy=False, _hash=None):
# def locate_faces(self, points, method='celltree', _copy=False, _memo=True, _hash=None):
# def build_celltree(self):
# def interpolation_alphas(self, points, indices=None, _copy=False, _memo=True, _hash=None):
# def interpolate_var_to_points(self,
# points,
# variable,
# location=None,
# fill_value=0,
# indices=None,
# alphas=None,
# slices=None,
# _copy=False,
# _memo=True,
# _hash=None):
# def build_face_face_connectivity(self):
# def get_lines(self):
# def build_edges(self):
# def build_boundaries(self):
# def build_face_edge_connectivity(self):
# def build_face_coordinates(self):
# def build_edge_coordinates(self):
# def build_boundary_coordinates(self):
# def save_as_netcdf(self, filename, format='netcdf4'):
# def save(self, filepath, format='netcdf4', variables={}):
# def _save_variables(self, nclocal, variables):
#
# Path: gridded/pyugrid/read_netcdf.py
# def find_mesh_names(nc):
# def is_valid_mesh(nc, varname):
# def load_grid_from_nc_dataset(nc, grid, mesh_name=None): # , load_data=True):
# def load_grid_from_ncfilename(filename, grid, mesh_name=None): # , load_data=True):
. Output only the next line. | with chdir(files): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
"""
Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
<|code_end|>
, predict the next line using imports from the current file:
import os
import pytest
import numpy as np
import netCDF4
from .utilities import chdir
from gridded.pyugrid import ugrid
from gridded.pyugrid import read_netcdf
and context including class names, function names, and sometimes code from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
# curdir = os.getcwd()
# try:
# if dirname is not None:
# os.chdir(dirname)
# yield
# finally:
# os.chdir(curdir)
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
# NODE_DT = np.float64 # datatype used for node coordinates.
# class UGrid(object):
# def __init__(self,
# nodes=None,
# node_lon=None,
# node_lat=None,
# faces=None,
# edges=None,
# boundaries=None,
# face_face_connectivity=None,
# face_edge_connectivity=None,
# edge_coordinates=None,
# face_coordinates=None,
# boundary_coordinates=None,
# data=None,
# mesh_name="mesh",
# ):
# def from_ncfile(klass, nc_url, mesh_name=None): # , load_data=False):
# def from_nc_dataset(klass, nc, mesh_name=None): # , load_data=False):
# def info(self):
# def check_consistent(self):
# def num_vertices(self):
# def nodes(self):
# def node_lon(self):
# def node_lat(self):
# def nodes(self, nodes_coords):
# def nodes(self):
# def faces(self):
# def faces(self, faces_indexes):
# def faces(self):
# def edges(self):
# def edges(self, edges_indexes):
# def edges(self):
# def boundaries(self):
# def boundaries(self, boundaries_indexes):
# def boundaries(self):
# def face_face_connectivity(self):
# def face_face_connectivity(self, face_face_connectivity):
# def face_face_connectivity(self):
# def face_edge_connectivity(self):
# def face_edge_connectivity(self, face_edge_connectivity):
# def face_edge_connectivity(self):
# def infer_location(self, data):
# def locate_nodes(self, points):
# def _build_kdtree(self):
# def _hash_of_pts(self, points):
# def _add_memo(self, points, item, D, _copy=False, _hash=None):
# def _get_memoed(self, points, D, _copy=False, _hash=None):
# def locate_faces(self, points, method='celltree', _copy=False, _memo=True, _hash=None):
# def build_celltree(self):
# def interpolation_alphas(self, points, indices=None, _copy=False, _memo=True, _hash=None):
# def interpolate_var_to_points(self,
# points,
# variable,
# location=None,
# fill_value=0,
# indices=None,
# alphas=None,
# slices=None,
# _copy=False,
# _memo=True,
# _hash=None):
# def build_face_face_connectivity(self):
# def get_lines(self):
# def build_edges(self):
# def build_boundaries(self):
# def build_face_edge_connectivity(self):
# def build_face_coordinates(self):
# def build_edge_coordinates(self):
# def build_boundary_coordinates(self):
# def save_as_netcdf(self, filename, format='netcdf4'):
# def save(self, filepath, format='netcdf4', variables={}):
# def _save_variables(self, nclocal, variables):
#
# Path: gridded/pyugrid/read_netcdf.py
# def find_mesh_names(nc):
# def is_valid_mesh(nc, varname):
# def load_grid_from_nc_dataset(nc, grid, mesh_name=None): # , load_data=True):
# def load_grid_from_ncfilename(filename, grid, mesh_name=None): # , load_data=True):
. Output only the next line. | UGrid = ugrid.UGrid |
Given the code snippet: <|code_start|>Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
UGrid = ugrid.UGrid
files = os.path.join(os.path.split(__file__)[0], 'files')
def test_simple_read():
"""Can it be read at all?"""
with chdir(files):
grid = UGrid.from_ncfile('ElevenPoints_UGRIDv0.9.nc')
assert isinstance(grid, UGrid)
def test_get_mesh_names():
"""
Check that it can find the mesh variable names.
"""
with chdir(files):
nc = netCDF4.Dataset('ElevenPoints_UGRIDv0.9.nc')
<|code_end|>
, generate the next line using the imports in this file:
import os
import pytest
import numpy as np
import netCDF4
from .utilities import chdir
from gridded.pyugrid import ugrid
from gridded.pyugrid import read_netcdf
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
# curdir = os.getcwd()
# try:
# if dirname is not None:
# os.chdir(dirname)
# yield
# finally:
# os.chdir(curdir)
#
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
# NODE_DT = np.float64 # datatype used for node coordinates.
# class UGrid(object):
# def __init__(self,
# nodes=None,
# node_lon=None,
# node_lat=None,
# faces=None,
# edges=None,
# boundaries=None,
# face_face_connectivity=None,
# face_edge_connectivity=None,
# edge_coordinates=None,
# face_coordinates=None,
# boundary_coordinates=None,
# data=None,
# mesh_name="mesh",
# ):
# def from_ncfile(klass, nc_url, mesh_name=None): # , load_data=False):
# def from_nc_dataset(klass, nc, mesh_name=None): # , load_data=False):
# def info(self):
# def check_consistent(self):
# def num_vertices(self):
# def nodes(self):
# def node_lon(self):
# def node_lat(self):
# def nodes(self, nodes_coords):
# def nodes(self):
# def faces(self):
# def faces(self, faces_indexes):
# def faces(self):
# def edges(self):
# def edges(self, edges_indexes):
# def edges(self):
# def boundaries(self):
# def boundaries(self, boundaries_indexes):
# def boundaries(self):
# def face_face_connectivity(self):
# def face_face_connectivity(self, face_face_connectivity):
# def face_face_connectivity(self):
# def face_edge_connectivity(self):
# def face_edge_connectivity(self, face_edge_connectivity):
# def face_edge_connectivity(self):
# def infer_location(self, data):
# def locate_nodes(self, points):
# def _build_kdtree(self):
# def _hash_of_pts(self, points):
# def _add_memo(self, points, item, D, _copy=False, _hash=None):
# def _get_memoed(self, points, D, _copy=False, _hash=None):
# def locate_faces(self, points, method='celltree', _copy=False, _memo=True, _hash=None):
# def build_celltree(self):
# def interpolation_alphas(self, points, indices=None, _copy=False, _memo=True, _hash=None):
# def interpolate_var_to_points(self,
# points,
# variable,
# location=None,
# fill_value=0,
# indices=None,
# alphas=None,
# slices=None,
# _copy=False,
# _memo=True,
# _hash=None):
# def build_face_face_connectivity(self):
# def get_lines(self):
# def build_edges(self):
# def build_boundaries(self):
# def build_face_edge_connectivity(self):
# def build_face_coordinates(self):
# def build_edge_coordinates(self):
# def build_boundary_coordinates(self):
# def save_as_netcdf(self, filename, format='netcdf4'):
# def save(self, filepath, format='netcdf4', variables={}):
# def _save_variables(self, nclocal, variables):
#
# Path: gridded/pyugrid/read_netcdf.py
# def find_mesh_names(nc):
# def is_valid_mesh(nc, varname):
# def load_grid_from_nc_dataset(nc, grid, mesh_name=None): # , load_data=True):
# def load_grid_from_ncfilename(filename, grid, mesh_name=None): # , load_data=True):
. Output only the next line. | names = read_netcdf.find_mesh_names(nc) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""
Testing of various utilities to manipulate the grid.
"""
from __future__ import (absolute_import, division, print_function)
def test_build_face_face_connectivity_small(two_triangles):
ugrid = two_triangles
ugrid.build_face_face_connectivity()
face_face = ugrid.face_face_connectivity
assert np.array_equal(face_face[0], [-1, 1, -1])
assert np.array_equal(face_face[1], [-1, -1, 0])
<|code_end|>
with the help of current file imports:
import numpy as np
import pytest
from .utilities import two_triangles, twenty_one_triangles
and context from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @pytest.fixture
# def two_triangles():
# """
# Returns a simple triangular grid: 4 nodes, two triangles, five edges.
#
# """
# nodes = [(0.1, 0.1),
# (2.1, 0.1),
# (1.1, 2.1),
# (3.1, 2.1)]
#
# faces = [(0, 1, 2),
# (1, 3, 2), ]
#
# edges = [(0, 1),
# (1, 3),
# (3, 2),
# (2, 0),
# (1, 2)]
#
# return ugrid.UGrid(nodes=nodes, faces=faces, edges=edges)
#
# @pytest.fixture
# def twenty_one_triangles():
# """
# Returns a basic triangular grid: 21 triangles, a hole, and a tail.
#
# """
# nodes = [(5, 1),
# (10, 1),
# (3, 3),
# (7, 3),
# (9, 4),
# (12, 4),
# (5, 5),
# (3, 7),
# (5, 7),
# (7, 7),
# (9, 7),
# (11, 7),
# (5, 9),
# (8, 9),
# (11, 9),
# (9, 11),
# (11, 11),
# (7, 13),
# (9, 13),
# (7, 15), ]
#
# faces = [(0, 1, 3),
# (0, 6, 2),
# (0, 3, 6),
# (1, 4, 3),
# (1, 5, 4),
# (2, 6, 7),
# (6, 8, 7),
# (7, 8, 12),
# (6, 9, 8),
# (8, 9, 12),
# (9, 13, 12),
# (4, 5, 11),
# (4, 11, 10),
# (9, 10, 13),
# (10, 11, 14),
# (10, 14, 13),
# (13, 14, 15),
# (14, 16, 15),
# (15, 16, 18),
# (15, 18, 17),
# (17, 18, 19), ]
#
# # We may want to use this later to define just the outer boundary.
# boundaries = [(0, 1),
# (1, 5),
# (5, 11),
# (11, 14),
# (14, 16),
# (16, 18),
# (18, 19),
# (19, 17),
# (17, 15),
# (15, 13),
# (13, 12),
# (12, 7),
# (7, 2),
# (2, 0),
# (3, 4),
# (4, 10),
# (10, 9),
# (9, 6),
# (6, 3), ]
#
# grid = ugrid.UGrid(nodes=nodes, faces=faces, boundaries=boundaries)
# grid.build_edges()
# return grid
, which may contain function names, class names, or code. Output only the next line. | def test_build_face_face_connectivity_big(twenty_one_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Tests for adding a data attribute to a UGrid object.
"""
from __future__ import (absolute_import, division, print_function)
# from gridded.pyugrid import UVar
pytestmark = pytest.mark.skipif(True, reason="gridded does not support UVars anymore")
#pytest.mark.skipif(True, "gridded does not support UVars anymore")
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import pytest
from .utilities import two_triangles
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @pytest.fixture
# def two_triangles():
# """
# Returns a simple triangular grid: 4 nodes, two triangles, five edges.
#
# """
# nodes = [(0.1, 0.1),
# (2.1, 0.1),
# (1.1, 2.1),
# (3.1, 2.1)]
#
# faces = [(0, 1, 2),
# (1, 3, 2), ]
#
# edges = [(0, 1),
# (1, 3),
# (3, 2),
# (2, 0),
# (1, 2)]
#
# return ugrid.UGrid(nodes=nodes, faces=faces, edges=edges)
. Output only the next line. | def test_add_all_data(two_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Tests for the UVar object
"""
from __future__ import (absolute_import, division, print_function)
# pytestmark = pytest.mark.skipif(True, reason="gridded does not support UVars anymore")
test_files = os.path.join(os.path.dirname(__file__), 'files')
def test_init():
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import pytest
import netCDF4
from gridded.pyugrid.uvar import UVar
from .utilities import chdir
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pyugrid/uvar.py
# class UVar(object):
# """
# A class to hold a variable associated with the UGrid. Data can be on the
# nodes, edges, etc. -- "UGrid Variable"
#
# It holds an array of the data, as well as the attributes associated
# with that data -- this is mapped to a netcdf variable with
# attributes(attributes get stored in the netcdf file)
# """
#
# def __init__(self, name, location, data=None, attributes=None):
# """
# create a UVar object
# :param name: the name of the variable (depth, u_velocity, etc.)
# :type name: string
#
# :param location: the type of grid element the data is associated with:
# 'node', 'edge', or 'face'
#
# :param data: The data itself
# :type data: 1-d numpy array or array-like object ().
# If you have a list or tuple, it should be something that can be
# converted to a numpy array (list, etc.)
# """
# self.name = name
#
# if location not in ['node', 'edge', 'face', 'boundary']:
# raise ValueError("location must be one of: "
# "'node', 'edge', 'face', 'boundary'")
#
# self.location = location
#
# if data is None:
# # Could be any data type, but we'll default to float
# self._data = np.zeros((0,), dtype=np.float64)
# else:
# self._data = asarraylike(data)
#
# # FixMe: we need a separate attribute dict -- we really do'nt want all this
# # getting mixed up with the python object attributes
# self.attributes = {} if attributes is None else attributes
# # if the data is a netcdf variable, pull the attributes from there
# try:
# for attr in data.ncattrs():
# self.attributes[attr] = data.getncattr(attr)
# except AttributeError: # must not be a netcdf variable
# pass
#
# self._cache = OrderedDict()
#
# # def update_attrs(self, attrs):
# # """
# # update the attributes of the UVar object
#
# # :param attr: Dict containing attributes to be added to the object
# # """
# # for key, val in attrs.items():
# # setattr(self, key, val)
#
# @property
# def data(self):
# """
# The data associated with the UVar -- a numpy array-like object with the actual data
# """
# return self._data
#
# @data.setter
# def data(self, data):
# self._data = asarraylike(data)
#
# @data.deleter
# def data(self):
# self._data = self._data = np.zeros((0,), dtype=np.float64)
#
# @property
# def shape(self):
# """
# The shape of the data array associated with the UVar.
# """
# return self.data.shape
#
# @property
# def max(self):
# """ maximum value of the variable """
# return np.max(self._data)
#
# @property
# def min(self):
# """ minimum value of the variable """
# return np.min(self._data)
#
# @property
# def dtype(self):
# """ data type of the variable """
# return self.data.dtype
#
# @property
# def ndim(self):
# """ number of dimensions of the variable """
# return self.data.ndim
#
# def __getitem__(self, item):
# """
# Transfers responsibility to the data's __getitem__ if not cached
# """
# rv = None
# if str(item) in self._cache:
# rv = self._cache[str(item)]
# else:
# rv = self._data.__getitem__(item)
# self._cache[str(item)] = rv
# if len(self._cache) > 3:
# self._cache.popitem(last=False)
# return rv
#
# def __str__(self):
# print("in __str__, data is:", self.data)
# msg = ("UVar object: {0:s}, on the {1:s}s, and {2:d} data "
# "points\nAttributes: {3}").format
# return msg(self.name, self.location, len(self.data), self.attributes)
#
# def __len__(self):
# return len(self.data)
#
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
# curdir = os.getcwd()
# try:
# if dirname is not None:
# os.chdir(dirname)
# yield
# finally:
# os.chdir(curdir)
. Output only the next line. | d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0]) |
Predict the next line after this snippet: <|code_start|>
def test_delete_data():
d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])
del d.data
assert np.array_equal(d.data, [])
def test_str():
d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])
assert str(d) == ('UVar object: depth, on the nodes, and 4 data points\n'
'Attributes: {}')
def test_add_attributes():
d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])
d.attributes = {'standard_name': 'sea_floor_depth_below_geoid',
'units': 'm',
'positive': 'down'}
assert d.attributes['units'] == 'm'
assert d.attributes['positive'] == 'down'
def test_nc_variable():
"""
test that it works with a netcdf variable object
"""
# make a variable
<|code_end|>
using the current file's imports:
import os
import numpy as np
import pytest
import netCDF4
from gridded.pyugrid.uvar import UVar
from .utilities import chdir
and any relevant context from other files:
# Path: gridded/pyugrid/uvar.py
# class UVar(object):
# """
# A class to hold a variable associated with the UGrid. Data can be on the
# nodes, edges, etc. -- "UGrid Variable"
#
# It holds an array of the data, as well as the attributes associated
# with that data -- this is mapped to a netcdf variable with
# attributes(attributes get stored in the netcdf file)
# """
#
# def __init__(self, name, location, data=None, attributes=None):
# """
# create a UVar object
# :param name: the name of the variable (depth, u_velocity, etc.)
# :type name: string
#
# :param location: the type of grid element the data is associated with:
# 'node', 'edge', or 'face'
#
# :param data: The data itself
# :type data: 1-d numpy array or array-like object ().
# If you have a list or tuple, it should be something that can be
# converted to a numpy array (list, etc.)
# """
# self.name = name
#
# if location not in ['node', 'edge', 'face', 'boundary']:
# raise ValueError("location must be one of: "
# "'node', 'edge', 'face', 'boundary'")
#
# self.location = location
#
# if data is None:
# # Could be any data type, but we'll default to float
# self._data = np.zeros((0,), dtype=np.float64)
# else:
# self._data = asarraylike(data)
#
# # FixMe: we need a separate attribute dict -- we really do'nt want all this
# # getting mixed up with the python object attributes
# self.attributes = {} if attributes is None else attributes
# # if the data is a netcdf variable, pull the attributes from there
# try:
# for attr in data.ncattrs():
# self.attributes[attr] = data.getncattr(attr)
# except AttributeError: # must not be a netcdf variable
# pass
#
# self._cache = OrderedDict()
#
# # def update_attrs(self, attrs):
# # """
# # update the attributes of the UVar object
#
# # :param attr: Dict containing attributes to be added to the object
# # """
# # for key, val in attrs.items():
# # setattr(self, key, val)
#
# @property
# def data(self):
# """
# The data associated with the UVar -- a numpy array-like object with the actual data
# """
# return self._data
#
# @data.setter
# def data(self, data):
# self._data = asarraylike(data)
#
# @data.deleter
# def data(self):
# self._data = self._data = np.zeros((0,), dtype=np.float64)
#
# @property
# def shape(self):
# """
# The shape of the data array associated with the UVar.
# """
# return self.data.shape
#
# @property
# def max(self):
# """ maximum value of the variable """
# return np.max(self._data)
#
# @property
# def min(self):
# """ minimum value of the variable """
# return np.min(self._data)
#
# @property
# def dtype(self):
# """ data type of the variable """
# return self.data.dtype
#
# @property
# def ndim(self):
# """ number of dimensions of the variable """
# return self.data.ndim
#
# def __getitem__(self, item):
# """
# Transfers responsibility to the data's __getitem__ if not cached
# """
# rv = None
# if str(item) in self._cache:
# rv = self._cache[str(item)]
# else:
# rv = self._data.__getitem__(item)
# self._cache[str(item)] = rv
# if len(self._cache) > 3:
# self._cache.popitem(last=False)
# return rv
#
# def __str__(self):
# print("in __str__, data is:", self.data)
# msg = ("UVar object: {0:s}, on the {1:s}s, and {2:d} data "
# "points\nAttributes: {3}").format
# return msg(self.name, self.location, len(self.data), self.attributes)
#
# def __len__(self):
# return len(self.data)
#
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
# curdir = os.getcwd()
# try:
# if dirname is not None:
# os.chdir(dirname)
# yield
# finally:
# os.chdir(curdir)
. Output only the next line. | with chdir(test_files): |
Given the code snippet: <|code_start|>"""Test file for building the face_edge_connectivity"""
def test_build_face_edge_connectivity():
faces = [[0, 1, 2], [1, 2, 3]]
edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 1]]
nodes = [1, 2, 3, 4]
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from gridded.pyugrid import ugrid
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
# NODE_DT = np.float64 # datatype used for node coordinates.
# class UGrid(object):
# def __init__(self,
# nodes=None,
# node_lon=None,
# node_lat=None,
# faces=None,
# edges=None,
# boundaries=None,
# face_face_connectivity=None,
# face_edge_connectivity=None,
# edge_coordinates=None,
# face_coordinates=None,
# boundary_coordinates=None,
# data=None,
# mesh_name="mesh",
# ):
# def from_ncfile(klass, nc_url, mesh_name=None): # , load_data=False):
# def from_nc_dataset(klass, nc, mesh_name=None): # , load_data=False):
# def info(self):
# def check_consistent(self):
# def num_vertices(self):
# def nodes(self):
# def node_lon(self):
# def node_lat(self):
# def nodes(self, nodes_coords):
# def nodes(self):
# def faces(self):
# def faces(self, faces_indexes):
# def faces(self):
# def edges(self):
# def edges(self, edges_indexes):
# def edges(self):
# def boundaries(self):
# def boundaries(self, boundaries_indexes):
# def boundaries(self):
# def face_face_connectivity(self):
# def face_face_connectivity(self, face_face_connectivity):
# def face_face_connectivity(self):
# def face_edge_connectivity(self):
# def face_edge_connectivity(self, face_edge_connectivity):
# def face_edge_connectivity(self):
# def infer_location(self, data):
# def locate_nodes(self, points):
# def _build_kdtree(self):
# def _hash_of_pts(self, points):
# def _add_memo(self, points, item, D, _copy=False, _hash=None):
# def _get_memoed(self, points, D, _copy=False, _hash=None):
# def locate_faces(self, points, method='celltree', _copy=False, _memo=True, _hash=None):
# def build_celltree(self):
# def interpolation_alphas(self, points, indices=None, _copy=False, _memo=True, _hash=None):
# def interpolate_var_to_points(self,
# points,
# variable,
# location=None,
# fill_value=0,
# indices=None,
# alphas=None,
# slices=None,
# _copy=False,
# _memo=True,
# _hash=None):
# def build_face_face_connectivity(self):
# def get_lines(self):
# def build_edges(self):
# def build_boundaries(self):
# def build_face_edge_connectivity(self):
# def build_face_coordinates(self):
# def build_edge_coordinates(self):
# def build_boundary_coordinates(self):
# def save_as_netcdf(self, filename, format='netcdf4'):
# def save(self, filepath, format='netcdf4', variables={}):
# def _save_variables(self, nclocal, variables):
. Output only the next line. | grid = ugrid.UGrid( |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Testing of code to find nodes.
Currently only nearest neighbor.
"""
from __future__ import (absolute_import, division, print_function)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .utilities import twenty_one_triangles
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/tests/test_ugrid/utilities.py
# @pytest.fixture
# def twenty_one_triangles():
# """
# Returns a basic triangular grid: 21 triangles, a hole, and a tail.
#
# """
# nodes = [(5, 1),
# (10, 1),
# (3, 3),
# (7, 3),
# (9, 4),
# (12, 4),
# (5, 5),
# (3, 7),
# (5, 7),
# (7, 7),
# (9, 7),
# (11, 7),
# (5, 9),
# (8, 9),
# (11, 9),
# (9, 11),
# (11, 11),
# (7, 13),
# (9, 13),
# (7, 15), ]
#
# faces = [(0, 1, 3),
# (0, 6, 2),
# (0, 3, 6),
# (1, 4, 3),
# (1, 5, 4),
# (2, 6, 7),
# (6, 8, 7),
# (7, 8, 12),
# (6, 9, 8),
# (8, 9, 12),
# (9, 13, 12),
# (4, 5, 11),
# (4, 11, 10),
# (9, 10, 13),
# (10, 11, 14),
# (10, 14, 13),
# (13, 14, 15),
# (14, 16, 15),
# (15, 16, 18),
# (15, 18, 17),
# (17, 18, 19), ]
#
# # We may want to use this later to define just the outer boundary.
# boundaries = [(0, 1),
# (1, 5),
# (5, 11),
# (11, 14),
# (14, 16),
# (16, 18),
# (18, 19),
# (19, 17),
# (17, 15),
# (15, 13),
# (13, 12),
# (12, 7),
# (7, 2),
# (2, 0),
# (3, 4),
# (4, 10),
# (10, 9),
# (9, 6),
# (6, 3), ]
#
# grid = ugrid.UGrid(nodes=nodes, faces=faces, boundaries=boundaries)
# grid.build_edges()
# return grid
. Output only the next line. | def test_locate_node(twenty_one_triangles): |
Predict the next line for this snippet: <|code_start|>from __future__ import (absolute_import, division, print_function)
def test_point_in_tri():
test_datasets = [
{
'triangle': np.array([[0., 0.], [1., 0.], [0., 1.]]),
'points_inside': [np.array([0.1, 0.1]), np.array([0.3, 0.3])],
'points_outside': [np.array([5., 5.])],
},
]
for dataset in test_datasets:
for point in dataset['points_inside']:
<|code_end|>
with the help of current file imports:
import numpy as np
from gridded.pyugrid.util import point_in_tri
and context from other files:
# Path: gridded/pyugrid/util.py
# def point_in_tri(face_points, point, return_weights=False):
# """
# Calculates whether point is internal/external
# to element by comparing summed area of sub triangles with area of triangle
# element.
#
# NOTE: this seems like a pretty expensive way to do it
# -- compared to three side of line tests..
# """
# sub_tri_areas = np.zeros(3)
# sub_tri_areas[0] = _signed_area_tri(np.vstack((face_points[(0, 1), :],
# point)))
# sub_tri_areas[1] = _signed_area_tri(np.vstack((face_points[(1, 2), :],
# point)))
# sub_tri_areas[2] = _signed_area_tri(np.vstack((face_points[(0, 2), :],
# point)))
# tri_area = _signed_area_tri(face_points)
#
# if abs(np.abs(sub_tri_areas).sum() - tri_area) / tri_area <= epsilon:
# if return_weights:
# raise NotImplementedError
# # weights = sub_tri_areas/tri_area
# # weights[1] = max(0., min(1., weights[1]))
# # weights[2] = max(0., min(1., weights[2]))
# # if (weights[0]+weights[1]>1):
# # weights[2] = 0
# # weights[1] = 1-weights[0]
# # else:
# # weights[2] = 1-weights[0]-weights[1]
# #
# # return weights
# else:
# return True
# return False
, which may contain function names, class names, or code. Output only the next line. | assert point_in_tri(dataset['triangle'], point) |
Given snippet: <|code_start|>
def get_test_file_dir():
"""
returns the test file dir path
"""
test_file_dir = os.path.join(os.path.dirname(__file__), 'test_data')
return test_file_dir
def get_temp_test_file(filename):
"""
returns the path to a temporary test file.
If it exists, it will return it directly.
If not, it will attempt to download it.
If it can't download, it will return None
"""
print("getting temp test file")
filepath = os.path.join(os.path.dirname(__file__),
'temp_data',
filename)
if os.path.isfile(filepath):
print("already there")
return filepath
else:
# attempt to download it
print("trying to download")
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import contextlib
import urllib.request as urllib_request # for python 3
import urllib2 as urllib_request # for python 2
import pytest
from .get_remote_data import get_datafile
and context:
# Path: gridded/tests/get_remote_data.py
# def get_datafile(file_):
# """
# Function looks to see if file_ exists in local directory. If it exists,
# then it simply returns the 'file_' back as a string.
# If 'file_' does not exist in local filesystem, then it tries to download it
# from the gnome server:
#
# http://gnome.orr.noaa.gov/py_gnome_testdata
#
# If it successfully downloads the file, it puts it in the user specified
# path given in file_ and returns the 'file_' string.
#
# If file is not found or server is down, it rethrows the HTTPError raised
# by urllib2.urlopen
#
# :param file_: path to the file including filename
# :type file_: string
# :exception: raises urllib2.HTTPError if server is down or file not found
# on server
# :returns: returns the string 'file_' once it has been downloaded to
# user specified location
# """
#
# if os.path.exists(file_):
# return file_
# else:
#
# # download file, then return file_ path
#
# (path_, fname) = os.path.split(file_)
# if path_ == '':
# path_ = '.' # relative to current path
#
# try:
# resp = urllib_request.urlopen(urljoin(DATA_SERVER, fname))
# except urllib_request.HTTPError as ex:
# ex.msg = ("{0}. '{1}' not found on server or server is down"
# .format(ex.msg, fname))
# raise ex
#
# # # progress bar
# # widgets = [fname + ': ',
# # pb.Percentage(),
# # ' ',
# # pb.Bar(),
# # ' ',
# # pb.ETA(),
# # ' ',
# # pb.FileTransferSpeed(),
# # ]
#
# # pbar = pb.ProgressBar(widgets=widgets,
# # maxval=int(resp.info().getheader('Content-Length'))
# # ).start()
#
# if not os.path.exists(path_):
# os.makedirs(path_)
#
# sz_read = 0
# with open(file_, 'wb') as fh:
# # while sz_read < resp.info().getheader('Content-Length')
# # goes into infinite recursion so break loop for len(data) == 0
# while True:
# data = resp.read(CHUNKSIZE)
#
# if len(data) == 0:
# break
# else:
# fh.write(data)
# sz_read += len(data)
#
# # if sz_read >= CHUNKSIZE:
# # pbar.update(CHUNKSIZE)
#
# # pbar.finish()
# return file_
which might include code, classes, or functions. Output only the next line. | get_datafile(filepath) |
Given snippet: <|code_start|>Assorted utilities useful for the tests.
"""
from __future__ import (absolute_import, division, print_function)
@pytest.fixture
def two_triangles():
"""
Returns a simple triangular grid: 4 nodes, two triangles, five edges.
"""
nodes = [(0.1, 0.1),
(2.1, 0.1),
(1.1, 2.1),
(3.1, 2.1)]
faces = [(0, 1, 2),
(1, 3, 2), ]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import contextlib
import pytest
from gridded.pyugrid import ugrid
and context:
# Path: gridded/pyugrid/ugrid.py
# IND_DT = np.int32
# NODE_DT = np.float64 # datatype used for node coordinates.
# class UGrid(object):
# def __init__(self,
# nodes=None,
# node_lon=None,
# node_lat=None,
# faces=None,
# edges=None,
# boundaries=None,
# face_face_connectivity=None,
# face_edge_connectivity=None,
# edge_coordinates=None,
# face_coordinates=None,
# boundary_coordinates=None,
# data=None,
# mesh_name="mesh",
# ):
# def from_ncfile(klass, nc_url, mesh_name=None): # , load_data=False):
# def from_nc_dataset(klass, nc, mesh_name=None): # , load_data=False):
# def info(self):
# def check_consistent(self):
# def num_vertices(self):
# def nodes(self):
# def node_lon(self):
# def node_lat(self):
# def nodes(self, nodes_coords):
# def nodes(self):
# def faces(self):
# def faces(self, faces_indexes):
# def faces(self):
# def edges(self):
# def edges(self, edges_indexes):
# def edges(self):
# def boundaries(self):
# def boundaries(self, boundaries_indexes):
# def boundaries(self):
# def face_face_connectivity(self):
# def face_face_connectivity(self, face_face_connectivity):
# def face_face_connectivity(self):
# def face_edge_connectivity(self):
# def face_edge_connectivity(self, face_edge_connectivity):
# def face_edge_connectivity(self):
# def infer_location(self, data):
# def locate_nodes(self, points):
# def _build_kdtree(self):
# def _hash_of_pts(self, points):
# def _add_memo(self, points, item, D, _copy=False, _hash=None):
# def _get_memoed(self, points, D, _copy=False, _hash=None):
# def locate_faces(self, points, method='celltree', _copy=False, _memo=True, _hash=None):
# def build_celltree(self):
# def interpolation_alphas(self, points, indices=None, _copy=False, _memo=True, _hash=None):
# def interpolate_var_to_points(self,
# points,
# variable,
# location=None,
# fill_value=0,
# indices=None,
# alphas=None,
# slices=None,
# _copy=False,
# _memo=True,
# _hash=None):
# def build_face_face_connectivity(self):
# def get_lines(self):
# def build_edges(self):
# def build_boundaries(self):
# def build_face_edge_connectivity(self):
# def build_face_coordinates(self):
# def build_edge_coordinates(self):
# def build_boundary_coordinates(self):
# def save_as_netcdf(self, filename, format='netcdf4'):
# def save(self, filepath, format='netcdf4', variables={}):
# def _save_variables(self, nclocal, variables):
which might include code, classes, or functions. Output only the next line. | return ugrid.UGrid(nodes=nodes, faces=faces, edges=edges) |
Predict the next line for this snippet: <|code_start|> Use regex expressions to break apart an
attribute string containing padding types
for each variable with a cf_role of
'grid_topology'.
Padding information is returned within a named tuple
for each node dimension of an edge, face, or vertical
dimension. The named tuples have the following attributes:
mesh_topology_var, dim_name, dim_var, and padding.
Padding information is returned as a list
of these named tuples.
:param str padding_str: string containing padding types from
a netCDF attribute.
:return: named tuples with padding information.
:rtype: list.
"""
p = re.compile('([a-zA-Z0-9_]+:) ([a-zA-Z0-9_]+) (\(padding: [a-zA-Z]+\))')
padding_matches = p.findall(padding_str)
padding_type_list = []
for padding_match in padding_matches:
raw_dim, raw_sub_dim, raw_padding_var = padding_match
dim = raw_dim.split(':')[0]
sub_dim = raw_sub_dim
# Remove parentheses. (That is why regular expressions are bad!
# You need a commend to explain what is going on!!)
cleaned_padding_var = re.sub('[\(\)]', '', raw_padding_var)
# Get the padding value and remove spaces.
padding_type = cleaned_padding_var.split(':')[1].strip()
<|code_end|>
with the help of current file imports:
import re
from gridded.pysgrid.lookup import X_COORDINATES, Y_COORDINATES
from gridded.pysgrid.utils import GridPadding
and context from other files:
# Path: gridded/pysgrid/utils.py
# def pair_arrays(x_array, y_array):
# def check_element_equal(lst):
# def does_intersection_exist(a, b):
# def determine_variable_slicing(sgrid_obj, nc_variable, method='center'):
# def infer_avg_axes(sgrid_obj, nc_var_obj):
# def infer_variable_location(sgrid, variable):
# def calculate_bearing(lon_lat_1, lon_lat_2):
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# def points_in_polys(points, polys, polyy=None):
, which may contain function names, class names, or code. Output only the next line. | grid_padding = GridPadding(mesh_topology_var=mesh_topology_var,
|
Given the code snippet: <|code_start|>
@pytest.fixture
def check_element():
"""
FIXME: These tests only check for a True return and not for correctness.
"""
a = [7, 7, 7, 7]
b = [7, 8, 9, 10]
return a, b
def test_list_with_identical_elements(check_element):
a, b = check_element
result = check_element_equal(a)
assert result
def test_list_with_different_elements(check_element):
a, b = check_element
result = check_element_equal(b)
assert result is False
def test_bearing_calculation():
points = np.array([(-93.51105439, 11.88846735),
(-93.46607342, 11.90917952)])
point_1 = points[:-1, :]
point_2 = points[1:, :]
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from gridded.pysgrid.utils import (calculate_bearing,
calculate_angle_from_true_east,
check_element_equal,
does_intersection_exist,
pair_arrays,
)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/utils.py
# def calculate_bearing(lon_lat_1, lon_lat_2):
# """
# return bearing from true north in degrees
#
# """
# lon_lat_1_radians = lon_lat_1 * np.pi / 180
# lon_lat_2_radians = lon_lat_2 * np.pi / 180
# lon_1 = lon_lat_1_radians[..., 0]
# lat_1 = lon_lat_1_radians[..., 1]
# lon_2 = lon_lat_2_radians[..., 0]
# lat_2 = lon_lat_2_radians[..., 1]
# x1 = np.sin(lon_2 - lon_1) * np.cos(lat_2)
# x2 = np.cos(lat_1) * np.sin(lat_2) - np.sin(lat_1) * np.cos(lat_2) * np.cos(lon_2 - lon_1) # noqa
# bearing_radians = np.arctan2(x1, x2)
# bearing_degrees = bearing_radians * 180 / np.pi
# return (bearing_degrees + 360) % 360
#
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# """
# Return the angle from true east in radians.
#
# """
# bearing = calculate_bearing(lon_lat_1, lon_lat_2)
# bearing_from_true_east = 90 - bearing
# bearing_from_true_east_radians = bearing_from_true_east * np.pi / 180
# # not sure if this is the most appropriate thing to do for the last grid
# # cell
# angles = np.append(bearing_from_true_east_radians,
# bearing_from_true_east_radians[..., -1:],
# axis=-1)
# return angles
#
# def check_element_equal(lst):
# """
# Check that all elements in an
# iterable are the same.
#
# :params lst: iterable object to be checked
# :type lst: np.array, list, tuple
# :return: result of element equality check
# :rtype: bool
#
# """
# return lst[1:] == lst[:-1]
#
# def does_intersection_exist(a, b):
# set_a = set(a)
# try:
# set_b = set(b)
# except TypeError:
# intersect_exists = False
# else:
# intersect = set_a.intersection(set_b)
# if len(intersect) > 0:
# intersect_exists = True
# else:
# intersect_exists = False
# return intersect_exists
#
# def pair_arrays(x_array, y_array):
# """
# Given two arrays to equal dimensions,
# pair their values element-wise.
#
# For example given arrays [[1, 2], [3, 4]]
# and [[-1, -2], [-3, -4]], this function will
# return [[[1, -1], [2, -2]], [[3, -3], [4, -4]]].
#
# :param np.array x_array: a numpy array containing "x" coordinates
# :param np.array y_array: a numpy array containing "y" coordinates
# :return: array containing (x, y) arrays
# :rtype: np.array
#
# """
# x_shape = x_array.shape
# paired_array_shape = x_shape + (2,)
# paired_array = np.empty(paired_array_shape, dtype=np.float64)
# paired_array[..., 0] = x_array[:]
# paired_array[..., 1] = y_array[:]
# return paired_array
. Output only the next line. | result = calculate_bearing(point_1, point_2) |
Next line prediction: <|code_start|>def test_bearing_calculation():
points = np.array([(-93.51105439, 11.88846735),
(-93.46607342, 11.90917952)])
point_1 = points[:-1, :]
point_2 = points[1:, :]
result = calculate_bearing(point_1, point_2)
expected = 64.7947
np.testing.assert_almost_equal(result, expected, decimal=3)
def test_angle_from_true_east_calculation():
vertical_1 = np.array([[-122.41, 37.78],
[-122.33, 37.84],
[-122.22, 37.95]])
vertical_2 = np.array([[-90.07, 29.95],
[-89.97, 29.84],
[-89.91, 29.76]])
vertical_3 = np.array([[-89.40, 43.07],
[-89.49, 42.93],
[-89.35, 42.84]])
vertical_4 = np.array([[-122.41, 37.78],
[-122.53, 37.84],
[-122.67, 37.95]])
centers = np.array((vertical_1,
vertical_2,
vertical_3,
vertical_4))
bearing_start_points = centers[:, :-1, :]
bearing_end_points = centers[:, 1:, :]
<|code_end|>
. Use current file imports:
(import pytest
import numpy as np
from gridded.pysgrid.utils import (calculate_bearing,
calculate_angle_from_true_east,
check_element_equal,
does_intersection_exist,
pair_arrays,
))
and context including class names, function names, or small code snippets from other files:
# Path: gridded/pysgrid/utils.py
# def calculate_bearing(lon_lat_1, lon_lat_2):
# """
# return bearing from true north in degrees
#
# """
# lon_lat_1_radians = lon_lat_1 * np.pi / 180
# lon_lat_2_radians = lon_lat_2 * np.pi / 180
# lon_1 = lon_lat_1_radians[..., 0]
# lat_1 = lon_lat_1_radians[..., 1]
# lon_2 = lon_lat_2_radians[..., 0]
# lat_2 = lon_lat_2_radians[..., 1]
# x1 = np.sin(lon_2 - lon_1) * np.cos(lat_2)
# x2 = np.cos(lat_1) * np.sin(lat_2) - np.sin(lat_1) * np.cos(lat_2) * np.cos(lon_2 - lon_1) # noqa
# bearing_radians = np.arctan2(x1, x2)
# bearing_degrees = bearing_radians * 180 / np.pi
# return (bearing_degrees + 360) % 360
#
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# """
# Return the angle from true east in radians.
#
# """
# bearing = calculate_bearing(lon_lat_1, lon_lat_2)
# bearing_from_true_east = 90 - bearing
# bearing_from_true_east_radians = bearing_from_true_east * np.pi / 180
# # not sure if this is the most appropriate thing to do for the last grid
# # cell
# angles = np.append(bearing_from_true_east_radians,
# bearing_from_true_east_radians[..., -1:],
# axis=-1)
# return angles
#
# def check_element_equal(lst):
# """
# Check that all elements in an
# iterable are the same.
#
# :params lst: iterable object to be checked
# :type lst: np.array, list, tuple
# :return: result of element equality check
# :rtype: bool
#
# """
# return lst[1:] == lst[:-1]
#
# def does_intersection_exist(a, b):
# set_a = set(a)
# try:
# set_b = set(b)
# except TypeError:
# intersect_exists = False
# else:
# intersect = set_a.intersection(set_b)
# if len(intersect) > 0:
# intersect_exists = True
# else:
# intersect_exists = False
# return intersect_exists
#
# def pair_arrays(x_array, y_array):
# """
# Given two arrays to equal dimensions,
# pair their values element-wise.
#
# For example given arrays [[1, 2], [3, 4]]
# and [[-1, -2], [-3, -4]], this function will
# return [[[1, -1], [2, -2]], [[3, -3], [4, -4]]].
#
# :param np.array x_array: a numpy array containing "x" coordinates
# :param np.array y_array: a numpy array containing "y" coordinates
# :return: array containing (x, y) arrays
# :rtype: np.array
#
# """
# x_shape = x_array.shape
# paired_array_shape = x_shape + (2,)
# paired_array = np.empty(paired_array_shape, dtype=np.float64)
# paired_array[..., 0] = x_array[:]
# paired_array[..., 1] = y_array[:]
# return paired_array
. Output only the next line. | angle_from_true_east = calculate_angle_from_true_east(bearing_start_points, bearing_end_points) # noqa |
Given the code snippet: <|code_start|> a, b, c = intersection_data
result = does_intersection_exist(a, c)
assert result is False
def test_pair_arrays():
a1, a2, a3 = (1, 2), (3, 4), (5, 6)
b1, b2, b3 = (10, 20), (30, 40), (50, 60)
a = np.array([a1, a2, a3])
b = np.array([b1, b2, b3])
result = pair_arrays(a, b)
expected = np.array([[(1, 10), (2, 20)],
[(3, 30), (4, 40)],
[(5, 50), (6, 60)]])
np.testing.assert_almost_equal(result, expected, decimal=3)
@pytest.fixture
def check_element():
"""
FIXME: These tests only check for a True return and not for correctness.
"""
a = [7, 7, 7, 7]
b = [7, 8, 9, 10]
return a, b
def test_list_with_identical_elements(check_element):
a, b = check_element
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from gridded.pysgrid.utils import (calculate_bearing,
calculate_angle_from_true_east,
check_element_equal,
does_intersection_exist,
pair_arrays,
)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/utils.py
# def calculate_bearing(lon_lat_1, lon_lat_2):
# """
# return bearing from true north in degrees
#
# """
# lon_lat_1_radians = lon_lat_1 * np.pi / 180
# lon_lat_2_radians = lon_lat_2 * np.pi / 180
# lon_1 = lon_lat_1_radians[..., 0]
# lat_1 = lon_lat_1_radians[..., 1]
# lon_2 = lon_lat_2_radians[..., 0]
# lat_2 = lon_lat_2_radians[..., 1]
# x1 = np.sin(lon_2 - lon_1) * np.cos(lat_2)
# x2 = np.cos(lat_1) * np.sin(lat_2) - np.sin(lat_1) * np.cos(lat_2) * np.cos(lon_2 - lon_1) # noqa
# bearing_radians = np.arctan2(x1, x2)
# bearing_degrees = bearing_radians * 180 / np.pi
# return (bearing_degrees + 360) % 360
#
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# """
# Return the angle from true east in radians.
#
# """
# bearing = calculate_bearing(lon_lat_1, lon_lat_2)
# bearing_from_true_east = 90 - bearing
# bearing_from_true_east_radians = bearing_from_true_east * np.pi / 180
# # not sure if this is the most appropriate thing to do for the last grid
# # cell
# angles = np.append(bearing_from_true_east_radians,
# bearing_from_true_east_radians[..., -1:],
# axis=-1)
# return angles
#
# def check_element_equal(lst):
# """
# Check that all elements in an
# iterable are the same.
#
# :params lst: iterable object to be checked
# :type lst: np.array, list, tuple
# :return: result of element equality check
# :rtype: bool
#
# """
# return lst[1:] == lst[:-1]
#
# def does_intersection_exist(a, b):
# set_a = set(a)
# try:
# set_b = set(b)
# except TypeError:
# intersect_exists = False
# else:
# intersect = set_a.intersection(set_b)
# if len(intersect) > 0:
# intersect_exists = True
# else:
# intersect_exists = False
# return intersect_exists
#
# def pair_arrays(x_array, y_array):
# """
# Given two arrays to equal dimensions,
# pair their values element-wise.
#
# For example given arrays [[1, 2], [3, 4]]
# and [[-1, -2], [-3, -4]], this function will
# return [[[1, -1], [2, -2]], [[3, -3], [4, -4]]].
#
# :param np.array x_array: a numpy array containing "x" coordinates
# :param np.array y_array: a numpy array containing "y" coordinates
# :return: array containing (x, y) arrays
# :rtype: np.array
#
# """
# x_shape = x_array.shape
# paired_array_shape = x_shape + (2,)
# paired_array = np.empty(paired_array_shape, dtype=np.float64)
# paired_array[..., 0] = x_array[:]
# paired_array[..., 1] = y_array[:]
# return paired_array
. Output only the next line. | result = check_element_equal(a) |
Given the code snippet: <|code_start|>"""
Created on Mar 23, 2015
@author: ayan
"""
from __future__ import (absolute_import, division, print_function)
@pytest.fixture
def intersection_data():
a = (718, 903, 1029, 1701)
b = (718, 828)
c = (15, 20)
return a, b, c
def test_intersect_exists(intersection_data):
a, b, c = intersection_data
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from gridded.pysgrid.utils import (calculate_bearing,
calculate_angle_from_true_east,
check_element_equal,
does_intersection_exist,
pair_arrays,
)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/utils.py
# def calculate_bearing(lon_lat_1, lon_lat_2):
# """
# return bearing from true north in degrees
#
# """
# lon_lat_1_radians = lon_lat_1 * np.pi / 180
# lon_lat_2_radians = lon_lat_2 * np.pi / 180
# lon_1 = lon_lat_1_radians[..., 0]
# lat_1 = lon_lat_1_radians[..., 1]
# lon_2 = lon_lat_2_radians[..., 0]
# lat_2 = lon_lat_2_radians[..., 1]
# x1 = np.sin(lon_2 - lon_1) * np.cos(lat_2)
# x2 = np.cos(lat_1) * np.sin(lat_2) - np.sin(lat_1) * np.cos(lat_2) * np.cos(lon_2 - lon_1) # noqa
# bearing_radians = np.arctan2(x1, x2)
# bearing_degrees = bearing_radians * 180 / np.pi
# return (bearing_degrees + 360) % 360
#
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# """
# Return the angle from true east in radians.
#
# """
# bearing = calculate_bearing(lon_lat_1, lon_lat_2)
# bearing_from_true_east = 90 - bearing
# bearing_from_true_east_radians = bearing_from_true_east * np.pi / 180
# # not sure if this is the most appropriate thing to do for the last grid
# # cell
# angles = np.append(bearing_from_true_east_radians,
# bearing_from_true_east_radians[..., -1:],
# axis=-1)
# return angles
#
# def check_element_equal(lst):
# """
# Check that all elements in an
# iterable are the same.
#
# :params lst: iterable object to be checked
# :type lst: np.array, list, tuple
# :return: result of element equality check
# :rtype: bool
#
# """
# return lst[1:] == lst[:-1]
#
# def does_intersection_exist(a, b):
# set_a = set(a)
# try:
# set_b = set(b)
# except TypeError:
# intersect_exists = False
# else:
# intersect = set_a.intersection(set_b)
# if len(intersect) > 0:
# intersect_exists = True
# else:
# intersect_exists = False
# return intersect_exists
#
# def pair_arrays(x_array, y_array):
# """
# Given two arrays to equal dimensions,
# pair their values element-wise.
#
# For example given arrays [[1, 2], [3, 4]]
# and [[-1, -2], [-3, -4]], this function will
# return [[[1, -1], [2, -2]], [[3, -3], [4, -4]]].
#
# :param np.array x_array: a numpy array containing "x" coordinates
# :param np.array y_array: a numpy array containing "y" coordinates
# :return: array containing (x, y) arrays
# :rtype: np.array
#
# """
# x_shape = x_array.shape
# paired_array_shape = x_shape + (2,)
# paired_array = np.empty(paired_array_shape, dtype=np.float64)
# paired_array[..., 0] = x_array[:]
# paired_array[..., 1] = y_array[:]
# return paired_array
. Output only the next line. | result = does_intersection_exist(a, b) |
Given the code snippet: <|code_start|>
@pytest.fixture
def intersection_data():
a = (718, 903, 1029, 1701)
b = (718, 828)
c = (15, 20)
return a, b, c
def test_intersect_exists(intersection_data):
a, b, c = intersection_data
result = does_intersection_exist(a, b)
assert result
def test_intersect_does_not_exist(intersection_data):
a, b, c = intersection_data
result = does_intersection_exist(a, c)
assert result is False
def test_pair_arrays():
a1, a2, a3 = (1, 2), (3, 4), (5, 6)
b1, b2, b3 = (10, 20), (30, 40), (50, 60)
a = np.array([a1, a2, a3])
b = np.array([b1, b2, b3])
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import numpy as np
from gridded.pysgrid.utils import (calculate_bearing,
calculate_angle_from_true_east,
check_element_equal,
does_intersection_exist,
pair_arrays,
)
and context (functions, classes, or occasionally code) from other files:
# Path: gridded/pysgrid/utils.py
# def calculate_bearing(lon_lat_1, lon_lat_2):
# """
# return bearing from true north in degrees
#
# """
# lon_lat_1_radians = lon_lat_1 * np.pi / 180
# lon_lat_2_radians = lon_lat_2 * np.pi / 180
# lon_1 = lon_lat_1_radians[..., 0]
# lat_1 = lon_lat_1_radians[..., 1]
# lon_2 = lon_lat_2_radians[..., 0]
# lat_2 = lon_lat_2_radians[..., 1]
# x1 = np.sin(lon_2 - lon_1) * np.cos(lat_2)
# x2 = np.cos(lat_1) * np.sin(lat_2) - np.sin(lat_1) * np.cos(lat_2) * np.cos(lon_2 - lon_1) # noqa
# bearing_radians = np.arctan2(x1, x2)
# bearing_degrees = bearing_radians * 180 / np.pi
# return (bearing_degrees + 360) % 360
#
# def calculate_angle_from_true_east(lon_lat_1, lon_lat_2):
# """
# Return the angle from true east in radians.
#
# """
# bearing = calculate_bearing(lon_lat_1, lon_lat_2)
# bearing_from_true_east = 90 - bearing
# bearing_from_true_east_radians = bearing_from_true_east * np.pi / 180
# # not sure if this is the most appropriate thing to do for the last grid
# # cell
# angles = np.append(bearing_from_true_east_radians,
# bearing_from_true_east_radians[..., -1:],
# axis=-1)
# return angles
#
# def check_element_equal(lst):
# """
# Check that all elements in an
# iterable are the same.
#
# :params lst: iterable object to be checked
# :type lst: np.array, list, tuple
# :return: result of element equality check
# :rtype: bool
#
# """
# return lst[1:] == lst[:-1]
#
# def does_intersection_exist(a, b):
# set_a = set(a)
# try:
# set_b = set(b)
# except TypeError:
# intersect_exists = False
# else:
# intersect = set_a.intersection(set_b)
# if len(intersect) > 0:
# intersect_exists = True
# else:
# intersect_exists = False
# return intersect_exists
#
# def pair_arrays(x_array, y_array):
# """
# Given two arrays to equal dimensions,
# pair their values element-wise.
#
# For example given arrays [[1, 2], [3, 4]]
# and [[-1, -2], [-3, -4]], this function will
# return [[[1, -1], [2, -2]], [[3, -3], [4, -4]]].
#
# :param np.array x_array: a numpy array containing "x" coordinates
# :param np.array y_array: a numpy array containing "y" coordinates
# :return: array containing (x, y) arrays
# :rtype: np.array
#
# """
# x_shape = x_array.shape
# paired_array_shape = x_shape + (2,)
# paired_array = np.empty(paired_array_shape, dtype=np.float64)
# paired_array[..., 0] = x_array[:]
# paired_array[..., 1] = y_array[:]
# return paired_array
. Output only the next line. | result = pair_arrays(a, b) |
Given the code snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
"libraryReference","reads","overrepresentedSequences","QCStatus")
search_fields = ("sampleReference","sampleName","libraryReference")
class runAdmin(admin.ModelAdmin):
fields = ("runName","date","length","notes")
list_display = ("runName","date","length")
search_fields = ("date","runName")
class projectAdmin(admin.ModelAdmin):
fields = ("project","projectPROID","notes")
list_display = ("project","projectPROID")
list_display = ("project","projectPROID")
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from almostSignificant.models import Sample, Project, Run
and context (functions, classes, or occasionally code) from other files:
# Path: almostSignificant/models.py
# class Sample(models.Model):
# """Sample Model for the GSU statistics viewer.
#
# Description of the sample and the results of its QC analysis
#
# """
# run = models.ForeignKey('Run')
# project = models.ForeignKey('Project')
# software = models.ManyToManyField('Software')
# lane = models.ForeignKey('Lane')
# sampleReference = models.CharField(max_length=255)
# sampleName = models.CharField(max_length=255,blank=True)
# readNumber = models.PositiveSmallIntegerField()
# reads = models.PositiveIntegerField()
# sequenceLength = models.TextField()
# sampleDescription = models.TextField(blank=True)
# libraryReference = models.CharField(max_length=255)
# barcode = models.CharField(max_length=17)
# species = models.CharField(max_length=255,blank=True)
#
# method = models.CharField(max_length=100)
# fastQLocation = models.TextField()
# md5hash = models.CharField(max_length=255,blank=True)
# QCStatus = models.CharField(max_length=10,blank=True)
# insertLength = models.PositiveIntegerField(null=True)
# contaminantsImage = models.TextField()
# fastQCSummary = models.TextField()
# filteredSequences = models.PositiveIntegerField(default=0,null=True)
# Q30Length = models.PositiveSmallIntegerField(null=True)
# percentGC = models.PositiveSmallIntegerField(null=True)
#
# sequenceQuality = models.CharField(max_length=4,blank=True)
# sequenceQualityScores = models.CharField(max_length=4,blank=True)
# sequenceContent = models.CharField(max_length=4,blank=True)
# GCContent = models.CharField(max_length=4,blank=True)
# baseNContent = models.CharField(max_length=4,blank=True)
# sequenceLengthDistribution = models.CharField(max_length=4,blank=True)
# sequenceDuplicationLevels = models.CharField(max_length=4,blank=True)
# overrepresentedSequences = models.CharField(max_length=4,blank=True)
# kmerContent = models.CharField(max_length=4,blank=True)
# # adapterContent = models.CharField(max_length=4,blank=True)
# # tileSequenceQuality = models.CharField(max_length=4,blank=True)
#
# trimmed = models.BooleanField(default=False,blank=True)
#
# def __unicode__(self): # Python 3: def __str__(self):
# return self.sampleReference
#
# class Project(models.Model):
# """Basic details of a project."""
# project = models.CharField(max_length=255)
# projectMISOID = models.PositiveSmallIntegerField(null=True)
# projectPROID = models.CharField(max_length=20,null=True)
# owner = models.CharField(max_length=255,blank=True)
# description = models.TextField(blank=True)
# notes = models.TextField(blank=True)
#
# def __unicode__(self):
# return self.project
#
# class Run(models.Model):
# """Run data model for the GSU statistics viewer.
#
# Contains the description of the run.
#
# """
# runName = models.CharField(max_length=50, verbose_name="RunName")
# #runID = models.CharField(max_length=255)
# machine = models.CharField(max_length=20)
# machineType = models.CharField(max_length=10)
# date = models.DateField()
# alias = models.TextField(blank=True)
# length = models.PositiveSmallIntegerField()
# fcPosition = models.CharField(max_length=1)
# notes = models.TextField(blank=True)
#
# pairedSingle = models.TextField(max_length=6)
# def __unicode__(self):
# return self.runName
. Output only the next line. | admin.site.register(Sample, sampleAdmin) |
Given snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
"libraryReference","reads","overrepresentedSequences","QCStatus")
search_fields = ("sampleReference","sampleName","libraryReference")
class runAdmin(admin.ModelAdmin):
fields = ("runName","date","length","notes")
list_display = ("runName","date","length")
search_fields = ("date","runName")
class projectAdmin(admin.ModelAdmin):
fields = ("project","projectPROID","notes")
list_display = ("project","projectPROID")
list_display = ("project","projectPROID")
admin.site.register(Sample, sampleAdmin)
admin.site.register(Run, runAdmin)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from almostSignificant.models import Sample, Project, Run
and context:
# Path: almostSignificant/models.py
# class Sample(models.Model):
# """Sample Model for the GSU statistics viewer.
#
# Description of the sample and the results of its QC analysis
#
# """
# run = models.ForeignKey('Run')
# project = models.ForeignKey('Project')
# software = models.ManyToManyField('Software')
# lane = models.ForeignKey('Lane')
# sampleReference = models.CharField(max_length=255)
# sampleName = models.CharField(max_length=255,blank=True)
# readNumber = models.PositiveSmallIntegerField()
# reads = models.PositiveIntegerField()
# sequenceLength = models.TextField()
# sampleDescription = models.TextField(blank=True)
# libraryReference = models.CharField(max_length=255)
# barcode = models.CharField(max_length=17)
# species = models.CharField(max_length=255,blank=True)
#
# method = models.CharField(max_length=100)
# fastQLocation = models.TextField()
# md5hash = models.CharField(max_length=255,blank=True)
# QCStatus = models.CharField(max_length=10,blank=True)
# insertLength = models.PositiveIntegerField(null=True)
# contaminantsImage = models.TextField()
# fastQCSummary = models.TextField()
# filteredSequences = models.PositiveIntegerField(default=0,null=True)
# Q30Length = models.PositiveSmallIntegerField(null=True)
# percentGC = models.PositiveSmallIntegerField(null=True)
#
# sequenceQuality = models.CharField(max_length=4,blank=True)
# sequenceQualityScores = models.CharField(max_length=4,blank=True)
# sequenceContent = models.CharField(max_length=4,blank=True)
# GCContent = models.CharField(max_length=4,blank=True)
# baseNContent = models.CharField(max_length=4,blank=True)
# sequenceLengthDistribution = models.CharField(max_length=4,blank=True)
# sequenceDuplicationLevels = models.CharField(max_length=4,blank=True)
# overrepresentedSequences = models.CharField(max_length=4,blank=True)
# kmerContent = models.CharField(max_length=4,blank=True)
# # adapterContent = models.CharField(max_length=4,blank=True)
# # tileSequenceQuality = models.CharField(max_length=4,blank=True)
#
# trimmed = models.BooleanField(default=False,blank=True)
#
# def __unicode__(self): # Python 3: def __str__(self):
# return self.sampleReference
#
# class Project(models.Model):
# """Basic details of a project."""
# project = models.CharField(max_length=255)
# projectMISOID = models.PositiveSmallIntegerField(null=True)
# projectPROID = models.CharField(max_length=20,null=True)
# owner = models.CharField(max_length=255,blank=True)
# description = models.TextField(blank=True)
# notes = models.TextField(blank=True)
#
# def __unicode__(self):
# return self.project
#
# class Run(models.Model):
# """Run data model for the GSU statistics viewer.
#
# Contains the description of the run.
#
# """
# runName = models.CharField(max_length=50, verbose_name="RunName")
# #runID = models.CharField(max_length=255)
# machine = models.CharField(max_length=20)
# machineType = models.CharField(max_length=10)
# date = models.DateField()
# alias = models.TextField(blank=True)
# length = models.PositiveSmallIntegerField()
# fcPosition = models.CharField(max_length=1)
# notes = models.TextField(blank=True)
#
# pairedSingle = models.TextField(max_length=6)
# def __unicode__(self):
# return self.runName
which might include code, classes, or functions. Output only the next line. | admin.site.register(Project, projectAdmin) |
Continue the code snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
"libraryReference","reads","overrepresentedSequences","QCStatus")
search_fields = ("sampleReference","sampleName","libraryReference")
class runAdmin(admin.ModelAdmin):
fields = ("runName","date","length","notes")
list_display = ("runName","date","length")
search_fields = ("date","runName")
class projectAdmin(admin.ModelAdmin):
fields = ("project","projectPROID","notes")
list_display = ("project","projectPROID")
list_display = ("project","projectPROID")
admin.site.register(Sample, sampleAdmin)
<|code_end|>
. Use current file imports:
from django.contrib import admin
from almostSignificant.models import Sample, Project, Run
and context (classes, functions, or code) from other files:
# Path: almostSignificant/models.py
# class Sample(models.Model):
# """Sample Model for the GSU statistics viewer.
#
# Description of the sample and the results of its QC analysis
#
# """
# run = models.ForeignKey('Run')
# project = models.ForeignKey('Project')
# software = models.ManyToManyField('Software')
# lane = models.ForeignKey('Lane')
# sampleReference = models.CharField(max_length=255)
# sampleName = models.CharField(max_length=255,blank=True)
# readNumber = models.PositiveSmallIntegerField()
# reads = models.PositiveIntegerField()
# sequenceLength = models.TextField()
# sampleDescription = models.TextField(blank=True)
# libraryReference = models.CharField(max_length=255)
# barcode = models.CharField(max_length=17)
# species = models.CharField(max_length=255,blank=True)
#
# method = models.CharField(max_length=100)
# fastQLocation = models.TextField()
# md5hash = models.CharField(max_length=255,blank=True)
# QCStatus = models.CharField(max_length=10,blank=True)
# insertLength = models.PositiveIntegerField(null=True)
# contaminantsImage = models.TextField()
# fastQCSummary = models.TextField()
# filteredSequences = models.PositiveIntegerField(default=0,null=True)
# Q30Length = models.PositiveSmallIntegerField(null=True)
# percentGC = models.PositiveSmallIntegerField(null=True)
#
# sequenceQuality = models.CharField(max_length=4,blank=True)
# sequenceQualityScores = models.CharField(max_length=4,blank=True)
# sequenceContent = models.CharField(max_length=4,blank=True)
# GCContent = models.CharField(max_length=4,blank=True)
# baseNContent = models.CharField(max_length=4,blank=True)
# sequenceLengthDistribution = models.CharField(max_length=4,blank=True)
# sequenceDuplicationLevels = models.CharField(max_length=4,blank=True)
# overrepresentedSequences = models.CharField(max_length=4,blank=True)
# kmerContent = models.CharField(max_length=4,blank=True)
# # adapterContent = models.CharField(max_length=4,blank=True)
# # tileSequenceQuality = models.CharField(max_length=4,blank=True)
#
# trimmed = models.BooleanField(default=False,blank=True)
#
# def __unicode__(self): # Python 3: def __str__(self):
# return self.sampleReference
#
# class Project(models.Model):
# """Basic details of a project."""
# project = models.CharField(max_length=255)
# projectMISOID = models.PositiveSmallIntegerField(null=True)
# projectPROID = models.CharField(max_length=20,null=True)
# owner = models.CharField(max_length=255,blank=True)
# description = models.TextField(blank=True)
# notes = models.TextField(blank=True)
#
# def __unicode__(self):
# return self.project
#
# class Run(models.Model):
# """Run data model for the GSU statistics viewer.
#
# Contains the description of the run.
#
# """
# runName = models.CharField(max_length=50, verbose_name="RunName")
# #runID = models.CharField(max_length=255)
# machine = models.CharField(max_length=20)
# machineType = models.CharField(max_length=10)
# date = models.DateField()
# alias = models.TextField(blank=True)
# length = models.PositiveSmallIntegerField()
# fcPosition = models.CharField(max_length=1)
# notes = models.TextField(blank=True)
#
# pairedSingle = models.TextField(max_length=6)
# def __unicode__(self):
# return self.runName
. Output only the next line. | admin.site.register(Run, runAdmin) |
Using the snippet: <|code_start|>
logger = logging.getLogger('website')
class Communicator(object):
"""
The Communicator with the backend api server.
"""
client = None
def __init__(self, cookies={}):
self.client = requests.session()
for name, value in cookies.items():
self.client.cookies[name] = value
def login(self, data):
"""
Return cookies.
"""
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
import requests
from website.utils import (get_api_server_url, get_url_of_monitor_iframe)
and context (class names, function names, or code) available:
# Path: website/utils.py
# def get_api_server_url(path):
# """
# Return the url for api server.
# """
# return "http://" + settings.API_SERVER + path
#
# def get_url_of_monitor_iframe(type, namespace, pod_name):
# """
# Get the url of monitor iframe in user dashboard.
# """
# if type == "memory":
# type_id = 1
# elif type == "cpu":
# type_id = 14
#
# items = pod_name.split('-')
# container = '-'.join(items[0:-1])
# url = 'http://{}/dashboard-solo/db/containers?panelId={}&fullscreen&\
# var-namespace={}&var-pod={}&var-container={}'.format(settings.GRAFANA_SERVER,
# type_id, namespace, pod_name, container)
#
# return url
. Output only the next line. | url = get_api_server_url('/api/auth/login/') |
Continue the code snippet: <|code_start|> return False
def download_from_volume(self, project_id, volume_id):
"""
Download data from volume with id volume_id.
"""
url = get_api_server_url('/api/projects/{}/volumes/{}/download/'
.format(project_id, volume_id))
response = self.client.get(url)
return response
def clear_volume(self, project_id, volume_id):
"""
Clear data of volume with id volume_id.
"""
url = get_api_server_url('/api/projects/{}/volumes/{}/clear/'
.format(project_id, volume_id))
response = self.client.get(url)
if response.status_code == 200:
return True
else:
return False
def get_container_monitor_image(self, type, namespace, pod_name):
"""
Get container monitor image.
Params:
type: 1 is mem, 14 is cpu.
"""
<|code_end|>
. Use current file imports:
import json
import logging
import requests
from website.utils import (get_api_server_url, get_url_of_monitor_iframe)
and context (classes, functions, or code) from other files:
# Path: website/utils.py
# def get_api_server_url(path):
# """
# Return the url for api server.
# """
# return "http://" + settings.API_SERVER + path
#
# def get_url_of_monitor_iframe(type, namespace, pod_name):
# """
# Get the url of monitor iframe in user dashboard.
# """
# if type == "memory":
# type_id = 1
# elif type == "cpu":
# type_id = 14
#
# items = pod_name.split('-')
# container = '-'.join(items[0:-1])
# url = 'http://{}/dashboard-solo/db/containers?panelId={}&fullscreen&\
# var-namespace={}&var-pod={}&var-container={}'.format(settings.GRAFANA_SERVER,
# type_id, namespace, pod_name, container)
#
# return url
. Output only the next line. | url = get_url_of_monitor_iframe(type, namespace, pod_name) |
Based on the snippet: <|code_start|>
logger = logging.getLogger('hummer')
class ImageBuilder(object):
"""
ImageBuilder is to build image. One way is to use image file directly, the
other way is to use Dockerfile to build image.
is_image: 0|1|2, 0 represents build file, 1 represents image file,
2 represents container snapshot.
"""
build_file = None
is_image = 0
dockerfile = None
image = None
user = None
def __init__(self, build_file, is_image, dockerfile, image_id,
old_image_name, old_image_version):
self.build_file = build_file
self.is_image = is_image
self.dockerfile = dockerfile
<|code_end|>
, predict the immediate next line with the help of imports:
import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory
and context (classes, functions, sometimes code) from other files:
# Path: backend/models.py
# class Image(models.Model):
# """
# Image represents the model of every application, and there are many
# different version images in every application.
# """
# STATUS_CHOICES = (
# ('deleted', 'deleted'),
# ('deleting', 'deleting'),
# ('active', 'active'),
# ('creating', 'creating'),
# ('failed', 'failed')
# )
#
# user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True,
# default=True)
# project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
# default=True)
#
# name = models.CharField(max_length=32, default='')
# desc = models.TextField(max_length=256, null=True)
# version = models.CharField(max_length=32)
# digest = models.CharField(max_length=64, blank=True, null=True, default='')
# token = models.CharField(max_length=64, blank=True, null=True, default='')
# is_public = models.BooleanField(default=False)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES,
# default='creating')
# create_time = models.DateTimeField(auto_now=True)
#
# Path: backend/utils.py
# def fetch_digest_from_response(response):
# """
# Fetch the image digest from response when push image from docker host to
# private registry.
# """
# # logger.debug(response)
# res = json.loads(response.decode())
# items = res.get('status').split(' ')
# res = [item for item in items if item.startswith('sha256:')]
# digest = res[0].split(':')[-1]
#
# return digest
#
# def get_optimal_docker_host():
# """
# Returns the optimal docker host to build image.
# """
# scheduler = DockerSchedulerFactory.get_scheduler()
# docker_host = scheduler.get_optimal_docker_host()
# return docker_host
#
# def remove_file_from_disk(filename):
# """
# Delete the file from disk.
# """
# if os.path.exists(filename):
# os.remove(filename)
#
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
. Output only the next line. | self.image = Image.objects.get(id=image_id) |
Next line prediction: <|code_start|> logger.info('There is no image called %s on docker host %s' %
(image_complete_name, base_url))
return None
logger.info('Image %s on docker host %s has been deleted.' %
(image_complete_name, base_url))
def _push_image_to_registry(self, base_url, image_name, image_version,
image_token):
"""
Push image from docker host to private registry.
Returns the sha256 digest of the image.
"""
image_complete_name = '%s:%s' %(image_name, image_version)
if not self._is_image_on_docker_host(base_url, image_token):
logger.error('There is no image called %s on docker host %s' %
(image_complete_name, base_url))
return None
client = Client(base_url=base_url)
try:
response = [res for res in client.push(image_complete_name,
stream=True)]
except Exception:
logger.error('Communicate with %s failed.' % base_url)
return None
try:
<|code_end|>
. Use current file imports:
(import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory)
and context including class names, function names, or small code snippets from other files:
# Path: backend/models.py
# class Image(models.Model):
# """
# Image represents the model of every application, and there are many
# different version images in every application.
# """
# STATUS_CHOICES = (
# ('deleted', 'deleted'),
# ('deleting', 'deleting'),
# ('active', 'active'),
# ('creating', 'creating'),
# ('failed', 'failed')
# )
#
# user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True,
# default=True)
# project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
# default=True)
#
# name = models.CharField(max_length=32, default='')
# desc = models.TextField(max_length=256, null=True)
# version = models.CharField(max_length=32)
# digest = models.CharField(max_length=64, blank=True, null=True, default='')
# token = models.CharField(max_length=64, blank=True, null=True, default='')
# is_public = models.BooleanField(default=False)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES,
# default='creating')
# create_time = models.DateTimeField(auto_now=True)
#
# Path: backend/utils.py
# def fetch_digest_from_response(response):
# """
# Fetch the image digest from response when push image from docker host to
# private registry.
# """
# # logger.debug(response)
# res = json.loads(response.decode())
# items = res.get('status').split(' ')
# res = [item for item in items if item.startswith('sha256:')]
# digest = res[0].split(':')[-1]
#
# return digest
#
# def get_optimal_docker_host():
# """
# Returns the optimal docker host to build image.
# """
# scheduler = DockerSchedulerFactory.get_scheduler()
# docker_host = scheduler.get_optimal_docker_host()
# return docker_host
#
# def remove_file_from_disk(filename):
# """
# Delete the file from disk.
# """
# if os.path.exists(filename):
# os.remove(filename)
#
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
. Output only the next line. | digest = fetch_digest_from_response(response[-1]) |
Continue the code snippet: <|code_start|>
def __init__(self, build_file, is_image, dockerfile, image_id,
old_image_name, old_image_version):
self.build_file = build_file
self.is_image = is_image
self.dockerfile = dockerfile
self.image = Image.objects.get(id=image_id)
self.user = self.image.user
self.old_image_name = old_image_name
self.old_image_version = old_image_version
def create_image(self):
"""
Create image by two ways.
"""
target = None
if self.is_image != 0:
target = self._create_image_by_imagefile
else:
target = self._create_image_by_dockerfile
creating_thread = Thread(target=target)
creating_thread.start()
def _create_image_by_imagefile(self):
"""
Create image by imagefile.
"""
logger.debug("creating an image by imagefile.")
<|code_end|>
. Use current file imports:
import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory
and context (classes, functions, or code) from other files:
# Path: backend/models.py
# class Image(models.Model):
# """
# Image represents the model of every application, and there are many
# different version images in every application.
# """
# STATUS_CHOICES = (
# ('deleted', 'deleted'),
# ('deleting', 'deleting'),
# ('active', 'active'),
# ('creating', 'creating'),
# ('failed', 'failed')
# )
#
# user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True,
# default=True)
# project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
# default=True)
#
# name = models.CharField(max_length=32, default='')
# desc = models.TextField(max_length=256, null=True)
# version = models.CharField(max_length=32)
# digest = models.CharField(max_length=64, blank=True, null=True, default='')
# token = models.CharField(max_length=64, blank=True, null=True, default='')
# is_public = models.BooleanField(default=False)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES,
# default='creating')
# create_time = models.DateTimeField(auto_now=True)
#
# Path: backend/utils.py
# def fetch_digest_from_response(response):
# """
# Fetch the image digest from response when push image from docker host to
# private registry.
# """
# # logger.debug(response)
# res = json.loads(response.decode())
# items = res.get('status').split(' ')
# res = [item for item in items if item.startswith('sha256:')]
# digest = res[0].split(':')[-1]
#
# return digest
#
# def get_optimal_docker_host():
# """
# Returns the optimal docker host to build image.
# """
# scheduler = DockerSchedulerFactory.get_scheduler()
# docker_host = scheduler.get_optimal_docker_host()
# return docker_host
#
# def remove_file_from_disk(filename):
# """
# Delete the file from disk.
# """
# if os.path.exists(filename):
# os.remove(filename)
#
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
. Output only the next line. | docker_host = get_optimal_docker_host() |
Using the snippet: <|code_start|>
# TODO: create image on docker host
base_url = self._get_docker_host_base_url(docker_host)
image_name = self._get_image_name()
if self.is_image == 1:
token = self._load_image_on_docker_host(base_url, self.build_file,
image_name, self.image.version)
elif self.is_image == 2:
token = self._import_snapshot_on_docker_host(base_url,
self.build_file, image_name, self.image.version)
if not token:
logger.error("Import image on docker host failed")
self._update_image_status(status="failed")
return None
logger.info('Image %s:%s has been imported, with token %s', image_name,
self.image.version, token)
digest = self._push_image_to_registry(base_url, image_name,
self.image.version, token)
if not digest:
logger.error("Push image from docker host to registry failed")
self._update_image_status(status="failed")
return None
logger.info('Image %s:%s has been pushed to registry, with digest %s',
image_name, self.image.version, digest)
self._update_image_status(status="active", digest=digest, token=token)
<|code_end|>
, determine the next line of code. You have imports:
import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory
and context (class names, function names, or code) available:
# Path: backend/models.py
# class Image(models.Model):
# """
# Image represents the model of every application, and there are many
# different version images in every application.
# """
# STATUS_CHOICES = (
# ('deleted', 'deleted'),
# ('deleting', 'deleting'),
# ('active', 'active'),
# ('creating', 'creating'),
# ('failed', 'failed')
# )
#
# user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True,
# default=True)
# project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
# default=True)
#
# name = models.CharField(max_length=32, default='')
# desc = models.TextField(max_length=256, null=True)
# version = models.CharField(max_length=32)
# digest = models.CharField(max_length=64, blank=True, null=True, default='')
# token = models.CharField(max_length=64, blank=True, null=True, default='')
# is_public = models.BooleanField(default=False)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES,
# default='creating')
# create_time = models.DateTimeField(auto_now=True)
#
# Path: backend/utils.py
# def fetch_digest_from_response(response):
# """
# Fetch the image digest from response when push image from docker host to
# private registry.
# """
# # logger.debug(response)
# res = json.loads(response.decode())
# items = res.get('status').split(' ')
# res = [item for item in items if item.startswith('sha256:')]
# digest = res[0].split(':')[-1]
#
# return digest
#
# def get_optimal_docker_host():
# """
# Returns the optimal docker host to build image.
# """
# scheduler = DockerSchedulerFactory.get_scheduler()
# docker_host = scheduler.get_optimal_docker_host()
# return docker_host
#
# def remove_file_from_disk(filename):
# """
# Delete the file from disk.
# """
# if os.path.exists(filename):
# os.remove(filename)
#
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
. Output only the next line. | remove_file_from_disk(self.build_file) |
Predict the next line for this snippet: <|code_start|>
digest = self._push_image_to_registry(base_url, image_name,
self.image.version, token)
if not digest:
logger.error("Push image from docker host to registry failed")
self._update_image_status(status="failed")
return None
logger.info('Image %s:%s has been pushed to registry, with digest %s',
image_name, self.image.version, digest)
self._update_image_status(status="active", digest=digest, token=token)
remove_file_from_disk(self.build_file)
def _update_image_status(self, status, digest=None, token=None):
"""
Update image metadata after building the image.
"""
self.image.status = status
if digest:
self.image.digest = digest
if token:
self.image.token = token
self.image.save()
def _get_build_docker_host(self):
"""
Returns the optimal docker host to build image.
"""
<|code_end|>
with the help of current file imports:
import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory
and context from other files:
# Path: backend/models.py
# class Image(models.Model):
# """
# Image represents the model of every application, and there are many
# different version images in every application.
# """
# STATUS_CHOICES = (
# ('deleted', 'deleted'),
# ('deleting', 'deleting'),
# ('active', 'active'),
# ('creating', 'creating'),
# ('failed', 'failed')
# )
#
# user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True,
# default=True)
# project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
# default=True)
#
# name = models.CharField(max_length=32, default='')
# desc = models.TextField(max_length=256, null=True)
# version = models.CharField(max_length=32)
# digest = models.CharField(max_length=64, blank=True, null=True, default='')
# token = models.CharField(max_length=64, blank=True, null=True, default='')
# is_public = models.BooleanField(default=False)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES,
# default='creating')
# create_time = models.DateTimeField(auto_now=True)
#
# Path: backend/utils.py
# def fetch_digest_from_response(response):
# """
# Fetch the image digest from response when push image from docker host to
# private registry.
# """
# # logger.debug(response)
# res = json.loads(response.decode())
# items = res.get('status').split(' ')
# res = [item for item in items if item.startswith('sha256:')]
# digest = res[0].split(':')[-1]
#
# return digest
#
# def get_optimal_docker_host():
# """
# Returns the optimal docker host to build image.
# """
# scheduler = DockerSchedulerFactory.get_scheduler()
# docker_host = scheduler.get_optimal_docker_host()
# return docker_host
#
# def remove_file_from_disk(filename):
# """
# Delete the file from disk.
# """
# if os.path.exists(filename):
# os.remove(filename)
#
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
, which may contain function names, class names, or code. Output only the next line. | scheduler = DockerSchedulerFactory.get_scheduler() |
Given the following code snippet before the placeholder: <|code_start|>
class DockerSchedulerTestCase(unittest.TestCase):
def setUp(self):
self.scheduler = DockerScheduler('192.168.0.10', 4001)
def tearDown(self):
self.scheduler = None
def test_docker_hosts(self):
hosts = self.scheduler.get_docker_hosts()
self.assertEqual(2, len(hosts))
self.assertListEqual(sorted(hosts), ['192.168.0.10', '192.168.0.14'])
class DockerSchedulerFactoryTestCase(unittest.TestCase):
def test_scheduler_factory(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import os
from backend.schedule import DockerScheduler, DockerSchedulerFactory
and context including class names, function names, and sometimes code from other files:
# Path: backend/schedule.py
# class DockerScheduler(object):
# """
# DockerScheduler is a Docker Scheduler which is used to select a Docker
# mechine by a few strategies.
# """
# etcd_host = None
# etcd_port = None
# docker_hosts = None
# current_host = None
#
# def __init__(self, etcd_host='127.0.0.1', etcd_port=4001):
# self.etcd_host = etcd_host
# self.etcd_port = etcd_port
# self.docker_hosts = self._update_docker_list()
#
# def _update_docker_list(self):
# """
# Communicate with the etcd service, then update the docker list.
# """
# client = etcd.Client(host=self.etcd_host, port=self.etcd_port)
# try:
# result = client.get('/registry/minions/')
# except Exception:
# logger.error("Can't connect to etcd host %s:%s" % (self.etcd_host,
# self.etcd_port))
# return []
#
# hosts = []
# for child in result.children:
# hosts.append(child.key.split('/')[-1])
# return sorted(hosts)
#
# def get_docker_hosts(self):
# return self.docker_hosts
#
# def get_optimal_docker_host(self):
# """
# Returns the optimal docker host from the docker host lists by polling
# strategy.
# """
# self.docker_hosts = self._update_docker_list()
# if not self.docker_hosts:
# return None
#
# if (not self.current_host or
# (self.current_host not in self.docker_hosts)):
# index = random.randint(0, len(self.docker_hosts))
# else:
# index = self.docker_hosts.index(self.current_host)
#
# next_index = (index + 1) % len(self.docker_hosts)
#
# self.current_host = self.docker_hosts[next_index]
#
# return self.current_host
#
# class DockerSchedulerFactory(object):
# """
# Factory of DockerScheduler, to use the only one scheduler allways.
# """
# _scheduler = None
#
# @classmethod
# def get_scheduler(self):
# if not self._scheduler:
# self._scheduler = DockerScheduler(settings.MASTER_IP,
# settings.ETCD_PORT)
# return self._scheduler
. Output only the next line. | scheduler1 = DockerSchedulerFactory.get_scheduler() |
Given snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:
story_image = story.read()
ui = trivialzui.create_zui()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from zvm import zmachine, trivialzui
from zvm import quetzal
and context:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
#
# Path: zvm/quetzal.py
# class QuetzalError(Exception):
# class QuetzalMalformedChunk(QuetzalError):
# class QuetzalNoSuchSavefile(QuetzalError):
# class QuetzalUnrecognizedFileFormat(QuetzalError):
# class QuetzalIllegalChunkOrder(QuetzalError):
# class QuetzalMismatchedFile(QuetzalError):
# class QuetzalMemoryOutOfBounds(QuetzalError):
# class QuetzalMemoryMismatch(QuetzalError):
# class QuetzalStackFrameOverflow(QuetzalError):
# class QuetzalParser(object):
# class QuetzalWriter(object):
# def __init__(self, zmachine):
# def _parse_ifhd(self, data):
# def _parse_cmem(self, data):
# def _parse_umem(self, data):
# def _parse_stks(self, data):
# def _parse_intd(self, data):
# def _parse_auth(self, data):
# def _parse_copyright(self, data):
# def _parse_anno(self, data):
# def get_last_loaded(self):
# def load(self, savefile_path):
# def __init__(self, zmachine):
# def _generate_ifhd_chunk(self):
# def _generate_cmem_chunk(self):
# def _generate_stks_chunk(self):
# def _generate_anno_chunk(self):
# def write(self, savefile_path):
which might include code, classes, or functions. Output only the next line. | return zmachine.ZMachine(story_image, ui, debugmode=True) |
Based on the snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:
story_image = story.read()
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from zvm import zmachine, trivialzui
from zvm import quetzal
and context (classes, functions, sometimes code) from other files:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
#
# Path: zvm/quetzal.py
# class QuetzalError(Exception):
# class QuetzalMalformedChunk(QuetzalError):
# class QuetzalNoSuchSavefile(QuetzalError):
# class QuetzalUnrecognizedFileFormat(QuetzalError):
# class QuetzalIllegalChunkOrder(QuetzalError):
# class QuetzalMismatchedFile(QuetzalError):
# class QuetzalMemoryOutOfBounds(QuetzalError):
# class QuetzalMemoryMismatch(QuetzalError):
# class QuetzalStackFrameOverflow(QuetzalError):
# class QuetzalParser(object):
# class QuetzalWriter(object):
# def __init__(self, zmachine):
# def _parse_ifhd(self, data):
# def _parse_cmem(self, data):
# def _parse_umem(self, data):
# def _parse_stks(self, data):
# def _parse_intd(self, data):
# def _parse_auth(self, data):
# def _parse_copyright(self, data):
# def _parse_anno(self, data):
# def get_last_loaded(self):
# def load(self, savefile_path):
# def __init__(self, zmachine):
# def _generate_ifhd_chunk(self):
# def _generate_cmem_chunk(self):
# def _generate_stks_chunk(self):
# def _generate_anno_chunk(self):
# def write(self, savefile_path):
. Output only the next line. | ui = trivialzui.create_zui() |
Continue the code snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:
story_image = story.read()
ui = trivialzui.create_zui()
return zmachine.ZMachine(story_image, ui, debugmode=True)
class QuetzalWriterTest(TestCase):
def testWriteQuetzalFile(self):
machine = make_zmachine()
<|code_end|>
. Use current file imports:
from unittest import TestCase
from zvm import zmachine, trivialzui
from zvm import quetzal
and context (classes, functions, or code) from other files:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
#
# Path: zvm/quetzal.py
# class QuetzalError(Exception):
# class QuetzalMalformedChunk(QuetzalError):
# class QuetzalNoSuchSavefile(QuetzalError):
# class QuetzalUnrecognizedFileFormat(QuetzalError):
# class QuetzalIllegalChunkOrder(QuetzalError):
# class QuetzalMismatchedFile(QuetzalError):
# class QuetzalMemoryOutOfBounds(QuetzalError):
# class QuetzalMemoryMismatch(QuetzalError):
# class QuetzalStackFrameOverflow(QuetzalError):
# class QuetzalParser(object):
# class QuetzalWriter(object):
# def __init__(self, zmachine):
# def _parse_ifhd(self, data):
# def _parse_cmem(self, data):
# def _parse_umem(self, data):
# def _parse_stks(self, data):
# def _parse_intd(self, data):
# def _parse_auth(self, data):
# def _parse_copyright(self, data):
# def _parse_anno(self, data):
# def get_last_loaded(self):
# def load(self, savefile_path):
# def __init__(self, zmachine):
# def _generate_ifhd_chunk(self):
# def _generate_cmem_chunk(self):
# def _generate_stks_chunk(self):
# def _generate_anno_chunk(self):
# def write(self, savefile_path):
. Output only the next line. | writer = quetzal.QuetzalWriter(machine) |
Using the snippet: <|code_start|>#!/usr/bin/env python
def usage():
print("""Usage: %s <story file>
Run a Z-Machine story under ZVM.
""" % sys.argv[0])
sys.exit(1)
def main():
if len(sys.argv) != 2:
usage()
story_file = sys.argv[1]
if not os.path.isfile(story_file):
print("%s is not a file." % story_file)
usage()
try:
f = open(story_file, "rb")
story_image = f.read()
f.close()
except IOError:
print("Error accessing %s" % story_file)
sys.exit(1)
<|code_end|>
, determine the next line of code. You have imports:
import sys
import os.path
from zvm import zmachine, trivialzui
and context (class names, function names, or code) available:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
. Output only the next line. | machine = zmachine.ZMachine(story_image, |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
def usage():
print("""Usage: %s <story file>
Run a Z-Machine story under ZVM.
""" % sys.argv[0])
sys.exit(1)
def main():
if len(sys.argv) != 2:
usage()
story_file = sys.argv[1]
if not os.path.isfile(story_file):
print("%s is not a file." % story_file)
usage()
try:
f = open(story_file, "rb")
story_image = f.read()
f.close()
except IOError:
print("Error accessing %s" % story_file)
sys.exit(1)
machine = zmachine.ZMachine(story_image,
<|code_end|>
with the help of current file imports:
import sys
import os.path
from zvm import zmachine, trivialzui
and context from other files:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
, which may contain function names, class names, or code. Output only the next line. | ui=trivialzui.create_zui(), |
Based on the snippet: <|code_start|>#
# Unit tests for the bitfield class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class BitFieldTests(TestCase):
def testCreateInt(self):
for i in range(0,1024,3):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from zvm.bitfield import BitField
and context (classes, functions, sometimes code) from other files:
# Path: zvm/bitfield.py
# class BitField(object):
# """An bitfield gives read/write access to the individual bits of a
# value, in array and slice notation.
#
# Conversion back to an int value is also supported, and a method is
# provided to print the value in binary for debug purposes.
#
# For all indexes, 0 is the LSB (Least Significant Bit)."""
#
# def __init__(self, value=0):
# """Initialize a bitfield object from a number or string value."""
# if isinstance(value, str):
# self._d = ord(value)
# else:
# self._d = value
#
# def __getitem__(self, index):
# """Get the value of a single bit or slice."""
# if isinstance(index, slice):
# start, stop = index.start, index.stop
# if start > stop:
# (start, stop) = (stop, start)
# mask = (1<<(stop - start)) -1
# return (self._d >> start) & mask
# else:
# return (self._d >> index) & 1
#
# def __setitem__(self, index, value):
# """Set the value of a single bit or slice."""
# if isinstance(value, str):
# value = ord(value)
# if isinstance(index, slice):
# start, stop = index.start, index.stop
# mask = (1<<(stop - start)) -1
# value = (value & mask) << start
# mask = mask << start
# self._d = (self._d & ~mask) | value
# return (self._d >> start) & mask
# else:
# value = (value) << index
# mask = (1) << index
# self._d = (self._d & ~mask) | value
#
# def __int__(self):
# """Return the whole bitfield as an integer."""
# return self._d
#
# def to_str(self, len):
# """Print the binary representation of the bitfield."""
# return ''.join(["%d" % self[i]
# for i in range(len-1,-1,-1)])
. Output only the next line. | bf = BitField(i) |
Using the snippet: <|code_start|> pass
class ZStackPopError(ZStackError):
"Nothing to pop from stack!"
pass
# Helper class used by ZStackManager; a 'routine' object which
# includes its own private stack of data.
class ZRoutine(object):
def __init__(self, start_addr, return_addr, zmem, args,
local_vars=None, stack=None):
"""Initialize a routine object beginning at START_ADDR in ZMEM,
with initial argument values in list ARGS. If LOCAL_VARS is None,
then parse them from START_ADDR."""
self.start_addr = start_addr
self.return_addr = return_addr
self.program_counter = 0 # used when execution interrupted
if stack is None:
self.stack = []
else:
self.stack = stack[:]
if local_vars is not None:
self.local_vars = local_vars[:]
else:
num_local_vars = zmem[self.start_addr]
if not (0 <= num_local_vars <= 15):
<|code_end|>
, determine the next line of code. You have imports:
from .zlogging import log
and context (class names, function names, or code) available:
# Path: zvm/zlogging.py
# def log(msg):
# mainlog.debug(msg)
. Output only the next line. | log("num local vars is %d" % num_local_vars) |
Given the following code snippet before the placeholder: <|code_start|>#
# Unit tests for the Example class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:
story_image = story.read()
ui = trivialzui.create_zui()
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from zvm import zmachine, trivialzui
and context including class names, function names, and sometimes code from other files:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
. Output only the next line. | return zmachine.ZMachine(story_image, ui, debugmode=True) |
Using the snippet: <|code_start|>#
# Unit tests for the Example class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:
story_image = story.read()
<|code_end|>
, determine the next line of code. You have imports:
from unittest import TestCase
from zvm import zmachine, trivialzui
and context (class names, function names, or code) available:
# Path: zvm/zmachine.py
# class ZMachineError(Exception):
# class ZMachine(object):
# def __init__(self, story, ui, debugmode=False):
# def run(self):
#
# Path: zvm/trivialzui.py
# class TrivialAudio(zaudio.ZAudio):
# class TrivialScreen(zscreen.ZScreen):
# class TrivialKeyboardInputStream(zstream.ZInputStream):
# class TrivialFilesystem(zfilesystem.ZFilesystem):
# def __init__(self):
# def play_bleep(self, bleep_type):
# def __init__(self):
# def split_window(self, height):
# def select_window(self, window_num):
# def set_cursor_position(self, x, y):
# def erase_window(self, window=zscreen.WINDOW_LOWER,
# color=zscreen.COLOR_CURRENT):
# def set_font(self, font_number):
# def set_text_style(self, style):
# def __show_more_prompt(self):
# def on_input_occurred(self, newline_occurred=False):
# def __unbuffered_write(self, string):
# def write(self, string):
# def __init__(self, screen):
# def read_line(self, original_text=None, max_length=0,
# terminating_characters=None,
# timed_input_routine=None, timed_input_interval=0):
# def read_char(self, timed_input_routine=None,
# timed_input_interval=0):
# def __report_io_error(self, exception):
# def save_game(self, data, suggested_filename=None):
# def restore_game(self):
# def open_transcript_file_for_writing(self):
# def open_transcript_file_for_reading(self):
# def create_zui():
# def _win32_read_char():
# def _unix_read_char():
# def _read_char():
# def _read_line(original_text=None, terminating_characters=None):
# def _word_wrap(text, width):
# MORE_STRING = "[MORE]"
# _INTERRUPT_CHAR = chr(3)
# _BACKSPACE_CHAR = chr(8)
# _DELETE_CHAR = chr(127)
. Output only the next line. | ui = trivialzui.create_zui() |
Using the snippet: <|code_start|>
class TeamAuthenticationForm(AuthenticationForm):
"""
Custom variant of the login form that replaces "Username" with "Team name".
"""
username = forms.CharField(max_length=254, label=_('Team name'))
class FormalPasswordResetForm(PasswordResetForm):
"""
Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
and adds the CTF's title to the email rendering context.
"""
email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
'as authorative for sensitive requests.')
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
html_email_template_name=None):
<|code_end|>
, determine the next line of code. You have imports:
from django import forms
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm
from .scoring.models import GameControl
and context (class names, function names, or code) available:
# Path: src/ctf_gameserver/web/scoring/models.py
# class GameControl(models.Model):
# """
# Single-row database table to store control information for the competition.
# """
#
# competition_name = models.CharField(max_length=100, default='My A/D CTF')
# # Start and end times for the whole competition: Make them NULL-able (for the initial state), but not
# # blank-able (have to be set upon editing); "services_public" is the point at which information about the
# # services is public, but the actual game has not started yet
# services_public = models.DateTimeField(null=True)
# start = models.DateTimeField(null=True)
# end = models.DateTimeField(null=True)
# # Tick duration in seconds
# tick_duration = models.PositiveSmallIntegerField(default=180)
# # Number of ticks a flag is valid for including the one it was generated in
# valid_ticks = models.PositiveSmallIntegerField(default=5)
# current_tick = models.IntegerField(default=-1)
# flag_prefix = models.CharField(max_length=20, default='FLAG_')
# registration_open = models.BooleanField(default=False)
# registration_confirm_text = models.TextField(blank=True)
# min_net_number = models.PositiveIntegerField(null=True, blank=True)
# max_net_number = models.PositiveIntegerField(null=True, blank=True)
#
# class Meta:
# verbose_name_plural = 'Game control'
#
# @classmethod
# def get_instance(cls):
# try:
# return cls.objects.get()
# except cls.DoesNotExist:
# game_control = GameControl()
# game_control.save()
# return game_control
#
# def clean(self):
# """
# Ensures that only one instance of the class gets created.
# Inspired by https://stackoverflow.com/a/6436008.
# """
# cls = self.__class__
#
# if cls.objects.count() > 0 and self.id != cls.objects.get().id:
# # pylint: disable=no-member
# raise ValidationError(_('Only a single instance of {cls} can be created')
# .format(cls=cls.__name__))
#
# def are_services_public(self):
# """
# Indicates whether information about the services is public yet.
# """
# if self.services_public is None:
# return False
#
# return self.services_public <= timezone.now()
#
# def competition_started(self):
# """
# Indicates whether the competition has already begun (i.e. running or over).
# """
# if self.start is None or self.end is None:
# return False
#
# return self.start <= timezone.now()
#
# def competition_over(self):
# """
# Indicates whether the competition is already over.
# """
# if self.start is None or self.end is None:
# return False
#
# return self.end < timezone.now()
. Output only the next line. | context['competition_name'] = GameControl.get_instance().competition_name |
Using the snippet: <|code_start|>
class InlineTeamAdmin(admin.StackedInline):
"""
InlineModelAdmin for Team objects. Primarily designed to be used within a UserAdmin.
"""
model = Team
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from .models import Team
from .forms import AdminTeamForm
and context (class names, function names, or code) available:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/forms.py
# class AdminTeamForm(forms.ModelForm):
# """
# Form for Team objects to be used in TeamAdmin.
# """
#
# class Meta:
# fields = '__all__'
# labels = {
# 'nop_team': _('NOP team')
# }
# help_texts = {
# 'nop_team': _("NOP teams are meant for demo purposes (to provide a reference image) and don't "
# "get included in the scoring.")
# }
. Output only the next line. | form = AdminTeamForm |
Here is a snippet: <|code_start|>
def registration_open_required(view):
"""
View decorator which prohibits access to the decorated view if registration is closed from the
GameControl object.
"""
@wraps(view)
def func(request, *args, **kwargs):
<|code_end|>
. Write the next line using the current file imports:
from functools import wraps
from django.shortcuts import redirect
from django.conf import settings
from django.http import JsonResponse
from django.utils.translation import ugettext as _
from django.contrib import messages
from .models import GameControl
and context from other files:
# Path: src/ctf_gameserver/web/scoring/models.py
# class GameControl(models.Model):
# """
# Single-row database table to store control information for the competition.
# """
#
# competition_name = models.CharField(max_length=100, default='My A/D CTF')
# # Start and end times for the whole competition: Make them NULL-able (for the initial state), but not
# # blank-able (have to be set upon editing); "services_public" is the point at which information about the
# # services is public, but the actual game has not started yet
# services_public = models.DateTimeField(null=True)
# start = models.DateTimeField(null=True)
# end = models.DateTimeField(null=True)
# # Tick duration in seconds
# tick_duration = models.PositiveSmallIntegerField(default=180)
# # Number of ticks a flag is valid for including the one it was generated in
# valid_ticks = models.PositiveSmallIntegerField(default=5)
# current_tick = models.IntegerField(default=-1)
# flag_prefix = models.CharField(max_length=20, default='FLAG_')
# registration_open = models.BooleanField(default=False)
# registration_confirm_text = models.TextField(blank=True)
# min_net_number = models.PositiveIntegerField(null=True, blank=True)
# max_net_number = models.PositiveIntegerField(null=True, blank=True)
#
# class Meta:
# verbose_name_plural = 'Game control'
#
# @classmethod
# def get_instance(cls):
# try:
# return cls.objects.get()
# except cls.DoesNotExist:
# game_control = GameControl()
# game_control.save()
# return game_control
#
# def clean(self):
# """
# Ensures that only one instance of the class gets created.
# Inspired by https://stackoverflow.com/a/6436008.
# """
# cls = self.__class__
#
# if cls.objects.count() > 0 and self.id != cls.objects.get().id:
# # pylint: disable=no-member
# raise ValidationError(_('Only a single instance of {cls} can be created')
# .format(cls=cls.__name__))
#
# def are_services_public(self):
# """
# Indicates whether information about the services is public yet.
# """
# if self.services_public is None:
# return False
#
# return self.services_public <= timezone.now()
#
# def competition_started(self):
# """
# Indicates whether the competition has already begun (i.e. running or over).
# """
# if self.start is None or self.end is None:
# return False
#
# return self.start <= timezone.now()
#
# def competition_over(self):
# """
# Indicates whether the competition is already over.
# """
# if self.start is None or self.end is None:
# return False
#
# return self.end < timezone.now()
, which may include functions, classes, or code. Output only the next line. | if not GameControl.get_instance().registration_open: |
Using the snippet: <|code_start|>
class CTFAdminSite(admin.AdminSite):
"""
Custom variant of the AdminSite which replaces the default headers and titles.
"""
index_title = _('Administration home')
# Declare this lazily through a classproperty in order to avoid a circular dependency when creating
# migrations
@classproperty
def site_header(cls): # pylint: disable=no-self-argument
return format_lazy(_('{competition_name} administration'),
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django.utils.functional import classproperty
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from .registration.models import Team
from .registration.admin import InlineTeamAdmin
from .scoring.models import GameControl
from .util import format_lazy
and context (class names, function names, or code) available:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/admin.py
# class InlineTeamAdmin(admin.StackedInline):
# """
# InlineModelAdmin for Team objects. Primarily designed to be used within a UserAdmin.
# """
#
# model = Team
# form = AdminTeamForm
#
# # Abuse the plural title as headline, since more than one team will never be edited using this inline
# verbose_name_plural = _('Associated team')
#
# Path: src/ctf_gameserver/web/scoring/models.py
# class GameControl(models.Model):
# """
# Single-row database table to store control information for the competition.
# """
#
# competition_name = models.CharField(max_length=100, default='My A/D CTF')
# # Start and end times for the whole competition: Make them NULL-able (for the initial state), but not
# # blank-able (have to be set upon editing); "services_public" is the point at which information about the
# # services is public, but the actual game has not started yet
# services_public = models.DateTimeField(null=True)
# start = models.DateTimeField(null=True)
# end = models.DateTimeField(null=True)
# # Tick duration in seconds
# tick_duration = models.PositiveSmallIntegerField(default=180)
# # Number of ticks a flag is valid for including the one it was generated in
# valid_ticks = models.PositiveSmallIntegerField(default=5)
# current_tick = models.IntegerField(default=-1)
# flag_prefix = models.CharField(max_length=20, default='FLAG_')
# registration_open = models.BooleanField(default=False)
# registration_confirm_text = models.TextField(blank=True)
# min_net_number = models.PositiveIntegerField(null=True, blank=True)
# max_net_number = models.PositiveIntegerField(null=True, blank=True)
#
# class Meta:
# verbose_name_plural = 'Game control'
#
# @classmethod
# def get_instance(cls):
# try:
# return cls.objects.get()
# except cls.DoesNotExist:
# game_control = GameControl()
# game_control.save()
# return game_control
#
# def clean(self):
# """
# Ensures that only one instance of the class gets created.
# Inspired by https://stackoverflow.com/a/6436008.
# """
# cls = self.__class__
#
# if cls.objects.count() > 0 and self.id != cls.objects.get().id:
# # pylint: disable=no-member
# raise ValidationError(_('Only a single instance of {cls} can be created')
# .format(cls=cls.__name__))
#
# def are_services_public(self):
# """
# Indicates whether information about the services is public yet.
# """
# if self.services_public is None:
# return False
#
# return self.services_public <= timezone.now()
#
# def competition_started(self):
# """
# Indicates whether the competition has already begun (i.e. running or over).
# """
# if self.start is None or self.end is None:
# return False
#
# return self.start <= timezone.now()
#
# def competition_over(self):
# """
# Indicates whether the competition is already over.
# """
# if self.start is None or self.end is None:
# return False
#
# return self.end < timezone.now()
#
# Path: src/ctf_gameserver/web/util.py
# def _format_proxy(proxy, *args, **kwargs):
. Output only the next line. | competition_name=GameControl.get_instance().competition_name) |
Given the following code snippet before the placeholder: <|code_start|>
class CTFAdminSite(admin.AdminSite):
"""
Custom variant of the AdminSite which replaces the default headers and titles.
"""
index_title = _('Administration home')
# Declare this lazily through a classproperty in order to avoid a circular dependency when creating
# migrations
@classproperty
def site_header(cls): # pylint: disable=no-self-argument
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from django.utils.functional import classproperty
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from .registration.models import Team
from .registration.admin import InlineTeamAdmin
from .scoring.models import GameControl
from .util import format_lazy
and context including class names, function names, and sometimes code from other files:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/admin.py
# class InlineTeamAdmin(admin.StackedInline):
# """
# InlineModelAdmin for Team objects. Primarily designed to be used within a UserAdmin.
# """
#
# model = Team
# form = AdminTeamForm
#
# # Abuse the plural title as headline, since more than one team will never be edited using this inline
# verbose_name_plural = _('Associated team')
#
# Path: src/ctf_gameserver/web/scoring/models.py
# class GameControl(models.Model):
# """
# Single-row database table to store control information for the competition.
# """
#
# competition_name = models.CharField(max_length=100, default='My A/D CTF')
# # Start and end times for the whole competition: Make them NULL-able (for the initial state), but not
# # blank-able (have to be set upon editing); "services_public" is the point at which information about the
# # services is public, but the actual game has not started yet
# services_public = models.DateTimeField(null=True)
# start = models.DateTimeField(null=True)
# end = models.DateTimeField(null=True)
# # Tick duration in seconds
# tick_duration = models.PositiveSmallIntegerField(default=180)
# # Number of ticks a flag is valid for including the one it was generated in
# valid_ticks = models.PositiveSmallIntegerField(default=5)
# current_tick = models.IntegerField(default=-1)
# flag_prefix = models.CharField(max_length=20, default='FLAG_')
# registration_open = models.BooleanField(default=False)
# registration_confirm_text = models.TextField(blank=True)
# min_net_number = models.PositiveIntegerField(null=True, blank=True)
# max_net_number = models.PositiveIntegerField(null=True, blank=True)
#
# class Meta:
# verbose_name_plural = 'Game control'
#
# @classmethod
# def get_instance(cls):
# try:
# return cls.objects.get()
# except cls.DoesNotExist:
# game_control = GameControl()
# game_control.save()
# return game_control
#
# def clean(self):
# """
# Ensures that only one instance of the class gets created.
# Inspired by https://stackoverflow.com/a/6436008.
# """
# cls = self.__class__
#
# if cls.objects.count() > 0 and self.id != cls.objects.get().id:
# # pylint: disable=no-member
# raise ValidationError(_('Only a single instance of {cls} can be created')
# .format(cls=cls.__name__))
#
# def are_services_public(self):
# """
# Indicates whether information about the services is public yet.
# """
# if self.services_public is None:
# return False
#
# return self.services_public <= timezone.now()
#
# def competition_started(self):
# """
# Indicates whether the competition has already begun (i.e. running or over).
# """
# if self.start is None or self.end is None:
# return False
#
# return self.start <= timezone.now()
#
# def competition_over(self):
# """
# Indicates whether the competition is already over.
# """
# if self.start is None or self.end is None:
# return False
#
# return self.end < timezone.now()
#
# Path: src/ctf_gameserver/web/util.py
# def _format_proxy(proxy, *args, **kwargs):
. Output only the next line. | return format_lazy(_('{competition_name} administration'), |
Next line prediction: <|code_start|> team_entry = {
'id': team.user.pk,
'nop': team.nop_team,
'name': team.user.username,
'ticks': [],
}
if team.image:
team_entry['image'] = team.image.url
team_entry['thumbnail'] = team.image.get_thumbnail_url()
for tick in response['ticks']:
tick_services = []
for service in services:
try:
tick_services.append(tick_statuses[tick][service])
except KeyError:
tick_services.append('')
team_entry['ticks'].append(tick_services)
response['teams'].append(team_entry)
for service in services:
response['services'].append(service.name)
return JsonResponse(response)
@cache_page(60)
# Don't provide a list of all teams while registration is open to prevent
# crawling of registered teams and comparing with this list
<|code_end|>
. Use current file imports:
(from collections import defaultdict
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.db.models import Max
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from . import models, calculations
from .decorators import registration_closed_required, services_public_required
import ctf_gameserver.web.registration.models as registration_models)
and context including class names, function names, or small code snippets from other files:
# Path: src/ctf_gameserver/web/scoring/decorators.py
# def registration_closed_required(view):
# """
# View decorator which only allows access to the decorated view if registration is closed from the
# GameControl object.
# Format of the response is currently always JSON.
# """
#
# @wraps(view)
# def func(request, *args, **kwargs):
# if GameControl.get_instance().registration_open:
# return JsonResponse({'error': 'Not available yet'}, status=404)
#
# return view(request, *args, **kwargs)
#
# return func
#
# def services_public_required(resp_format):
# """
# View decorator which prohibits access to the decorated view if information about the services is not
# public yet.
#
# Args:
# resp_format: Format of the response when the competition has not yet started. Supported options are
# 'html' and 'json'.
# """
#
# def decorator(view):
# @wraps(view)
# def func(request, *args, **kwargs):
# game_control = GameControl.get_instance()
# if game_control.are_services_public():
# return view(request, *args, **kwargs)
#
# if resp_format == 'json':
# return JsonResponse({'error': 'Not available yet'}, status=404)
# else:
# messages.error(request, _('Sorry, the page you requested is not available yet.'))
# return redirect(settings.HOME_URL)
#
# return func
#
# return decorator
. Output only the next line. | @registration_closed_required |
Here is a snippet: <|code_start|>
def _gen_image_name(instance, _):
"""
Returns the upload path (relative to settings.MEDIA_ROOT) for the specified Team's image.
"""
# Must "return a Unix-style path (with forward slashes)"
return 'team-images' + '/' + str(instance.user.id) + '.png'
class Team(models.Model):
"""
Database representation of a team participating in the competition.
This enhances the user model, where the team name, password, formal email address etc. are stored. It is
particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
net_number = models.PositiveSmallIntegerField(null=True, unique=True)
informal_email = models.EmailField(_('Informal email address'))
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .fields import ThumbnailImageField
and context from other files:
# Path: src/ctf_gameserver/web/registration/fields.py
# class ThumbnailImageField(ImageField):
# """
# Custom variant of ImageField which automatically resizes and re-serializes an uploaded image.
# """
#
# attr_class = ThumbnailImageFieldFile
, which may include functions, classes, or code. Output only the next line. | image = ThumbnailImageField(upload_to=_gen_image_name, blank=True) |
Here is a snippet: <|code_start|>
def game_control(_):
"""
Context processor which adds information from the Game Control table to the context.
"""
control_instance = scoring_models.GameControl.get_instance()
return {
'competition_name': control_instance.competition_name,
'registration_open': control_instance.registration_open,
'services_public': control_instance.are_services_public()
}
def flatpage_nav(_):
"""
Context processor which adds data required for the main navigation of flatpages to the context.
"""
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from .scoring import models as scoring_models
from .flatpages import models as flatpages_models
and context from other files:
# Path: src/ctf_gameserver/web/scoring/models.py
# class Service(models.Model):
# class Flag(models.Model):
# class Meta:
# class Capture(models.Model):
# class Meta:
# class StatusCheck(models.Model):
# class Meta:
# class ScoreBoard(models.Model):
# class Meta:
# class CheckerState(models.Model):
# class Meta:
# class GameControl(models.Model):
# class Meta:
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def get_instance(cls):
# def clean(self):
# def are_services_public(self):
# def competition_started(self):
# def competition_over(self):
# STATUSES = {
# _('up'): 0, # Maps to "OK" from the checkers' perspective
# _('down'): 1,
# _('faulty'): 2,
# _('flag not found'): 3,
# _('recovering'): 4
# }
#
# Path: src/ctf_gameserver/web/flatpages/models.py
# class Category(models.Model):
# class Meta:
# class Flatpage(models.Model):
# class Meta:
# class ObjectsWithoutCategoryManager(models.Manager):
# def __str__(self):
# def get_queryset(self):
# def __str__(self):
# def clean(self):
# def get_absolute_url(self):
# def siblings(self):
# def has_siblings(self):
# def is_home_page(self):
# def render_content(self):
, which may include functions, classes, or code. Output only the next line. | categories = flatpages_models.Category.objects.all() |
Given the code snippet: <|code_start|> return redirect(settings.HOME_URL)
else:
delete_form = forms.DeleteForm(user=request.user, prefix='delete')
return render(request, 'edit_team.html', {
'user_form': user_form,
'team_form': team_form,
'delete_form': delete_form
})
@transaction.atomic
def confirm_email(request):
try:
user_pk = request.GET['user']
token = request.GET['token']
except KeyError:
messages.error(request, _('Missing parameters, email address could not be confirmed.'))
return render(request, '400.html', status=400)
error_message = _('Invalid user or token, email address could not be confirmed.')
# pylint: disable=protected-access
try:
user = User._default_manager.get(pk=user_pk)
except User.DoesNotExist:
messages.error(request, error_message)
return render(request, '400.html', status=400)
<|code_end|>
, generate the next line using the imports in this file:
import logging
import random
import ctf_gameserver.web.scoring.models as scoring_models
from django.db import transaction, IntegrityError
from django.views.generic import ListView
from django.shortcuts import render, redirect
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.contrib.auth import logout, get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from ctf_gameserver.web.scoring.decorators import before_competition_required, registration_open_required
from . import forms
from .models import Team
from .util import email_token_generator
and context (functions, classes, or occasionally code) from other files:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
# def _make_hash_value(self, user, timestamp):
# def get_country_names():
. Output only the next line. | if not email_token_generator.check_token(user, token): |
Given the code snippet: <|code_start|> url(r'^auth/change-password/$',
auth_views.PasswordChangeView.as_view(template_name='password_change.html',
success_url=reverse_lazy('edit_team')),
name='password_change'
),
url(r'^auth/reset-password/$',
auth_views.PasswordResetView.as_view(template_name='password_reset.html',
email_template_name='password_reset_mail.txt',
subject_template_name='password_reset_subject.txt',
form_class=FormalPasswordResetForm),
name='password_reset'
),
url(r'^auth/reset-password/done/$',
auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'),
name='password_reset_done'
),
url(r'^auth/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'),
name='password_reset_confirm'
),
url(r'^auth/reset/complete/$',
auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'),
name='password_reset_complete'
),
url(r'^competition/teams/$',
registration_views.TeamList.as_view(),
name='team_list'
),
url(r'^competition/teams\.json$',
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import re_path as url, reverse_lazy
from .registration import views as registration_views
from .scoring import views as scoring_views
from .flatpages import views as flatpages_views
from .admin import admin_site
from .forms import TeamAuthenticationForm, FormalPasswordResetForm
and context (functions, classes, or occasionally code) from other files:
# Path: src/ctf_gameserver/web/registration/views.py
# class TeamList(ListView):
# def register(request):
# def edit_team(request):
# def delete_team(request):
# def confirm_email(request):
# def mail_teams(request):
#
# Path: src/ctf_gameserver/web/scoring/views.py
# def scoreboard(request):
# def scoreboard_json(_):
# def scoreboard_json_ctftime(_):
# def service_status(request):
# def service_status_json(_):
# def teams_json(_):
# def service_history(request):
# def service_history_json(request):
# def append_result(next_team_id):
# def _get_status_descriptions():
#
# Path: src/ctf_gameserver/web/flatpages/views.py
# def flatpage(request, category=None, slug=''):
#
# Path: src/ctf_gameserver/web/admin.py
# class CTFAdminSite(admin.AdminSite):
# class CTFUserAdmin(UserAdmin):
# class TeamListFilter(admin.SimpleListFilter):
# def site_header(cls): # pylint: disable=no-self-argument
# def site_title(cls): # pylint: disable=no-self-argument
# def __init__(self, *args, **kwargs):
# def lookups(self, request, model_admin):
# def queryset(self, request, queryset):
# def user_has_team(self, user):
#
# Path: src/ctf_gameserver/web/forms.py
# class TeamAuthenticationForm(AuthenticationForm):
# """
# Custom variant of the login form that replaces "Username" with "Team name".
# """
#
# username = forms.CharField(max_length=254, label=_('Team name'))
#
# class FormalPasswordResetForm(PasswordResetForm):
# """
# Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
# and adds the CTF's title to the email rendering context.
# """
#
# email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
# 'as authorative for sensitive requests.')
#
# def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name=None):
# context['competition_name'] = GameControl.get_instance().competition_name
#
# return super().send_mail(subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name)
. Output only the next line. | scoring_views.teams_json, |
Given the code snippet: <|code_start|> url(r'^competition/scoreboard-ctftime\.json$',
scoring_views.scoreboard_json_ctftime,
name='scoreboard_json_ctftime'
),
url(r'^competition/status/$',
scoring_views.service_status,
name='service_status'
),
url(r'^competition/status\.json$',
scoring_views.service_status_json,
name='service_status_json'
),
url(r'^internal/mail-teams/$',
registration_views.mail_teams,
name='mail_teams'
),
url(r'^internal/service-history$',
scoring_views.service_history,
name='service_history'
),
url(r'^internal/service-history\.json$',
scoring_views.service_history_json,
name='service_history_json'
),
url(r'^admin/', admin_site.urls),
# Multiple seperate URL patterns have to be used to work around
# https://code.djangoproject.com/ticket/9176
url(r'^$',
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import re_path as url, reverse_lazy
from .registration import views as registration_views
from .scoring import views as scoring_views
from .flatpages import views as flatpages_views
from .admin import admin_site
from .forms import TeamAuthenticationForm, FormalPasswordResetForm
and context (functions, classes, or occasionally code) from other files:
# Path: src/ctf_gameserver/web/registration/views.py
# class TeamList(ListView):
# def register(request):
# def edit_team(request):
# def delete_team(request):
# def confirm_email(request):
# def mail_teams(request):
#
# Path: src/ctf_gameserver/web/scoring/views.py
# def scoreboard(request):
# def scoreboard_json(_):
# def scoreboard_json_ctftime(_):
# def service_status(request):
# def service_status_json(_):
# def teams_json(_):
# def service_history(request):
# def service_history_json(request):
# def append_result(next_team_id):
# def _get_status_descriptions():
#
# Path: src/ctf_gameserver/web/flatpages/views.py
# def flatpage(request, category=None, slug=''):
#
# Path: src/ctf_gameserver/web/admin.py
# class CTFAdminSite(admin.AdminSite):
# class CTFUserAdmin(UserAdmin):
# class TeamListFilter(admin.SimpleListFilter):
# def site_header(cls): # pylint: disable=no-self-argument
# def site_title(cls): # pylint: disable=no-self-argument
# def __init__(self, *args, **kwargs):
# def lookups(self, request, model_admin):
# def queryset(self, request, queryset):
# def user_has_team(self, user):
#
# Path: src/ctf_gameserver/web/forms.py
# class TeamAuthenticationForm(AuthenticationForm):
# """
# Custom variant of the login form that replaces "Username" with "Team name".
# """
#
# username = forms.CharField(max_length=254, label=_('Team name'))
#
# class FormalPasswordResetForm(PasswordResetForm):
# """
# Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
# and adds the CTF's title to the email rendering context.
# """
#
# email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
# 'as authorative for sensitive requests.')
#
# def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name=None):
# context['competition_name'] = GameControl.get_instance().competition_name
#
# return super().send_mail(subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name)
. Output only the next line. | flatpages_views.flatpage, |
Predict the next line for this snippet: <|code_start|> ),
url(r'^competition/scoreboard\.json$',
scoring_views.scoreboard_json,
name='scoreboard_json'
),
url(r'^competition/scoreboard-ctftime\.json$',
scoring_views.scoreboard_json_ctftime,
name='scoreboard_json_ctftime'
),
url(r'^competition/status/$',
scoring_views.service_status,
name='service_status'
),
url(r'^competition/status\.json$',
scoring_views.service_status_json,
name='service_status_json'
),
url(r'^internal/mail-teams/$',
registration_views.mail_teams,
name='mail_teams'
),
url(r'^internal/service-history$',
scoring_views.service_history,
name='service_history'
),
url(r'^internal/service-history\.json$',
scoring_views.service_history_json,
name='service_history_json'
),
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import re_path as url, reverse_lazy
from .registration import views as registration_views
from .scoring import views as scoring_views
from .flatpages import views as flatpages_views
from .admin import admin_site
from .forms import TeamAuthenticationForm, FormalPasswordResetForm
and context from other files:
# Path: src/ctf_gameserver/web/registration/views.py
# class TeamList(ListView):
# def register(request):
# def edit_team(request):
# def delete_team(request):
# def confirm_email(request):
# def mail_teams(request):
#
# Path: src/ctf_gameserver/web/scoring/views.py
# def scoreboard(request):
# def scoreboard_json(_):
# def scoreboard_json_ctftime(_):
# def service_status(request):
# def service_status_json(_):
# def teams_json(_):
# def service_history(request):
# def service_history_json(request):
# def append_result(next_team_id):
# def _get_status_descriptions():
#
# Path: src/ctf_gameserver/web/flatpages/views.py
# def flatpage(request, category=None, slug=''):
#
# Path: src/ctf_gameserver/web/admin.py
# class CTFAdminSite(admin.AdminSite):
# class CTFUserAdmin(UserAdmin):
# class TeamListFilter(admin.SimpleListFilter):
# def site_header(cls): # pylint: disable=no-self-argument
# def site_title(cls): # pylint: disable=no-self-argument
# def __init__(self, *args, **kwargs):
# def lookups(self, request, model_admin):
# def queryset(self, request, queryset):
# def user_has_team(self, user):
#
# Path: src/ctf_gameserver/web/forms.py
# class TeamAuthenticationForm(AuthenticationForm):
# """
# Custom variant of the login form that replaces "Username" with "Team name".
# """
#
# username = forms.CharField(max_length=254, label=_('Team name'))
#
# class FormalPasswordResetForm(PasswordResetForm):
# """
# Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
# and adds the CTF's title to the email rendering context.
# """
#
# email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
# 'as authorative for sensitive requests.')
#
# def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name=None):
# context['competition_name'] = GameControl.get_instance().competition_name
#
# return super().send_mail(subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name)
, which may contain function names, class names, or code. Output only the next line. | url(r'^admin/', admin_site.urls), |
Based on the snippet: <|code_start|>
# pylint: disable=invalid-name, bad-continuation
urlpatterns = [
url(r'^auth/register/$',
registration_views.register,
name='register'
), # noqa
url(r'^auth/confirm-email/$',
registration_views.confirm_email,
name='confirm_email'
),
url(r'^auth/edit-team/$',
registration_views.edit_team,
name='edit_team'
),
url(r'^auth/delete-team/$',
registration_views.delete_team,
name='delete_team'
),
url(r'^auth/login/$',
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import re_path as url, reverse_lazy
from .registration import views as registration_views
from .scoring import views as scoring_views
from .flatpages import views as flatpages_views
from .admin import admin_site
from .forms import TeamAuthenticationForm, FormalPasswordResetForm
and context (classes, functions, sometimes code) from other files:
# Path: src/ctf_gameserver/web/registration/views.py
# class TeamList(ListView):
# def register(request):
# def edit_team(request):
# def delete_team(request):
# def confirm_email(request):
# def mail_teams(request):
#
# Path: src/ctf_gameserver/web/scoring/views.py
# def scoreboard(request):
# def scoreboard_json(_):
# def scoreboard_json_ctftime(_):
# def service_status(request):
# def service_status_json(_):
# def teams_json(_):
# def service_history(request):
# def service_history_json(request):
# def append_result(next_team_id):
# def _get_status_descriptions():
#
# Path: src/ctf_gameserver/web/flatpages/views.py
# def flatpage(request, category=None, slug=''):
#
# Path: src/ctf_gameserver/web/admin.py
# class CTFAdminSite(admin.AdminSite):
# class CTFUserAdmin(UserAdmin):
# class TeamListFilter(admin.SimpleListFilter):
# def site_header(cls): # pylint: disable=no-self-argument
# def site_title(cls): # pylint: disable=no-self-argument
# def __init__(self, *args, **kwargs):
# def lookups(self, request, model_admin):
# def queryset(self, request, queryset):
# def user_has_team(self, user):
#
# Path: src/ctf_gameserver/web/forms.py
# class TeamAuthenticationForm(AuthenticationForm):
# """
# Custom variant of the login form that replaces "Username" with "Team name".
# """
#
# username = forms.CharField(max_length=254, label=_('Team name'))
#
# class FormalPasswordResetForm(PasswordResetForm):
# """
# Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
# and adds the CTF's title to the email rendering context.
# """
#
# email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
# 'as authorative for sensitive requests.')
#
# def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name=None):
# context['competition_name'] = GameControl.get_instance().competition_name
#
# return super().send_mail(subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name)
. Output only the next line. | auth_views.LoginView.as_view(template_name='login.html', authentication_form=TeamAuthenticationForm), |
Here is a snippet: <|code_start|> url(r'^auth/confirm-email/$',
registration_views.confirm_email,
name='confirm_email'
),
url(r'^auth/edit-team/$',
registration_views.edit_team,
name='edit_team'
),
url(r'^auth/delete-team/$',
registration_views.delete_team,
name='delete_team'
),
url(r'^auth/login/$',
auth_views.LoginView.as_view(template_name='login.html', authentication_form=TeamAuthenticationForm),
name='login'
),
url(r'^auth/logout/$',
auth_views.LogoutView.as_view(next_page=settings.HOME_URL),
name='logout'
),
url(r'^auth/change-password/$',
auth_views.PasswordChangeView.as_view(template_name='password_change.html',
success_url=reverse_lazy('edit_team')),
name='password_change'
),
url(r'^auth/reset-password/$',
auth_views.PasswordResetView.as_view(template_name='password_reset.html',
email_template_name='password_reset_mail.txt',
subject_template_name='password_reset_subject.txt',
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import re_path as url, reverse_lazy
from .registration import views as registration_views
from .scoring import views as scoring_views
from .flatpages import views as flatpages_views
from .admin import admin_site
from .forms import TeamAuthenticationForm, FormalPasswordResetForm
and context from other files:
# Path: src/ctf_gameserver/web/registration/views.py
# class TeamList(ListView):
# def register(request):
# def edit_team(request):
# def delete_team(request):
# def confirm_email(request):
# def mail_teams(request):
#
# Path: src/ctf_gameserver/web/scoring/views.py
# def scoreboard(request):
# def scoreboard_json(_):
# def scoreboard_json_ctftime(_):
# def service_status(request):
# def service_status_json(_):
# def teams_json(_):
# def service_history(request):
# def service_history_json(request):
# def append_result(next_team_id):
# def _get_status_descriptions():
#
# Path: src/ctf_gameserver/web/flatpages/views.py
# def flatpage(request, category=None, slug=''):
#
# Path: src/ctf_gameserver/web/admin.py
# class CTFAdminSite(admin.AdminSite):
# class CTFUserAdmin(UserAdmin):
# class TeamListFilter(admin.SimpleListFilter):
# def site_header(cls): # pylint: disable=no-self-argument
# def site_title(cls): # pylint: disable=no-self-argument
# def __init__(self, *args, **kwargs):
# def lookups(self, request, model_admin):
# def queryset(self, request, queryset):
# def user_has_team(self, user):
#
# Path: src/ctf_gameserver/web/forms.py
# class TeamAuthenticationForm(AuthenticationForm):
# """
# Custom variant of the login form that replaces "Username" with "Team name".
# """
#
# username = forms.CharField(max_length=254, label=_('Team name'))
#
# class FormalPasswordResetForm(PasswordResetForm):
# """
# Custom variant of the password reset form that replaces "Email" with "Formal email", adds a help text
# and adds the CTF's title to the email rendering context.
# """
#
# email = forms.EmailField(max_length=254, label=_('Formal email'), help_text='The address you stated '
# 'as authorative for sensitive requests.')
#
# def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name=None):
# context['competition_name'] = GameControl.get_instance().competition_name
#
# return super().send_mail(subject_template_name, email_template_name, context, from_email, to_email,
# html_email_template_name)
, which may include functions, classes, or code. Output only the next line. | form_class=FormalPasswordResetForm), |
Given snippet: <|code_start|> Sends an email containing the address confirmation link to the user associated with this form. As it
requires a User instance, it should only be called after the object has initially been saved.
Args:
request: The HttpRequest from which this function is being called
"""
competition_name = scoring_models.GameControl.get_instance().competition_name
context = {
'competition_name': competition_name,
'protocol': 'https' if request.is_secure() else 'http',
'domain': get_current_site(request),
'user': self.instance.pk,
'token': email_token_generator.make_token(self.instance)
}
message = loader.render_to_string('confirmation_mail.txt', context)
send_mail(competition_name+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
[self.instance.email])
class TeamForm(forms.ModelForm):
"""
The portion of the registration form which ends up in the 'Team' model. Designed to be used in
conjunction with UserForm.
"""
country = forms.ChoiceField(choices=[(name, name) for name in get_country_names()])
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models
and context:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
# """
# Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
# thumbnail image instead of the image's filename.
# """
#
# def get_template_substitution_values(self, value):
# return {
# 'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
# value.get_thumbnail_url(), str(value)),
# 'initial_url': conditional_escape(value.url),
# }
#
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
# def _make_hash_value(self, user, timestamp):
# def get_country_names():
which might include code, classes, or functions. Output only the next line. | model = Team |
Predict the next line after this snippet: <|code_start|> competition_name = scoring_models.GameControl.get_instance().competition_name
context = {
'competition_name': competition_name,
'protocol': 'https' if request.is_secure() else 'http',
'domain': get_current_site(request),
'user': self.instance.pk,
'token': email_token_generator.make_token(self.instance)
}
message = loader.render_to_string('confirmation_mail.txt', context)
send_mail(competition_name+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
[self.instance.email])
class TeamForm(forms.ModelForm):
"""
The portion of the registration form which ends up in the 'Team' model. Designed to be used in
conjunction with UserForm.
"""
country = forms.ChoiceField(choices=[(name, name) for name in get_country_names()])
class Meta:
model = Team
fields = ['informal_email', 'image', 'affiliation', 'country']
labels = {
'informal_email': _('Informal email')
}
widgets = {
<|code_end|>
using the current file's imports:
from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models
and any relevant context from other files:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
# """
# Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
# thumbnail image instead of the image's filename.
# """
#
# def get_template_substitution_values(self, value):
# return {
# 'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
# value.get_thumbnail_url(), str(value)),
# 'initial_url': conditional_escape(value.url),
# }
#
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
# def _make_hash_value(self, user, timestamp):
# def get_country_names():
. Output only the next line. | 'image': ClearableThumbnailImageInput |
Based on the snippet: <|code_start|> been changed. It should stay that way until the address is confirmed.
"""
user = super().save(commit=False)
if self.cleaned_data.get('password'):
user.set_password(self.cleaned_data['password'])
if 'email' in self.changed_data:
user.is_active = False
if commit:
user.save()
return user
def send_confirmation_mail(self, request):
"""
Sends an email containing the address confirmation link to the user associated with this form. As it
requires a User instance, it should only be called after the object has initially been saved.
Args:
request: The HttpRequest from which this function is being called
"""
competition_name = scoring_models.GameControl.get_instance().competition_name
context = {
'competition_name': competition_name,
'protocol': 'https' if request.is_secure() else 'http',
'domain': get_current_site(request),
'user': self.instance.pk,
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models
and context (classes, functions, sometimes code) from other files:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
# """
# Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
# thumbnail image instead of the image's filename.
# """
#
# def get_template_substitution_values(self, value):
# return {
# 'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
# value.get_thumbnail_url(), str(value)),
# 'initial_url': conditional_escape(value.url),
# }
#
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
# def _make_hash_value(self, user, timestamp):
# def get_country_names():
. Output only the next line. | 'token': email_token_generator.make_token(self.instance) |
Based on the snippet: <|code_start|>
def send_confirmation_mail(self, request):
"""
Sends an email containing the address confirmation link to the user associated with this form. As it
requires a User instance, it should only be called after the object has initially been saved.
Args:
request: The HttpRequest from which this function is being called
"""
competition_name = scoring_models.GameControl.get_instance().competition_name
context = {
'competition_name': competition_name,
'protocol': 'https' if request.is_secure() else 'http',
'domain': get_current_site(request),
'user': self.instance.pk,
'token': email_token_generator.make_token(self.instance)
}
message = loader.render_to_string('confirmation_mail.txt', context)
send_mail(competition_name+' email confirmation', message, settings.DEFAULT_FROM_EMAIL,
[self.instance.email])
class TeamForm(forms.ModelForm):
"""
The portion of the registration form which ends up in the 'Team' model. Designed to be used in
conjunction with UserForm.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.core.mail import send_mail
from django.template import loader
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from .models import Team
from .fields import ClearableThumbnailImageInput
from .util import email_token_generator, get_country_names
import ctf_gameserver.web.scoring.models as scoring_models
and context (classes, functions, sometimes code) from other files:
# Path: src/ctf_gameserver/web/registration/models.py
# class Team(models.Model):
# """
# Database representation of a team participating in the competition.
# This enhances the user model, where the team name, password, formal email address etc. are stored. It is
# particularly attuned to django.contrib.auth.models.User, but should work with other user models as well.
# """
#
# user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
#
# net_number = models.PositiveSmallIntegerField(null=True, unique=True)
# informal_email = models.EmailField(_('Informal email address'))
# image = ThumbnailImageField(upload_to=_gen_image_name, blank=True)
# affiliation = models.CharField(max_length=100, blank=True)
# country = models.CharField(max_length=100)
# # NOP teams don't get included in the scoring
# nop_team = models.BooleanField(default=False, db_index=True)
#
# class ActiveObjectsManager(models.Manager):
# def get_queryset(self):
# return super().get_queryset().filter(user__is_active=True)
#
# class ActiveNotNopObjectsManager(ActiveObjectsManager):
# def get_queryset(self):
# return super().get_queryset().filter(nop_team=False)
#
# # The first Manager in a class is used as default
# objects = models.Manager()
# # QuerySet that only returns Teams whose associated user object is not marked as inactive
# active_objects = ActiveObjectsManager()
# # QuerySet that only returns active Teams that are not marked as NOP team
# active_not_nop_objects = ActiveNotNopObjectsManager()
#
# def __str__(self):
# # pylint: disable=no-member
# return self.user.username
#
# Path: src/ctf_gameserver/web/registration/fields.py
# class ClearableThumbnailImageInput(ClearableFileInput):
# """
# Custom variant of the ClearableFileInput widget for rendering a ThumbnailImageField. It will display the
# thumbnail image instead of the image's filename.
# """
#
# def get_template_substitution_values(self, value):
# return {
# 'initial': format_html('<img class="clearable-input-image" src="{}" alt="{}" />',
# value.get_thumbnail_url(), str(value)),
# 'initial_url': conditional_escape(value.url),
# }
#
# Path: src/ctf_gameserver/web/registration/util.py
# class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
# def _make_hash_value(self, user, timestamp):
# def get_country_names():
. Output only the next line. | country = forms.ChoiceField(choices=[(name, name) for name in get_country_names()]) |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as_u={0.checked_as_undefined}, c_as_d={0.checked_as_defined}').format(var).encode('utf-8')
def _indent(lines, spaces):
indent = ' ' * spaces
return [indent + line for line in lines]
def _debug_repr(var):
rv = []
<|code_end|>
, predict the next line using imports from the current file:
from .model import Dictionary, Scalar, List, Unknown, Tuple
and context including class names, function names, and sometimes code from other files:
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
. Output only the next line. | if isinstance(var, (Dictionary, Tuple, List)): |
Based on the snippet: <|code_start|>def _indent(lines, spaces):
indent = ' ' * spaces
return [indent + line for line in lines]
def _debug_repr(var):
rv = []
if isinstance(var, (Dictionary, Tuple, List)):
if isinstance(var, Dictionary):
rv.append('Dictionary({}, {{'.format(_format_attrs(var)))
content = []
for key, value in sorted(var.iteritems()):
key_repr = key + ': '
value_repr = _debug_repr(value)
content.append(key_repr + value_repr[0])
content.extend(_indent(value_repr[1:], spaces=len(key_repr)))
rv.extend(_indent(content, spaces=4))
rv.append('})')
elif isinstance(var, Tuple):
rv.append('Tuple({},'.format(_format_attrs(var)))
for el in var.items:
el_repr = _debug_repr(el)
el_repr[-1] += ','
rv.extend(_indent(el_repr, spaces=4))
rv[-1] = rv[-1][:-1] # remove comma from the last tuple item
rv.append(')')
elif isinstance(var, List):
rv.append('List({},'.format(_format_attrs(var)))
rv.extend(_indent(_debug_repr(var.item), spaces=4))
rv.append(')')
<|code_end|>
, predict the immediate next line with the help of imports:
from .model import Dictionary, Scalar, List, Unknown, Tuple
and context (classes, functions, sometimes code) from other files:
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
. Output only the next line. | elif isinstance(var, Scalar): |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as_u={0.checked_as_undefined}, c_as_d={0.checked_as_defined}').format(var).encode('utf-8')
def _indent(lines, spaces):
indent = ' ' * spaces
return [indent + line for line in lines]
def _debug_repr(var):
rv = []
<|code_end|>
, predict the next line using imports from the current file:
from .model import Dictionary, Scalar, List, Unknown, Tuple
and context including class names, function names, and sometimes code from other files:
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
. Output only the next line. | if isinstance(var, (Dictionary, Tuple, List)): |
Predict the next line after this snippet: <|code_start|> return [indent + line for line in lines]
def _debug_repr(var):
rv = []
if isinstance(var, (Dictionary, Tuple, List)):
if isinstance(var, Dictionary):
rv.append('Dictionary({}, {{'.format(_format_attrs(var)))
content = []
for key, value in sorted(var.iteritems()):
key_repr = key + ': '
value_repr = _debug_repr(value)
content.append(key_repr + value_repr[0])
content.extend(_indent(value_repr[1:], spaces=len(key_repr)))
rv.extend(_indent(content, spaces=4))
rv.append('})')
elif isinstance(var, Tuple):
rv.append('Tuple({},'.format(_format_attrs(var)))
for el in var.items:
el_repr = _debug_repr(el)
el_repr[-1] += ','
rv.extend(_indent(el_repr, spaces=4))
rv[-1] = rv[-1][:-1] # remove comma from the last tuple item
rv.append(')')
elif isinstance(var, List):
rv.append('List({},'.format(_format_attrs(var)))
rv.extend(_indent(_debug_repr(var.item), spaces=4))
rv.append(')')
elif isinstance(var, Scalar):
rv = ['{}({})'.format(var.__class__.__name__, _format_attrs(var))]
<|code_end|>
using the current file's imports:
from .model import Dictionary, Scalar, List, Unknown, Tuple
and any relevant context from other files:
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
. Output only the next line. | elif isinstance(var, Unknown): |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as_u={0.checked_as_undefined}, c_as_d={0.checked_as_defined}').format(var).encode('utf-8')
def _indent(lines, spaces):
indent = ' ' * spaces
return [indent + line for line in lines]
def _debug_repr(var):
rv = []
<|code_end|>
, predict the next line using imports from the current file:
from .model import Dictionary, Scalar, List, Unknown, Tuple
and context including class names, function names, and sometimes code from other files:
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
. Output only the next line. | if isinstance(var, (Dictionary, Tuple, List)): |
Next line prediction: <|code_start|># coding: utf-8
def test_to_json_schema():
struct = Dictionary({
'list': List(
Tuple((
Dictionary({
<|code_end|>
. Use current file imports:
(from jinja2schema import core
from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String)
and context including class names, function names, or small code snippets from other files:
# Path: jinja2schema/core.py
# def parse(template, jinja2_env=None):
# def _ignore_constants(var):
# def infer_from_ast(ast, ignore_constants=True, config=Config()):
# def infer(template, config=Config()):
# def encode_common_attrs(self, var):
# def encode(self, var):
# def encode(self, var):
# def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder):
# class JSONSchemaDraft4Encoder(object):
# class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder):
#
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
#
# class Number(Scalar):
# """A number."""
# def __repr__(self):
# return '<number>'
#
# class Boolean(Scalar):
# """A boolean."""
# def __repr__(self):
# return '<boolean>'
#
# class String(Scalar):
# """A string."""
# def __repr__(self):
# return '<string>'
. Output only the next line. | 'field': Scalar(label='field', linenos=[3]), |
Next line prediction: <|code_start|># coding: utf-8
def test_to_json_schema():
struct = Dictionary({
'list': List(
Tuple((
Dictionary({
'field': Scalar(label='field', linenos=[3]),
}, label='a', linenos=[3]),
Scalar(label='b', linenos=[4])
), linenos=[2]),
label='list', linenos=[2]
),
<|code_end|>
. Use current file imports:
(from jinja2schema import core
from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tuple, Number, Boolean, String)
and context including class names, function names, or small code snippets from other files:
# Path: jinja2schema/core.py
# def parse(template, jinja2_env=None):
# def _ignore_constants(var):
# def infer_from_ast(ast, ignore_constants=True, config=Config()):
# def infer(template, config=Config()):
# def encode_common_attrs(self, var):
# def encode(self, var):
# def encode(self, var):
# def to_json_schema(var, jsonschema_encoder=JSONSchemaDraft4Encoder):
# class JSONSchemaDraft4Encoder(object):
# class StringJSONSchemaDraft4Encoder(JSONSchemaDraft4Encoder):
#
# Path: jinja2schema/model.py
# class Dictionary(Variable):
# """A dictionary.
#
# Implements some methods of Python :class:`dict`.
#
# .. automethod:: __setitem__
# .. automethod:: __getitem__
# .. automethod:: __delitem__
# .. automethod:: get
# .. automethod:: items
# .. automethod:: iteritems
# .. automethod:: keys
# .. automethod:: iterkeys
# .. automethod:: pop
# """
#
# def __init__(self, data=None, **kwargs):
# self.data = data or {}
# super(Dictionary, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Dictionary, self).__eq__(other) and self.data == other.data
#
# def __repr__(self):
# return pprint.pformat(self.data)
#
# def clone(self):
# rv = super(Dictionary, self).clone()
# rv.data = {}
# for k, v in _compat.iteritems(self.data):
# rv.data[k] = v.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, data=None, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(data, **kwargs)
#
# def __setitem__(self, key, value):
# self.data[key] = value
#
# def __getitem__(self, key):
# return self.data[key]
#
# def __delitem__(self, key):
# del self.data[key]
#
# def __contains__(self, key):
# return key in self.data
#
# def get(self, name, default=None):
# if name in self:
# return self[name]
# else:
# return default
#
# def items(self):
# return self.data.items()
#
# def iteritems(self):
# return _compat.iteritems(self.data)
#
# def keys(self):
# return self.data.keys()
#
# def iterkeys(self):
# return _compat.iterkeys(self.data)
#
# def pop(self, key, default=None):
# return self.data.pop(key, default)
#
# class Scalar(Variable):
# """A scalar. Either string, number, boolean or ``None``."""
# def __repr__(self):
# return '<scalar>'
#
# class List(Variable):
# """A list which items are of the same type.
#
# .. attribute:: item
#
# A structure of list items, subclass of :class:`Variable`.
# """
# def __init__(self, item, **kwargs):
# self.item = item
# super(List, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(List, self).__eq__(other) and self.item == other.item
#
# def __repr__(self):
# return pprint.pformat([self.item])
#
# def clone(self):
# rv = super(List, self).clone()
# rv.item = self.item.clone()
# return rv
#
# @classmethod
# def from_ast(cls, ast, item, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(item, **kwargs)
#
# class Unknown(Variable):
# """A variable which type is unknown."""
# def __repr__(self):
# return '<unknown>'
#
# class Tuple(Variable):
# """A tuple.
#
# .. attribute:: items
#
# A :class:`tuple` of :class:`Variable` instances or ``None`` if the tuple items are unknown.
#
# .. attribute:: items
#
# Whether new elements can be added to the tuple in the process of merge or not.
# """
# def __init__(self, items, **kwargs):
# self.items = tuple(items) if items is not None else None
# self.may_be_extended = kwargs.pop('may_be_extended', False)
# super(Tuple, self).__init__(**kwargs)
#
# def __eq__(self, other):
# return super(Tuple, self).__eq__(other) and self.items == other.items
#
# def __repr__(self):
# return pprint.pformat(self.items)
#
# def clone(self):
# rv = super(Tuple, self).clone()
# rv.items = self.items and tuple(s.clone() for s in self.items)
# return rv
#
# @classmethod
# def from_ast(cls, ast, items, **kwargs):
# kwargs = dict(cls._get_kwargs_from_ast(ast), **kwargs)
# return cls(items, **kwargs)
#
# class Number(Scalar):
# """A number."""
# def __repr__(self):
# return '<number>'
#
# class Boolean(Scalar):
# """A boolean."""
# def __repr__(self):
# return '<boolean>'
#
# class String(Scalar):
# """A string."""
# def __repr__(self):
# return '<string>'
. Output only the next line. | 'x': Unknown(may_be_defined=True), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.