Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
class ArrayCreateNode(Scene):
def run(self, **kwargs):
data_generator = kwargs['data_generator']
array = kwargs['container']
array.init(data_generator.quantity())
<|code_end|>
. Use current file imports:
(from alvi.client.containers import Array
from alvi.client.scenes.base import Scene)
and context including class names, function names, or small code snippets from other files:
# Path: alvi/client/containers/array.py
# class Array(base.Container):
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._nodes = []
#
# def init(self, size):
# if self._nodes:
# raise RuntimeError("Array was already initialized")
# for i in range(size):
# self._nodes.append(Node(self))
#
# def __getitem__(self, index):
# return self._nodes[index].value
#
# def __setitem__(self, index, value):
# self._nodes[index].value = value
#
# def size(self):
# return len(self._nodes)
#
# def create_marker(self, name, node_id):
# node = self._nodes[node_id]
# return Marker(name, node)
#
# def swap_nodes(self, index1, index2):
# array.swap_nodes(
# self._pipe,
# node1={'id': self._nodes[index1].id},
# node2={'id': self._nodes[index2].id}
# )
# self._nodes[index1], self._nodes[index2] = self._nodes[index2], self._nodes[index1]
#
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
. Output only the next line. | for i, value in enumerate(data_generator.values): |
Predict the next line after this snippet: <|code_start|>
class ArrayCreateNode(Scene):
def run(self, **kwargs):
data_generator = kwargs['data_generator']
array = kwargs['container']
array.init(data_generator.quantity())
for i, value in enumerate(data_generator.values):
array[i] = value
array.sync()
@classmethod
<|code_end|>
using the current file's imports:
from alvi.client.containers import Array
from alvi.client.scenes.base import Scene
and any relevant context from other files:
# Path: alvi/client/containers/array.py
# class Array(base.Container):
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._nodes = []
#
# def init(self, size):
# if self._nodes:
# raise RuntimeError("Array was already initialized")
# for i in range(size):
# self._nodes.append(Node(self))
#
# def __getitem__(self, index):
# return self._nodes[index].value
#
# def __setitem__(self, index, value):
# self._nodes[index].value = value
#
# def size(self):
# return len(self._nodes)
#
# def create_marker(self, name, node_id):
# node = self._nodes[node_id]
# return Marker(name, node)
#
# def swap_nodes(self, index1, index2):
# array.swap_nodes(
# self._pipe,
# node1={'id': self._nodes[index1].id},
# node2={'id': self._nodes[index2].id}
# )
# self._nodes[index1], self._nodes[index2] = self._nodes[index2], self._nodes[index1]
#
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
. Output only the next line. | def container_class(cls): |
Based on the snippet: <|code_start|>
class TreeMarker(TreeCreateNode):
def run(self, **kwargs):
super().run(**kwargs)
tree = kwargs['container']
#TODO removing marker0 variable causes test to fail
#looks like pipe message (see api.Pipe) is garbage collected too soon
#it is worth to investigate that... someday
marker0 = tree.create_marker("marker 0", self.nodes[2])
marker1 = tree.create_marker("marker 1", self.nodes[3])
<|code_end|>
, predict the immediate next line with the help of imports:
from alvi.tests.resources.client.local_python_client.scenes.tree.create_node import TreeCreateNode
and context (classes, functions, sometimes code) from other files:
# Path: alvi/tests/resources/client/local_python_client/scenes/tree/create_node.py
# class TreeCreateNode(Scene):
# class Form(Scene.Form):
# parents = forms.CharField(initial="0, 0, 1, 1, 4, 4")
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.nodes = []
#
# def run(self, **kwargs):
# tree = kwargs['container']
# data_generator = kwargs['data_generator']
# options = kwargs['options']
# parents = [int(parent) for parent in options['parents'].split(',')]
# value = next(data_generator.values)
# node = tree.create_root(value=value)
# self.nodes.append(node)
# #parents = [0, 0, 1, 1, 4, 4] # TODO this list could be passed from test case by custom form field
# for value, parent in zip(data_generator.values, parents):
# node = self.nodes[parent].children.create(value=value)
# self.nodes.append(node)
# tree.sync()
#
# @classmethod
# def container_class(cls):
# return Tree
. Output only the next line. | tree.sync() |
Continue the code snippet: <|code_start|>
class MergeSort(Sort):
def merge(self, array, left, mid, right):
temp = []
for i in range(left, right):
temp.append(array[i])
i = 0
j = right - mid
k = 0
while k < len(temp):
<|code_end|>
. Use current file imports:
from alvi.client.scenes.sort import Sort
and context (classes, functions, or code) from other files:
# Path: alvi/client/scenes/sort.py
# class Sort(base.Scene):
# """abstract scene, not to be used directly"""
# def swap(self, array, index_a, index_b):
# t = array[index_a]
# array[index_a] = array[index_b]
# array[index_b] = t
# array.stats.assignments += 2
#
# def init(self, array, n):
# array.stats.comparisons = 0
# array.stats.assignments = 0
# array.init(n)
# array.sync()
#
# def generate_points(self, array, data_generator):
# for i, value in enumerate(data_generator.values):
# array[i] = value
# array.sync()
#
# @abc.abstractmethod
# def sort(self, **kwargs):
# raise NotImplementedError
#
# def run(self, **kwargs):
# data_generator = kwargs['data_generator']
# array = kwargs['container']
# array.stats.elements = data_generator.quantity()
# self.init(array, data_generator.quantity())
# self.generate_points(array, data_generator)
# self.sort(**kwargs)
#
# @staticmethod
# def container_class():
# return alvi.client.containers.Array
#
# def test(self, array, test_case):
# for i in range(1, array.size()):
# previous = array[i-1]
# current = array[i]
# test_case.assertLessEqual(previous, current)
. Output only the next line. | if i >= mid - left: |
Given the following code snippet before the placeholder: <|code_start|>
class SequencedDataGenerator(DataGenerator):
class Form(DataGenerator.Form):
descending = forms.BooleanField(label="Descending", initial=True, required=False)
def _values(self):
return ((self.quantity()-i-1 if self.descending else i) for i in range(self.quantity())).__iter__()
<|code_end|>
, predict the next line using imports from the current file:
from alvi.client.data_generators.base import DataGenerator
from django import forms
and context including class names, function names, and sometimes code from other files:
# Path: alvi/client/data_generators/base.py
# class DataGenerator(metaclass=abc.ABCMeta):
# class Form(forms.Form):
# n = forms.IntegerField(min_value=1, max_value=256, label='Elements', initial=64)
#
# def __init__(self, options):
# form = self.Form(options)
# if not form.is_valid():
# raise forms.ValidationError(form.errors)
# self._options = form.cleaned_data
# self._values_iterator = None
#
# @property
# def values(self):
# """
# return iterator over self.quantity of subsequent generated values
# """
# if not self._values_iterator:
# self._values_iterator = self._values()
# return self._values_iterator
#
# @abc.abstractmethod
# def _values(self):
# """abstract method that shall return iterator to subsequent generated values"""
# raise NotImplementedError
#
# def quantity(self):
# return self._options['n']
. Output only the next line. | @property |
Predict the next line for this snippet: <|code_start|>
class GraphCreateNode(Scene):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nodes = []
def run(self, **kwargs):
data_generator = kwargs['data_generator']
graph = kwargs['container']
<|code_end|>
with the help of current file imports:
from alvi.client.scenes.base import Scene
from alvi.client.containers.graph import Graph
and context from other files:
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
#
# Path: alvi/client/containers/graph.py
# class Graph(base.Container):
# def create_node(self, value):
# return Node(self, None, value)
, which may contain function names, class names, or code. Output only the next line. | value = next(data_generator.values) |
Predict the next line for this snippet: <|code_start|>
class GraphCreateNode(Scene):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nodes = []
def run(self, **kwargs):
data_generator = kwargs['data_generator']
<|code_end|>
with the help of current file imports:
from alvi.client.scenes.base import Scene
from alvi.client.containers.graph import Graph
and context from other files:
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
#
# Path: alvi/client/containers/graph.py
# class Graph(base.Container):
# def create_node(self, value):
# return Node(self, None, value)
, which may contain function names, class names, or code. Output only the next line. | graph = kwargs['container'] |
Using the snippet: <|code_start|>
class TraverseTreeBreadthFirst(CreateTree):
def traverse(self, tree, node, traversed_marker, frontier_marker):
frontier = deque()
frontier.append(node)
frontier_marker.append(node)
tree.sync()
<|code_end|>
, determine the next line of code. You have imports:
from alvi.client.scenes.create_tree import CreateTree
from collections import deque
and context (class names, function names, or code) available:
# Path: alvi/client/scenes/create_tree.py
# class CreateTree(base.Scene):
# def run(self, **kwargs):
# tree = kwargs['container']
# data_generator = kwargs['data_generator']
# nodes = []
# value = next(data_generator.values)
# node = tree.create_root(value)
# nodes.append(node)
# tree.sync()
# for i, value in enumerate(data_generator.values):
# x = random.randint(0, i)
# parent = nodes[x]
# node = parent.children.create(value)
# nodes.append(node)
# tree.sync()
#
# @staticmethod
# def container_class():
# return alvi.client.containers.Tree
. Output only the next line. | while frontier: |
Based on the snippet: <|code_start|>
class TreeCreateNode(Scene):
class Form(Scene.Form):
parents = forms.CharField(initial="0, 0, 1, 1, 4, 4")
def __init__(self, *args, **kwargs):
<|code_end|>
, predict the immediate next line with the help of imports:
from alvi.client.scenes.base import Scene
from alvi.client.containers.tree import Tree
from django import forms
and context (classes, functions, sometimes code) from other files:
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
#
# Path: alvi/client/containers/tree.py
# class Tree(base.Container):
# @property
# def root(self):
# try:
# return self._root
# except AttributeError:
# return None
#
# def create_root(self, value):
# if self.root:
# raise RuntimeError("Cannot set root more that once")
# self._root = Node(self, None, value)
# return self._root
. Output only the next line. | super().__init__(*args, **kwargs) |
Predict the next line for this snippet: <|code_start|>
class TreeCreateNode(Scene):
class Form(Scene.Form):
parents = forms.CharField(initial="0, 0, 1, 1, 4, 4")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nodes = []
def run(self, **kwargs):
tree = kwargs['container']
data_generator = kwargs['data_generator']
<|code_end|>
with the help of current file imports:
from alvi.client.scenes.base import Scene
from alvi.client.containers.tree import Tree
from django import forms
and context from other files:
# Path: alvi/client/scenes/base.py
# class Scene(api.BaseScene):
# """base class for container based scenes"""
# class Form(forms.Form):
# pass
#
# @classmethod
# def run_wrapper(cls, scene, pipe, **kwargs):
# container = cls.container_class()(pipe)
# kwargs['container'] = container
# scene.run(**kwargs)
#
# @classmethod
# def container_name(cls):
# return cls.container_class().name()
#
# @classmethod
# @abc.abstractmethod
# def container_class(cls):
# raise NotImplementedError
#
# def test(self, container, test_case):
# logger.warning("skipping test for %s" % self.__class__.__name__)
#
# Path: alvi/client/containers/tree.py
# class Tree(base.Container):
# @property
# def root(self):
# try:
# return self._root
# except AttributeError:
# return None
#
# def create_root(self, value):
# if self.root:
# raise RuntimeError("Cannot set root more that once")
# self._root = Node(self, None, value)
# return self._root
, which may contain function names, class names, or code. Output only the next line. | options = kwargs['options'] |
Predict the next line after this snippet: <|code_start|>
class TreeAppendAndInsert(TreeCreateNode):
def run(self, **kwargs):
super().run(**kwargs)
tree = kwargs['container']
self.nodes[2].children.append(self.nodes[4])
tree.sync()
self.nodes[2].children.insert(0, self.nodes[3])
tree.sync()
self.nodes[2].children.append(self.nodes[5])
<|code_end|>
using the current file's imports:
from alvi.tests.resources.client.local_python_client.scenes.tree.create_node import TreeCreateNode
and any relevant context from other files:
# Path: alvi/tests/resources/client/local_python_client/scenes/tree/create_node.py
# class TreeCreateNode(Scene):
# class Form(Scene.Form):
# parents = forms.CharField(initial="0, 0, 1, 1, 4, 4")
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.nodes = []
#
# def run(self, **kwargs):
# tree = kwargs['container']
# data_generator = kwargs['data_generator']
# options = kwargs['options']
# parents = [int(parent) for parent in options['parents'].split(',')]
# value = next(data_generator.values)
# node = tree.create_root(value=value)
# self.nodes.append(node)
# #parents = [0, 0, 1, 1, 4, 4] # TODO this list could be passed from test case by custom form field
# for value, parent in zip(data_generator.values, parents):
# node = self.nodes[parent].children.create(value=value)
# self.nodes.append(node)
# tree.sync()
#
# @classmethod
# def container_class(cls):
# return Tree
. Output only the next line. | if __name__ == "__main__": |
Continue the code snippet: <|code_start|>
class SelectionSort(Sort):
def sort(self, **kwargs):
array = kwargs['container']
data_generator = kwargs['data_generator']
min_marker = array.create_marker("min", 0)
current_marker = array.create_marker("current", 0)
for current in range(0, data_generator.quantity()):
min = current
for j in range(current, data_generator.quantity()):
array.stats.comparisons += 1
if array[j] < array[min]:
<|code_end|>
. Use current file imports:
from alvi.client.scenes.sort import Sort
and context (classes, functions, or code) from other files:
# Path: alvi/client/scenes/sort.py
# class Sort(base.Scene):
# """abstract scene, not to be used directly"""
# def swap(self, array, index_a, index_b):
# t = array[index_a]
# array[index_a] = array[index_b]
# array[index_b] = t
# array.stats.assignments += 2
#
# def init(self, array, n):
# array.stats.comparisons = 0
# array.stats.assignments = 0
# array.init(n)
# array.sync()
#
# def generate_points(self, array, data_generator):
# for i, value in enumerate(data_generator.values):
# array[i] = value
# array.sync()
#
# @abc.abstractmethod
# def sort(self, **kwargs):
# raise NotImplementedError
#
# def run(self, **kwargs):
# data_generator = kwargs['data_generator']
# array = kwargs['container']
# array.stats.elements = data_generator.quantity()
# self.init(array, data_generator.quantity())
# self.generate_points(array, data_generator)
# self.sort(**kwargs)
#
# @staticmethod
# def container_class():
# return alvi.client.containers.Array
#
# def test(self, array, test_case):
# for i in range(1, array.size()):
# previous = array[i-1]
# current = array[i]
# test_case.assertLessEqual(previous, current)
. Output only the next line. | min = j |
Given the code snippet: <|code_start|>
class Quicksort(Sort):
def __init__(self):
self.qs_left = None
self.qs_right = None
self.part_partby = None
self.part_i = None
self.part_j = None
def sort(self, **kwargs):
array = kwargs['container']
self.qs_left = array.create_marker('qs_left', 0)
self.qs_right = array.create_marker('qs_right', 0)
self.part_partby = array.create_marker('partition_by', 0)
self.part_i = array.create_marker('partition_i', 0)
self.part_j = array.create_marker('partition_j', 0)
self._quicksort(array, 0, array.size()-1)
array.sync()
def _quicksort(self, A, p, r):
log.info('quicksort p=%d, r=%d' % (p, r))
if p < r:
self.qs_left.move(p)
self.qs_right.move(r)
q = self._partition(A, p, r)
log.info('q = %d'%q)
self._quicksort(A, p, q-1)
self._quicksort(A, q+1, r)
<|code_end|>
, generate the next line using the imports in this file:
from alvi.client.scenes.sort import Sort
import logging
and context (functions, classes, or occasionally code) from other files:
# Path: alvi/client/scenes/sort.py
# class Sort(base.Scene):
# """abstract scene, not to be used directly"""
# def swap(self, array, index_a, index_b):
# t = array[index_a]
# array[index_a] = array[index_b]
# array[index_b] = t
# array.stats.assignments += 2
#
# def init(self, array, n):
# array.stats.comparisons = 0
# array.stats.assignments = 0
# array.init(n)
# array.sync()
#
# def generate_points(self, array, data_generator):
# for i, value in enumerate(data_generator.values):
# array[i] = value
# array.sync()
#
# @abc.abstractmethod
# def sort(self, **kwargs):
# raise NotImplementedError
#
# def run(self, **kwargs):
# data_generator = kwargs['data_generator']
# array = kwargs['container']
# array.stats.elements = data_generator.quantity()
# self.init(array, data_generator.quantity())
# self.generate_points(array, data_generator)
# self.sort(**kwargs)
#
# @staticmethod
# def container_class():
# return alvi.client.containers.Array
#
# def test(self, array, test_case):
# for i in range(1, array.size()):
# previous = array[i-1]
# current = array[i]
# test_case.assertLessEqual(previous, current)
. Output only the next line. | def _partition(self, A, p, r): |
Continue the code snippet: <|code_start|>
class TestRandom(unittest.TestCase):
def test(self):
generator = RandomDataGenerator(dict(n=8))
<|code_end|>
. Use current file imports:
import unittest
from alvi.client.data_generators.random import RandomDataGenerator
and context (classes, functions, or code) from other files:
# Path: alvi/client/data_generators/random.py
# class RandomDataGenerator(DataGenerator):
# def _values(self):
# qty = self.quantity()
# return (random.randint(1, qty) for _ in range(qty)).__iter__()
. Output only the next line. | self.assertEquals(len(list(generator.values)), 8) |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
class TestGraph(TestContainer):
def test_create_node(self):
graph_page = pages.Graph(self._browser.driver, "GraphCreateNode")
graph_page.run(options=dict(n=4))
self.assertEqual(4, len(graph_page.svg.nodes), "create_node does not work properly")
self.assertEqual(4, len(graph_page.svg.edges), "create_edge does not work properly")
node_values = [int(element.find_element(By.CSS_SELECTOR, "text").text) for element in graph_page.svg.nodes]
node_values.sort()
created = node_values[:3]
self.assertEqual([0, 1, 2], created, "create_node does not work properly")
@unittest.skip("graph container does not support updating nodes at the moment")
def test_update_node(self):
graph_page = pages.Graph(self._browser.driver, "GraphUpdateNode")
graph_page.run()
updated = list(graph_page.svg.node_values)[3]
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import unittest
import alvi.tests.pages as pages
from selenium.webdriver.common.by import By
from alvi.tests.test_client.base import TestContainer
and context (classes, functions, sometimes code) from other files:
# Path: alvi/tests/test_client/base.py
# class TestContainer(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# config_path = os.path.join(os.path.dirname(__file__), "config.py")
# cls._backend = Backend.create(config_path)
# cls._client = Client.create()
# cls._browser = Browser.create()
#
# @classmethod
# def tearDownClass(cls):
# cls._browser.destroy()
# cls._client.destroy()
# cls._backend.destroy()
. Output only the next line. | self.assertEqual(10, updated, "update_node does not work properly") |
Predict the next line for this snippet: <|code_start|> # add any special contexts for actions (template snippets to include defined by ref to url param in template)
if action == self.PARAM_STR_ACTION_NEW_ACCOUNT: # new account
return self.create_or_edit_account(request)
elif action == self.PARAM_STR_ACTION_VIEW_ACCOUNTS or action == self.PARAM_STR_ACTION_VIEW_BUSINESS_ACCOUNTS: # view accounts
# SET UP SEARCH
self.MODELS_TO_SEARCH = {
'view_clients': ['invoicing.account'],
'view_client': ['invoicing.account']
}
if 'q' in request.GET:
return redirect(self.search_url)
# return the account_view method
return self.account_view(request)
elif action == self.PARAM_STR_ACTION_VIEW_SINGLE_ACCOUNT: # view single client
# set up search
self.MODELS_TO_SEARCH = {
'view_clients': ['invoicing.account'],
'view_client': ['invoicing.account']
}
if 'q' in request.GET:
return redirect(self.search_url)
# if requesting model id instead of account_id, get the account_id
model_id = helpers.sanitize_url_param(request.GET.get('id'))
account_id = helpers.sanitize_url_param(request.GET.get(
self.PARAM_STR_ID_ACCOUNT_ID))
if model_id:
try:
account_id = Account.objects.get(id=model_id).account_id
except Account.DoesNotExist:
account_id = None
<|code_end|>
with the help of current file imports:
import smtplib
import decimal
import html2text
from django.db.models import Q
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.template.loader import get_template
from django.test import RequestFactory
from weasyprint import HTML, CSS
from aninstance_framework import base, helpers, auth
from invoicing import forms
from invoicing.models import *
from django.conf import settings
from math import ceil
from django.db import IntegrityError
from aninstance_framework.search_forms import RightSidebarSearchForm
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext as __
from collections import OrderedDict
from django.utils import timezone as utc
from django.http import HttpResponse
from django.core.mail import EmailMultiAlternatives
from django.core.files.uploadedfile import SimpleUploadedFile
from django.template.loader import render_to_string
and context from other files:
# Path: aninstance_framework/base.py
# class AninstanceGenericView(AccessMixin, generic.View):
# NEVER_CACHE_TTL = 0 # set to 0 to prevent caching when this TTL is selected
# CACHE_TTL = settings.DEFAULT_CACHES_TTL
# TEMPLATE_NAME = None
# FOOTER_TEXT = None # None value means default is used, as defined in custom_context_processors.py
# PANEL_HEADING = None # None value means default is used, as defined in custom_context_processors.py
# PANEL_FOOTER = None # None value means default is used, as defined in custom_context_processors.py
# FRAGMENT_KEY = ''
# USE_CACHE = settings.DEFAULT_USE_TEMPLATE_FRAGMENT_CACHING # overridden in child views!
# PAGINATION = False
# PAGINATION_ITEMS_PER_PAGE = 5
# PARAM_STR = 'default_param'
# PAGE_STR = 'p'
# STATUS_MESSAGE = None
# AUTHENTICATION_REQUIRED = False # authorization not required for views by default. Overwrite in CVBs for auth.
# RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT = _('Search for')
# RIGHT_SIDEBAR_SEARCH_BUTTON_TEXT = _('Search')
# MODELS_TO_SEARCH = {
# '': [], # e.g. '<url_action_param'>: ['<app.model>', '<app.another_model>']
# }
# DEFAULT_FROM_EMAIL = settings.DEFAULT_FROM_EMAIL
# SITE_FQDN = settings.SITE_FQDN if not settings.DEBUG else 'localhost:8000'
# def __init__(self, **kwargs):
# def __str__(self):
# def view_cacher(self, request):
# def dispatch(self, request, *args, **kwargs):
# def get(self, request):
# def post(self, request):
#
# Path: aninstance_framework/helpers.py
# def set_session_data(request):
# def get_page(request):
# def get_client_ip(request):
# def utc_to_local(value, client_timezone, autoescape=True):
# def format_utc_str_for_template(value, autoescape=True):
# def local_to_utc(value):
# def is_num(value):
# def update_url_param(request, param_name):
# def remove_url_param(request, param):
# def strip_url_params(request):
# def sanitize_url_param(param):
# def sanitize_post_data(data):
# def format_data_for_display(data, file_formatting, media_type):
# def phrase_check(string):
#
# Path: aninstance_framework/auth.py
# def auth(self):
# return self.test_func()
#
# Path: invoicing/forms.py
# class AccountForm(ModelForm):
# class Meta:
# class InvoiceForm(ModelForm):
# class Meta:
# class MyNumberInput(TextInput):
# class InvoiceItemForm(ModelForm):
# class Meta:
# def __init__(self, *args, **kwargs):
# def clean_logo(self):
# def __init__(self, *args, **kwargs):
# def __init__(self, *args, **kwargs):
#
# Path: aninstance_framework/search_forms.py
# class RightSidebarSearchForm(SearchForm):
# # override elements of default SearchForm to add styling classes to fields
#
# def __init__(self, *args, **kwargs):
# super(RightSidebarSearchForm, self).__init__()
# self.placeholder = kwargs.get('placeholder') if 'placeholder' in kwargs else _('Search')
# self.fields['q'] = forms.CharField(required=False,
# label=_('Search for'),
# widget=forms.TextInput(attrs={'type': 'search',
# 'class': 'form-control',
# 'size': '15',
# 'placeholder': self.placeholder,
# }))
#
# def get_models(self):
# return self.models
#
# def search(self):
# # First, store the SearchQuerySet received from other processing.
# sqs = super(RightSidebarSearchForm, self).search()
# if not self.is_valid():
# return self.no_query_found()
# return sqs
, which may contain function names, class names, or code. Output only the next line. | return self.account_view(request, account_id=account_id) |
Predict the next line after this snippet: <|code_start|> 'default_site_logo_url': '/',
'default_footer_text': _('~ Aninstance Invoicing created by Dan Bright, at '
'<a href="https://www.aninstance.com">www.aninstance.com</a> | '
'<a href="https://www.github.com/aninstance/invoicing" target="_blank">'
'View on Github</a> ~'),
'default_site_name': DEFAULT_SITE_NAME,
'default_tag_line': _('Feel free to get in touch with bug reports, suggestions, or enquires about'
' subscribing to a managed instance: productions@aninstance.com'),
'default_main_footer': _('©{} {}. All Rights Reserved.'.format(datetime.datetime.now().strftime('%Y'),
DEFAULT_SITE_NAME.title())),
'default_panel_footer': '',
'default_right_sidebar_blurb': '',
'default_right_sidebar_image': '',
'default_right_sidebar_image_desc': '',
'default_right_sidebar_image_url': '',
'default_right_sidebar_links': None,
'default_left_sidebar_image': '{}/{}'.format(settings.STATIC_URL, 'images/aninstance_icon.png'),
'default_left_sidebar_image_desc': _('Aninstance.com'),
'default_left_sidebar_image_url': '/',
'default_head_title': _(
'Aninstance Invoicing | invoicing.aninstance.com'),
'default_client_ip_blurb': _('Your origin IP address appears to be'),
'no_client_ip_blurb': _('No client IP recorded ...'),
'page_register': PAGE_REGISTERY,
'client_timezone': '{}: {}'.format(_('Your timezone is set as'), request.session.get('django_timezone')),
'pagination': False,
'menu_items': PAGE_REGISTERY or None,
'footer_links': ' | '.join(
['<a href="/{}">{}</a>'.format(x.get('path'), x.get('menu_name').title())
for x in PAGE_REGISTERY if x.get('display_footer')]),
<|code_end|>
using the current file's imports:
import datetime
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from aninstance_framework.page_registry import PAGE_REGISTERY
and any relevant context from other files:
# Path: aninstance_framework/page_registry.py
# PAGE_REGISTERY = [
# {'menu_name': 'Invoicing',
# 'wp-id': None,
# 'path': 'invoicing',
# 'slug': 'invoicing',
# 'display_menu': True,
# 'display_footer': True
# },
# ]
. Output only the next line. | 'default_template_frag_cache_timeout': settings.DEFAULT_CACHES_TTL, |
Based on the snippet: <|code_start|>
urlpatterns = [
url(r'^$', views.Invoicing.as_view(), name='invoicing'),
]
if settings.DEBUG:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url, include
from invoicing import views
from django.conf.urls.static import static
from django.conf import settings
and context (classes, functions, sometimes code) from other files:
# Path: invoicing/views.py
# PDF_TYPES = {
# 'invoice': 'invoice',
# 'invoice_update': 'invoice_update',
# 'receipt': 'receipt'
# }
# DEFAULT_SITE_FQDN = base.SITE_FQDN
# DEFAULT_SITE_PROTO = API_PROTO = 'https' if not settings.DEBUG else 'http'
# API_BASE_URL = '{}/api/invoicing'.format(base.SITE_FQDN)
# PARAM_STR_ACTION_NEW_ACCOUNT = 'new_account'
# PARAM_STR_ACTION_EDIT_ACCOUNT = 'edit_account'
# PARAM_STR_ACTION_VIEW_ACCOUNTS = 'view_accounts'
# PARAM_STR_ACTION_VIEW_BUSINESS_ACCOUNTS = 'view_business_accounts'
# PARAM_STR_ACTION_VIEW_SINGLE_ACCOUNT = 'view_account'
# PARAM_STR_ACTION_EDIT_BUSINESS_ACCOUNT = 'edit_business_account'
# PARAM_STR_POST_ACTION_EDIT_BUSINESS_ACCOUNT = 'update_business_account'
# PARAM_STR_POST_ACTION_NEW_BUSINESS_ACCOUNT = 'new_account'
# PARAM_STR_POST_ACTION_EDIT_ACCOUNT = 'update_account'
# PARAM_STR_ACTION_PDF_GEN = 'pdf_gen'
# PARAM_STR_ID_INVOICE_NUMBER = 'invoice_number'
# PARAM_STR_ID_ACCOUNT_NUMBER = 'profile_number'
# PARAM_STR_ID_INVOICE_ITEM_NUMBER = 'invoice_item_number'
# PARAM_STR_ID_ACCOUNT_ID = 'account_id'
# PARAM_STR_ACTION_VIEW_INVOICES = 'view_invoices'
# PARAM_STR_ACTION_VIEW_INVOICE = 'view_invoice'
# PARAM_STR_ACTION_NEW_INVOICE = 'new_invoice'
# PARAM_STR_ACTION_EDIT_INVOICE = 'edit_invoice'
# PARAM_STR_ACTION_NEW_INVOICE_ITEM = 'new_invoice_item'
# PARAM_STR_ACTION_VIEW_INVOICE_ITEMS = 'view_invoice_items'
# PARAM_STR_ACTION_VIEW_INVOICE_ITEM = 'view_invoice_item'
# PARAM_STR_ACTION_EDIT_INVOICE_ITEM = 'edit_invoice_item'
# PARAM_STR_ACTION_USAGE = 'usage'
# PARAM_STR_ACTION_EMAIL_PDF = 'email_pdf'
# PARAM_STR_ACTION_EMAIL_SUCCESS = 'email_success'
# PARAM_STR_ACTION_EMAIL_FAIL = 'email_fail'
# PARAM_STR_PDF_TYPE = 'pdf_type'
# POST_ACTION_FIELD = 'form_hidden_field_post_action'
# POST_ACCOUNT_ID_FIELD = 'account_id'
# POST_INVOICE_NUMBER_ID_FIELD = 'invoice_number'
# POST_INVOICE_ITEM_ID_FIELD = 'invoice_item_id'
# TEMPLATE_NAME = 'invoicing/invoicing.html'
# FRAGMENT_KEY = 'invoicing'
# USE_CACHE = False
# PARAM_STR = 'action'
# RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT = _('Who?')
# RIGHT_SIDEBAR_SEARCH_BUTTON_TEXT = _('Find an account')
# PAGINATION_ITEMS_PER_PAGE = 5
# MODELS_TO_SEARCH = {'view_invoices': ['invoicing.invoice'],
# 'view_invoice': ['invoicing.invoice'],
# 'view_accounts': ['invoicing.account'],
# 'view_account': ['invoicing.account'],
# 'view_business_account': ['invoicing.account'],
# 'view_business_accounts': ['invoicing.account'],
# 'view_invoice_item': ['invoicing.invoiceitem'],
# 'view_invoice_items': ['invoicing.invoiceitem'],
# } # overwrite again in methods
# ITEMS_DASH_MENU = {'dropdown': [
# {'name': _('Dashboard'), 'action': 'dash'},
# {'name': _('View client accounts'),
# 'action': PARAM_STR_ACTION_VIEW_ACCOUNTS},
# {'name': _('Create new account'),
# 'action': PARAM_STR_ACTION_NEW_ACCOUNT},
# {'name': _('View invoice items'),
# 'action': PARAM_STR_ACTION_VIEW_INVOICE_ITEMS},
# {'name': _('View business profiles'),
# 'action': PARAM_STR_ACTION_VIEW_BUSINESS_ACCOUNTS},
# {'name': _('Docs: Usage instructions'),
# 'action': PARAM_STR_ACTION_USAGE},
# ],
# }
# TWOPLACES = Decimal('0.01')
# class Invoicing(base.AninstanceGenericView):
# def __init__(self, **kwargs):
# def get(self, request):
# def post(self, request):
# def default_view(self, request):
# def app_docs_view(self, request):
# def create_or_edit_account(self, request, account_id=None):
# def account_view(self, request, account_id=None):
# def new_invoice_view(self, request, client_account=None, inv_num=None):
# def invoice_view(self, request, inv_num=None, client_account=None, type=None, email=None):
# def invoice_items_view(self, request, single_item_id=None):
# def new_invoice_item_view(self, request, invoice_item=None):
# def pdf_view(self, request, invoice_number, pdf_type):
# def post_default(request): # if not a valid post request
# def post_new_account(self, request):
# def post_edit_account(self, request):
# def post_new_invoice(self, request):
# def post_edit_invoice(self, request):
# def post_new_invoice_item(self, request):
# def post_edit_invoice_item(self, request):
# def pdf_gen_or_fetch_or_email(invoice_number=None, type=None, email=None, regenerate=False):
# def _emailer(details=None):
# def invoice_sums(invoice_data=None, invoice=None):
# def apply_discount(subtotal, rate):
# def add_tax(subtotal, rate):
# def invoice_instance_to_dict(invoice=None):
. Output only the next line. | urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) |
Here is a snippet: <|code_start|> ''' note: pass functions like uuid.uuid4 and datatime.utcnow WITHOUT parentheses, so func called on each
new instance, than being called once when model imported and the value being used for every instance created'''
date_added = models.DateTimeField(default=timezone.now, blank=False, null=True, verbose_name='Date added',
editable=False)
account_id = models.CharField(max_length=255, blank=False, null=True, unique=True, default=uuid.uuid4,
verbose_name='Account ID')
account_name = models.CharField(max_length=255, blank=False, null=True, verbose_name=_('Account name'))
contact_title = models.CharField(max_length=3, blank=False, null=True, choices=ACCOUNT_CONTACT_TITLE_CHOICES,
default=ACCOUNT_CONTACT_TITLE_CHOICES[0][0], verbose_name=_('Contact title'))
contact_surname = models.CharField(max_length=255, blank=False, null=True, verbose_name=_('Contact surname'))
contact_first_name = models.CharField(max_length=255, blank=False, null=True, verbose_name=_('Contact first name'))
contact_email = models.EmailField(blank=False, null=True, verbose_name=_('Contact email'))
contact_phone = models.CharField(max_length=21, blank=True, null=True, verbose_name=_('Phone'))
company_name = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company name'))
company_website = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company website'))
addr_number = models.CharField(max_length=11, blank=True, null=True, verbose_name=_('Building #'))
addr_name = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Building name'))
addr_street = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Street'))
addr_locality = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Locality'))
addr_town = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Town'))
addr_county = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('County/State'))
addr_postcode = models.CharField(max_length=8, blank=True, null=True, verbose_name=_('Postcode/zip'))
account_status = models.CharField(max_length=21, blank=False, null=True, default=ACCOUNT_STATUS[0][0],
choices=ACCOUNT_STATUS, verbose_name=_('Account status'))
account_type = models.CharField(max_length=21, blank=False, null=True, default=ACCOUNT_TYPE[0][0],
choices=ACCOUNT_TYPE, verbose_name=_('Account type'))
logo = models.ImageField(upload_to=set_filename,
null=False, blank=True,
verbose_name=_('Business Logo'))
email_notifications = models.BooleanField(blank=False, null=False, default=False,
<|code_end|>
. Write the next line using the current file imports:
import os
import uuid
import re
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from decimal import Decimal
from django.utils import timezone
from invoicing import model_functions
from django.utils.translation import ugettext_lazy as _
from django.core.validators import DecimalValidator, MaxLengthValidator
and context from other files:
# Path: invoicing/model_functions.py
# def generate_invoice_random_id():
, which may include functions, classes, or code. Output only the next line. | verbose_name='Email notifications') |
Next line prediction: <|code_start|> url(r'^invoicing/', include('invoicing.urls')),
# Admin section
url(r'^adminardo/', admin.site.urls),
# Search
url(r'^search/?$', search.AninstanceSearchView.as_view(), name='search_view'),
### ROUTING
# Set timezone
url(r'^set_timezone/$', tz.SetTimeZone.as_view(), name='set_timezone'),
# Authorization
url(r'^accounts/password_change/$', auth_views.password_change,
{'template_name': 'registration/password_change_form.html'}, name='password_change'),
url(r'^accounts/password_change/done/$', auth_views.password_change_done,
{'template_name': 'registration/password_change_done.html'}, name='password_change_done'),
url(r'^accounts/password_reset/$', auth_views.password_reset,
{'template_name': 'registration/password_reset_form.html'}, name='password_reset'),
url(r'^accounts/password_reset/done$', auth_views.password_reset_done,
{'template_name': 'registration/password_reset_done.html'}, name='password_reset_done'),
url(r'^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm,
{'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'),
url(r'^accounts/reset/done$', auth_views.password_reset_complete,
{'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'),
url(r'^accounts/login/$', auth_views.login,
{'template_name': 'registration/login.html'}, name='login'),
url(r'^accounts/logout/$', auth_views.logout,
{'template_name': 'registration/logged_out.html'}, name='logout'),
### DEFAULT: Pages app urls.py serves everything not listed above - HAS TO COME LAST IN LIST!)
#url(r'^', include('pages.urls')),
### PROTECT MEDIA PROTECTED DIR
url(r'^media/protected/', RedirectView.as_view(url='/')),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from aninstance_framework import search, tz
from django.views.generic.base import RedirectView
from rest_framework import routers
from rest_framework.authtoken import views as rest_auth_views
from invoicing.api import ClientViewSet # API)
and context including class names, function names, or small code snippets from other files:
# Path: aninstance_framework/search.py
# class AninstanceSearchView(AccessMixin, SearchView):
# RESULTS_HEADING = 'Matching search results'
# def __init__(self, **kwargs):
# def get_queryset(self):
# def get_context_data(self, *args, **kwargs):
# def get(self, request, *args, **kwargs):
# def model_search_conf(self, request):
#
# Path: aninstance_framework/tz.py
# class SetTimeZone(generic.View):
# SUBMITTED_TEMPLATE = 'timezone.html'
# SUBMITTED_HEADING = 'Set your timezone'
# def get(self, request):
# def post(request):
#
# Path: invoicing/api.py
# class ClientViewSet(viewsets.ModelViewSet):
# # API endpoint for creation, editing or viewing of Client model
# queryset = Account.objects.all().order_by('account_name')
# serializer_class = ClientSerializer
#
#
# # # REFERENCE METHOD TO SHOW MODEL VIA API
# #
# #
# # def get_view_clients(self, request):
# # api_resource = 'client'
# # api_request_url = '{}://{}/{}'.format(
# # self.API_PROTO,
# # self.API_BASE_URL,
# # api_resource
# # )
# # try:
# # data = requests.get(api_request_url,
# # headers={'User-Agent': 'Magic Browser',
# # 'Authorization': 'Token {}'.format(
# # Token.objects.get_or_create(user=request.user)[0])
# # })
# # doc = data.json()
# # except Exception as e:
# # return http.HttpResponseNotFound(self.RESPONSE_INFO_API_CLIENT_ERROR)
# # # format for display
# # clients = []
# # try:
# # for client in doc.get('results'):
# # clients.append([{field[1]: client[field[0]]} for field in Client.CLIENT_VERBOSE_FIELDNAMES])
# # except TypeError:
# # self.context.update({'no_results': self.NO_CLIENTS_BLURB})
# # self.context.update({'clients': clients})
# # return render(request, self.TEMPLATE_NAME, self.context)
. Output only the next line. | url(r'^/?$', include('invoicing.urls')), |
Using the snippet: <|code_start|>
# REST API framework
router = routers.DefaultRouter()
router.register(r'invoicing/client', ClientViewSet)
# URL patterns
urlpatterns = [
### INCLUDES
# Invoicing app
url(r'^invoicing/', include('invoicing.urls')),
# Admin section
url(r'^adminardo/', admin.site.urls),
# Search
url(r'^search/?$', search.AninstanceSearchView.as_view(), name='search_view'),
### ROUTING
# Set timezone
url(r'^set_timezone/$', tz.SetTimeZone.as_view(), name='set_timezone'),
# Authorization
url(r'^accounts/password_change/$', auth_views.password_change,
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from aninstance_framework import search, tz
from django.views.generic.base import RedirectView
from rest_framework import routers
from rest_framework.authtoken import views as rest_auth_views
from invoicing.api import ClientViewSet # API
and context (class names, function names, or code) available:
# Path: aninstance_framework/search.py
# class AninstanceSearchView(AccessMixin, SearchView):
# RESULTS_HEADING = 'Matching search results'
# def __init__(self, **kwargs):
# def get_queryset(self):
# def get_context_data(self, *args, **kwargs):
# def get(self, request, *args, **kwargs):
# def model_search_conf(self, request):
#
# Path: aninstance_framework/tz.py
# class SetTimeZone(generic.View):
# SUBMITTED_TEMPLATE = 'timezone.html'
# SUBMITTED_HEADING = 'Set your timezone'
# def get(self, request):
# def post(request):
#
# Path: invoicing/api.py
# class ClientViewSet(viewsets.ModelViewSet):
# # API endpoint for creation, editing or viewing of Client model
# queryset = Account.objects.all().order_by('account_name')
# serializer_class = ClientSerializer
#
#
# # # REFERENCE METHOD TO SHOW MODEL VIA API
# #
# #
# # def get_view_clients(self, request):
# # api_resource = 'client'
# # api_request_url = '{}://{}/{}'.format(
# # self.API_PROTO,
# # self.API_BASE_URL,
# # api_resource
# # )
# # try:
# # data = requests.get(api_request_url,
# # headers={'User-Agent': 'Magic Browser',
# # 'Authorization': 'Token {}'.format(
# # Token.objects.get_or_create(user=request.user)[0])
# # })
# # doc = data.json()
# # except Exception as e:
# # return http.HttpResponseNotFound(self.RESPONSE_INFO_API_CLIENT_ERROR)
# # # format for display
# # clients = []
# # try:
# # for client in doc.get('results'):
# # clients.append([{field[1]: client[field[0]]} for field in Client.CLIENT_VERBOSE_FIELDNAMES])
# # except TypeError:
# # self.context.update({'no_results': self.NO_CLIENTS_BLURB})
# # self.context.update({'clients': clients})
# # return render(request, self.TEMPLATE_NAME, self.context)
. Output only the next line. | {'template_name': 'registration/password_change_form.html'}, name='password_change'), |
Given snippet: <|code_start|>
# REST API framework
router = routers.DefaultRouter()
router.register(r'invoicing/client', ClientViewSet)
# URL patterns
urlpatterns = [
### INCLUDES
# Invoicing app
url(r'^invoicing/', include('invoicing.urls')),
# Admin section
url(r'^adminardo/', admin.site.urls),
# Search
url(r'^search/?$', search.AninstanceSearchView.as_view(), name='search_view'),
### ROUTING
# Set timezone
url(r'^set_timezone/$', tz.SetTimeZone.as_view(), name='set_timezone'),
# Authorization
url(r'^accounts/password_change/$', auth_views.password_change,
{'template_name': 'registration/password_change_form.html'}, name='password_change'),
url(r'^accounts/password_change/done/$', auth_views.password_change_done,
{'template_name': 'registration/password_change_done.html'}, name='password_change_done'),
url(r'^accounts/password_reset/$', auth_views.password_reset,
{'template_name': 'registration/password_reset_form.html'}, name='password_reset'),
url(r'^accounts/password_reset/done$', auth_views.password_reset_done,
{'template_name': 'registration/password_reset_done.html'}, name='password_reset_done'),
url(r'^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm,
{'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'),
url(r'^accounts/reset/done$', auth_views.password_reset_complete,
{'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import views as auth_views
from aninstance_framework import search, tz
from django.views.generic.base import RedirectView
from rest_framework import routers
from rest_framework.authtoken import views as rest_auth_views
from invoicing.api import ClientViewSet # API
and context:
# Path: aninstance_framework/search.py
# class AninstanceSearchView(AccessMixin, SearchView):
# RESULTS_HEADING = 'Matching search results'
# def __init__(self, **kwargs):
# def get_queryset(self):
# def get_context_data(self, *args, **kwargs):
# def get(self, request, *args, **kwargs):
# def model_search_conf(self, request):
#
# Path: aninstance_framework/tz.py
# class SetTimeZone(generic.View):
# SUBMITTED_TEMPLATE = 'timezone.html'
# SUBMITTED_HEADING = 'Set your timezone'
# def get(self, request):
# def post(request):
#
# Path: invoicing/api.py
# class ClientViewSet(viewsets.ModelViewSet):
# # API endpoint for creation, editing or viewing of Client model
# queryset = Account.objects.all().order_by('account_name')
# serializer_class = ClientSerializer
#
#
# # # REFERENCE METHOD TO SHOW MODEL VIA API
# #
# #
# # def get_view_clients(self, request):
# # api_resource = 'client'
# # api_request_url = '{}://{}/{}'.format(
# # self.API_PROTO,
# # self.API_BASE_URL,
# # api_resource
# # )
# # try:
# # data = requests.get(api_request_url,
# # headers={'User-Agent': 'Magic Browser',
# # 'Authorization': 'Token {}'.format(
# # Token.objects.get_or_create(user=request.user)[0])
# # })
# # doc = data.json()
# # except Exception as e:
# # return http.HttpResponseNotFound(self.RESPONSE_INFO_API_CLIENT_ERROR)
# # # format for display
# # clients = []
# # try:
# # for client in doc.get('results'):
# # clients.append([{field[1]: client[field[0]]} for field in Client.CLIENT_VERBOSE_FIELDNAMES])
# # except TypeError:
# # self.context.update({'no_results': self.NO_CLIENTS_BLURB})
# # self.context.update({'clients': clients})
# # return render(request, self.TEMPLATE_NAME, self.context)
which might include code, classes, or functions. Output only the next line. | url(r'^accounts/login/$', auth_views.login, |
Predict the next line for this snippet: <|code_start|> self.CACHE_TTL = self.NEVER_CACHE_TTL
self.requested_page = 1
self.search_url = None
self.authentication_required = self.AUTHENTICATION_REQUIRED # change in child views to activate auth
self.auth_level = auth.USER_LEVEL.get('user') # default to required level being a basic user
self.context = {
'panel_heading': self.PANEL_HEADING,
'panel_footer': self.PANEL_FOOTER,
'cache_ttl': self.CACHE_TTL,
'pagination': self.PAGINATION,
'footer_text': self.FOOTER_TEXT,
'status_message': self.STATUS_MESSAGE,
'right_sidebar_search': False, # false by default
'form_right_search': RightSidebarSearchForm( # overwrite in child view to change placeholder text
placeholder=self.RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT),
'right_sidebar_search_button_text': self.RIGHT_SIDEBAR_SEARCH_BUTTON_TEXT,
}
def __str__(self):
return 'Default view for Aninstance project.'
def view_cacher(self, request):
if self.USE_CACHE:
# return cached version if cached variable set
cached_template_fragments = caches['template_fragments']
# child view overrides self.fragment_key
key = make_template_fragment_key(self.FRAGMENT_KEY, [request.get_full_path()])
if cached_template_fragments.get(key):
print('Returning cached response ...')
return render(request, self.TEMPLATE_NAME, self.context) # returned to view if cached response
<|code_end|>
with the help of current file imports:
from django.views import generic
from django.shortcuts import render
from django.core.cache import caches
from django.core.cache.utils import make_template_fragment_key
from django.conf import settings
from aninstance_framework.search_forms import RightSidebarSearchForm
from django.contrib.auth.mixins import AccessMixin
from aninstance_framework import helpers, auth
from django.utils.translation import ugettext_lazy as _
and context from other files:
# Path: aninstance_framework/search_forms.py
# class RightSidebarSearchForm(SearchForm):
# # override elements of default SearchForm to add styling classes to fields
#
# def __init__(self, *args, **kwargs):
# super(RightSidebarSearchForm, self).__init__()
# self.placeholder = kwargs.get('placeholder') if 'placeholder' in kwargs else _('Search')
# self.fields['q'] = forms.CharField(required=False,
# label=_('Search for'),
# widget=forms.TextInput(attrs={'type': 'search',
# 'class': 'form-control',
# 'size': '15',
# 'placeholder': self.placeholder,
# }))
#
# def get_models(self):
# return self.models
#
# def search(self):
# # First, store the SearchQuerySet received from other processing.
# sqs = super(RightSidebarSearchForm, self).search()
# if not self.is_valid():
# return self.no_query_found()
# return sqs
#
# Path: aninstance_framework/helpers.py
# def set_session_data(request):
# def get_page(request):
# def get_client_ip(request):
# def utc_to_local(value, client_timezone, autoescape=True):
# def format_utc_str_for_template(value, autoescape=True):
# def local_to_utc(value):
# def is_num(value):
# def update_url_param(request, param_name):
# def remove_url_param(request, param):
# def strip_url_params(request):
# def sanitize_url_param(param):
# def sanitize_post_data(data):
# def format_data_for_display(data, file_formatting, media_type):
# def phrase_check(string):
#
# Path: aninstance_framework/auth.py
# def auth(self):
# return self.test_func()
, which may contain function names, class names, or code. Output only the next line. | else: |
Given the code snippet: <|code_start|> PAGE_STR = 'p'
STATUS_MESSAGE = None
AUTHENTICATION_REQUIRED = False # authorization not required for views by default. Overwrite in CVBs for auth.
RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT = _('Search for')
RIGHT_SIDEBAR_SEARCH_BUTTON_TEXT = _('Search')
"""Define models to search
Overwrite accordingly in child CBV (otherwise authentication error thrown).
Indexes for models set in templates/search/indexes."""
MODELS_TO_SEARCH = {
'': [], # e.g. '<url_action_param'>: ['<app.model>', '<app.another_model>']
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.fragment_key = None # overridden with value in child view class
if not self.USE_CACHE:
self.CACHE_TTL = self.NEVER_CACHE_TTL
self.requested_page = 1
self.search_url = None
self.authentication_required = self.AUTHENTICATION_REQUIRED # change in child views to activate auth
self.auth_level = auth.USER_LEVEL.get('user') # default to required level being a basic user
self.context = {
'panel_heading': self.PANEL_HEADING,
'panel_footer': self.PANEL_FOOTER,
'cache_ttl': self.CACHE_TTL,
'pagination': self.PAGINATION,
'footer_text': self.FOOTER_TEXT,
'status_message': self.STATUS_MESSAGE,
'right_sidebar_search': False, # false by default
'form_right_search': RightSidebarSearchForm( # overwrite in child view to change placeholder text
<|code_end|>
, generate the next line using the imports in this file:
from django.views import generic
from django.shortcuts import render
from django.core.cache import caches
from django.core.cache.utils import make_template_fragment_key
from django.conf import settings
from aninstance_framework.search_forms import RightSidebarSearchForm
from django.contrib.auth.mixins import AccessMixin
from aninstance_framework import helpers, auth
from django.utils.translation import ugettext_lazy as _
and context (functions, classes, or occasionally code) from other files:
# Path: aninstance_framework/search_forms.py
# class RightSidebarSearchForm(SearchForm):
# # override elements of default SearchForm to add styling classes to fields
#
# def __init__(self, *args, **kwargs):
# super(RightSidebarSearchForm, self).__init__()
# self.placeholder = kwargs.get('placeholder') if 'placeholder' in kwargs else _('Search')
# self.fields['q'] = forms.CharField(required=False,
# label=_('Search for'),
# widget=forms.TextInput(attrs={'type': 'search',
# 'class': 'form-control',
# 'size': '15',
# 'placeholder': self.placeholder,
# }))
#
# def get_models(self):
# return self.models
#
# def search(self):
# # First, store the SearchQuerySet received from other processing.
# sqs = super(RightSidebarSearchForm, self).search()
# if not self.is_valid():
# return self.no_query_found()
# return sqs
#
# Path: aninstance_framework/helpers.py
# def set_session_data(request):
# def get_page(request):
# def get_client_ip(request):
# def utc_to_local(value, client_timezone, autoescape=True):
# def format_utc_str_for_template(value, autoescape=True):
# def local_to_utc(value):
# def is_num(value):
# def update_url_param(request, param_name):
# def remove_url_param(request, param):
# def strip_url_params(request):
# def sanitize_url_param(param):
# def sanitize_post_data(data):
# def format_data_for_display(data, file_formatting, media_type):
# def phrase_check(string):
#
# Path: aninstance_framework/auth.py
# def auth(self):
# return self.test_func()
. Output only the next line. | placeholder=self.RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT), |
Here is a snippet: <|code_start|> - Defaults to NO authentication required, and user level of a basic user.
"""
NEVER_CACHE_TTL = 0 # set to 0 to prevent caching when this TTL is selected
CACHE_TTL = settings.DEFAULT_CACHES_TTL
TEMPLATE_NAME = None
FOOTER_TEXT = None # None value means default is used, as defined in custom_context_processors.py
PANEL_HEADING = None # None value means default is used, as defined in custom_context_processors.py
PANEL_FOOTER = None # None value means default is used, as defined in custom_context_processors.py
FRAGMENT_KEY = ''
USE_CACHE = settings.DEFAULT_USE_TEMPLATE_FRAGMENT_CACHING # overridden in child views!
PAGINATION = False
PAGINATION_ITEMS_PER_PAGE = 5
PARAM_STR = 'default_param'
PAGE_STR = 'p'
STATUS_MESSAGE = None
AUTHENTICATION_REQUIRED = False # authorization not required for views by default. Overwrite in CVBs for auth.
RIGHT_SIDEBAR_SEARCH_PLACEHOLDER_TEXT = _('Search for')
RIGHT_SIDEBAR_SEARCH_BUTTON_TEXT = _('Search')
"""Define models to search
Overwrite accordingly in child CBV (otherwise authentication error thrown).
Indexes for models set in templates/search/indexes."""
MODELS_TO_SEARCH = {
'': [], # e.g. '<url_action_param'>: ['<app.model>', '<app.another_model>']
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.fragment_key = None # overridden with value in child view class
if not self.USE_CACHE:
self.CACHE_TTL = self.NEVER_CACHE_TTL
<|code_end|>
. Write the next line using the current file imports:
from django.views import generic
from django.shortcuts import render
from django.core.cache import caches
from django.core.cache.utils import make_template_fragment_key
from django.conf import settings
from aninstance_framework.search_forms import RightSidebarSearchForm
from django.contrib.auth.mixins import AccessMixin
from aninstance_framework import helpers, auth
from django.utils.translation import ugettext_lazy as _
and context from other files:
# Path: aninstance_framework/search_forms.py
# class RightSidebarSearchForm(SearchForm):
# # override elements of default SearchForm to add styling classes to fields
#
# def __init__(self, *args, **kwargs):
# super(RightSidebarSearchForm, self).__init__()
# self.placeholder = kwargs.get('placeholder') if 'placeholder' in kwargs else _('Search')
# self.fields['q'] = forms.CharField(required=False,
# label=_('Search for'),
# widget=forms.TextInput(attrs={'type': 'search',
# 'class': 'form-control',
# 'size': '15',
# 'placeholder': self.placeholder,
# }))
#
# def get_models(self):
# return self.models
#
# def search(self):
# # First, store the SearchQuerySet received from other processing.
# sqs = super(RightSidebarSearchForm, self).search()
# if not self.is_valid():
# return self.no_query_found()
# return sqs
#
# Path: aninstance_framework/helpers.py
# def set_session_data(request):
# def get_page(request):
# def get_client_ip(request):
# def utc_to_local(value, client_timezone, autoescape=True):
# def format_utc_str_for_template(value, autoescape=True):
# def local_to_utc(value):
# def is_num(value):
# def update_url_param(request, param_name):
# def remove_url_param(request, param):
# def strip_url_params(request):
# def sanitize_url_param(param):
# def sanitize_post_data(data):
# def format_data_for_display(data, file_formatting, media_type):
# def phrase_check(string):
#
# Path: aninstance_framework/auth.py
# def auth(self):
# return self.test_func()
, which may include functions, classes, or code. Output only the next line. | self.requested_page = 1 |
Given snippet: <|code_start|> '\nConverting Optical Map to SOMA Format\n' +\
'*'*50 + '\n'
sys.stderr.write(msg)
# Optical maps for chromosomes
# Remove all white space from restriction map names
for opMap in opMapList:
opMap.mapId = ''.join(opMap.mapId.split())
writeMaps(opMapList, opMapFileOut)
result = { 'enzyme' : enzyme,
'opMapList' : opMapList,
'opticalMapFile' : opMapFileOut}
return result
#############################################################################################
# Read an optical map in the Schwartz format
# Return a list of OpticalMapData instances
def readMapDataSchwartz(filename, verbose = False):
omaps = []
fin = open(filename)
mapGen = mapDataSchwartzGen(fin)
if verbose:
omaps = []
for map in mapGen:
omaps.append(map)
print 'Read map from chromosome %s with enzyme %s and %i fragments'%(map.mapId, map.enzyme, len(map.frags))
else:
omaps = [m for m in mapGen]
fin.close()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import re
from .MalignerMap import MalignerMap
from ..common import wrap_file_function
and context:
# Path: lib/malignpy/maps/MalignerMap.py
# class MalignerMap(object):
#
# def __init__(self, *args, **kwargs):
# if 'line' in kwargs:
# self.makeFromLine(kwargs['line'])
# else:
# self.makeFromAttributes(**kwargs)
# self.checkMap()
#
# # Create a MalignerMap from a line in maps file
# def makeFromLine(self, line):
# """
# Create a MalignerMap from a line in a SOMA Maps file.
# """
# fields = line.strip().split()
# self.mapId = fields[0]
# self.length = int(fields[1])
# self.numFrags = int(fields[2])
# self.frags = [int(f) for f in fields[3:]]
#
# # Create from mapId and frags attribute
# def makeFromAttributes(self, **kwargs):
# self.frags = list(kwargs['frags'])
# self.mapId = kwargs['mapId']
# self.numFrags = len(self.frags)
# self.length = sum(self.frags)
#
# # Add any other attributes from kwargs
# for attr in kwargs.iterkeys():
# if attr not in self.__dict__:
# self.__dict__[attr] = kwargs[attr]
#
# # write the MalignerMap to file
# def write(self, handle):
# f = handle
# fields = [self.mapId,
# str(self.length),
# str(len(self.frags))]
# fields.extend(str(frag) for frag in self.frags)
# outS = '\t'.join(fields) + '\n'
# f.write(outS)
#
# def get_data(self):
# """
# Return dict representation of a MalignerMap
# """
# fields = ['mapId', 'length', 'numFrags', 'frags']
# d = { k:getattr(self,k) for k in fields }
# return d
#
# # Check the consistency of the object
# def checkMap(self):
# if len(self.frags) != self.numFrags:
# raise Exception('MalignerMap attributes are inconsistent!')
#
# @property
# def name(self):
# return self.mapId
#
# Path: lib/malignpy/common/wrap_file_function.py
# class wrap_file_function(object):
# """
# Wrap a function which takes a file or a str as it's first argument.
# If a str is provided, replace the first argument of the wrapped function
# with a file handle, and close the file afterwards
#
# Example:
#
# @wrap_file_function('w')
# def write_hi(f):
# f.write('hi!\n')
#
# # This will write to already open file handle.
# f = open('f1.txt', 'w')
# write_hi(f)
# f.close()
#
# # This will open file f2.txt with mode 'w', write to it, and close the file.
# write_hi('f2.txt')
# """
#
# def __init__(self, *args):
# self.modes = args if args else ('r',)
#
# def __call__(self, func):
#
# @wraps(func)
# def wrapped(*args, **kwargs):
#
# close = [] # Files that should be closed
# files = [] # File handles that should be passed to func
# num_files = len(self.modes)
#
# for i, mode in enumerate(self.modes):
#
# fp = args[i]
#
# if isinstance(fp, str):
# fp = open(fp, mode)
# close.append(fp)
#
# files.append(fp)
#
# try:
#
# # Replace the files in args when calling func
# args = files + list(args[num_files:])
#
# # Make function call and return value
# return func(*args, **kwargs)
#
# finally:
#
# for fp in close:
# fp.close()
#
# return wrapped
which might include code, classes, or functions. Output only the next line. | return omaps |
Using the snippet: <|code_start|># Convert an optical map from the Schwartz lab format
# to the SOMA format
# opticalMapFile: optical map file in the Schwartz lab format
def convert_optical_maps(opticalMapFile, outputPfx):
opMapFileOut = '%s.opt'%outputPfx
msg = '\n'+'*'*50 + \
'\nReading Optical Map File %s\n'%opticalMapFile + \
'*'*50 + '\n'
sys.stderr.write(msg)
opMapList = readMapDataSchwartz(opticalMapFile)
enzymeSet = set(om.enzyme for om in opMapList)
if len(enzymeSet) > 1:
raise RuntimeError('Different enzymes used in the input optical map set!')
enzyme = opMapList[0].enzyme
msg = '\n'+'*'*50 +\
'\nConverting Optical Map to SOMA Format\n' +\
'*'*50 + '\n'
sys.stderr.write(msg)
# Optical maps for chromosomes
# Remove all white space from restriction map names
for opMap in opMapList:
opMap.mapId = ''.join(opMap.mapId.split())
writeMaps(opMapList, opMapFileOut)
result = { 'enzyme' : enzyme,
'opMapList' : opMapList,
'opticalMapFile' : opMapFileOut}
<|code_end|>
, determine the next line of code. You have imports:
import sys
import re
from .MalignerMap import MalignerMap
from ..common import wrap_file_function
and context (class names, function names, or code) available:
# Path: lib/malignpy/maps/MalignerMap.py
# class MalignerMap(object):
#
# def __init__(self, *args, **kwargs):
# if 'line' in kwargs:
# self.makeFromLine(kwargs['line'])
# else:
# self.makeFromAttributes(**kwargs)
# self.checkMap()
#
# # Create a MalignerMap from a line in maps file
# def makeFromLine(self, line):
# """
# Create a MalignerMap from a line in a SOMA Maps file.
# """
# fields = line.strip().split()
# self.mapId = fields[0]
# self.length = int(fields[1])
# self.numFrags = int(fields[2])
# self.frags = [int(f) for f in fields[3:]]
#
# # Create from mapId and frags attribute
# def makeFromAttributes(self, **kwargs):
# self.frags = list(kwargs['frags'])
# self.mapId = kwargs['mapId']
# self.numFrags = len(self.frags)
# self.length = sum(self.frags)
#
# # Add any other attributes from kwargs
# for attr in kwargs.iterkeys():
# if attr not in self.__dict__:
# self.__dict__[attr] = kwargs[attr]
#
# # write the MalignerMap to file
# def write(self, handle):
# f = handle
# fields = [self.mapId,
# str(self.length),
# str(len(self.frags))]
# fields.extend(str(frag) for frag in self.frags)
# outS = '\t'.join(fields) + '\n'
# f.write(outS)
#
# def get_data(self):
# """
# Return dict representation of a MalignerMap
# """
# fields = ['mapId', 'length', 'numFrags', 'frags']
# d = { k:getattr(self,k) for k in fields }
# return d
#
# # Check the consistency of the object
# def checkMap(self):
# if len(self.frags) != self.numFrags:
# raise Exception('MalignerMap attributes are inconsistent!')
#
# @property
# def name(self):
# return self.mapId
#
# Path: lib/malignpy/common/wrap_file_function.py
# class wrap_file_function(object):
# """
# Wrap a function which takes a file or a str as it's first argument.
# If a str is provided, replace the first argument of the wrapped function
# with a file handle, and close the file afterwards
#
# Example:
#
# @wrap_file_function('w')
# def write_hi(f):
# f.write('hi!\n')
#
# # This will write to already open file handle.
# f = open('f1.txt', 'w')
# write_hi(f)
# f.close()
#
# # This will open file f2.txt with mode 'w', write to it, and close the file.
# write_hi('f2.txt')
# """
#
# def __init__(self, *args):
# self.modes = args if args else ('r',)
#
# def __call__(self, func):
#
# @wraps(func)
# def wrapped(*args, **kwargs):
#
# close = [] # Files that should be closed
# files = [] # File handles that should be passed to func
# num_files = len(self.modes)
#
# for i, mode in enumerate(self.modes):
#
# fp = args[i]
#
# if isinstance(fp, str):
# fp = open(fp, mode)
# close.append(fp)
#
# files.append(fp)
#
# try:
#
# # Replace the files in args when calling func
# args = files + list(args[num_files:])
#
# # Make function call and return value
# return func(*args, **kwargs)
#
# finally:
#
# for fp in close:
# fp.close()
#
# return wrapped
. Output only the next line. | return result |
Continue the code snippet: <|code_start|>
# Extend the length of endy_position to make it touch the plane
# tangent at center_position.
endy_position /= numpy.dot(center_position, endy_position)
diff1 = endy_position-center_position
diff2 = local_north_position-center_position
cross_prod = numpy.cross(diff2, diff1)
length_cross_sq = numpy.dot(cross_prod, cross_prod)
normalization = numpy.dot(diff1, diff1) * numpy.dot(diff2, diff2)
# The length of the cross product equals the product of the lengths of
# the vectors times the sine of their angle.
# This is the angle between the y-axis and local north,
# measured eastwards.
# yoffset_angle = numpy.degrees(
# numpy.arcsin(numpy.sqrt(length_cross_sq/normalization)))
# The formula above is commented out because the angle computed
# in this way will always be 0<=yoffset_angle<=90.
# We'll use the dotproduct instead.
yoffs_rad = (numpy.arccos(numpy.dot(diff1, diff2) /
numpy.sqrt(normalization)))
# The multiplication with -sign_cor makes sure that the angle
# is measured eastwards (increasing RA), not westwards.
sign_cor = (numpy.dot(cross_prod, center_position) /
numpy.sqrt(length_cross_sq))
<|code_end|>
. Use current file imports:
import logging
import math
import numpy
import ndimage
from UserDict import DictMixin
from scipy import ndimage
from tkp.sourcefinder.deconv import deconv
from ..utility import coordinates
from ..utility.uncertain import Uncertain
from .gaussian import gaussian
from . import fitting
from . import utils
and context (classes, functions, or code) from other files:
# Path: tkp/utility/coordinates.py
# CORE_LAT = 52.9088
# CORE_LON = -6.8689
# ITRF_X = 3826577.066110000
# ITRF_Y = 461022.947639000
# ITRF_Z = 5064892.786
# SECONDS_IN_HOUR = 60**2
# SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR
# FK4 = "B1950 (FK4)"
# FK5 = "J2000 (FK5)"
# ORIGIN = 1
# WCS_ATTRS = ("crpix", "cdelt", "crval", "ctype", "cunit", "crota")
# def julian_date(time=None, modified=False):
# def mjd2datetime(mjd):
# def mjd2lst(mjd, position=None):
# def mjds2lst(mjds, position=None):
# def jd2lst(jd, position=None):
# def julian2unix(timestamp):
# def unix2julian(timestamp):
# def sec2deg(seconds):
# def sec2days(seconds):
# def sec2hms(seconds):
# def altaz(mjds, ra, dec, lat=CORE_LAT):
# def ratohms(radegs):
# def dectodms(decdegs):
# def propagate_sign(val1, val2, val3):
# def hmstora(rah, ram, ras):
# def dmstodec(decd, decm, decs):
# def angsep(ra1, dec1, ra2, dec2):
# def alphasep(ra1, ra2, dec1, dec2):
# def deltasep(dec1, dec2):
# def alpha(l, m, alpha0, delta0):
# def alpha_inflate(theta, decl):
# def delta(l, m, delta0):
# def l(ra, dec, cra, incr):
# def m(ra, dec, cra, cdec, incr):
# def lm_to_radec(ra0, dec0, l, m):
# def radec_to_lmn(ra0, dec0, ra, dec):
# def eq_to_gal(ra, dec):
# def gal_to_eq(lon_l, lat_b):
# def eq_to_cart(ra, dec):
# def coordsystem(name):
# def convert_coordsystem(ra, dec, insys, outsys):
# def __init__(self):
# def __setattr__(self, attrname, value):
# def __getattr__(self, attrname):
# def p2s(self, pixpos):
# def s2p(self, spatialpos):
# class CoordSystem(object):
# class WCS(object):
. Output only the next line. | yoffs_rad *= -sign_cor |
Here is a snippet: <|code_start|>from __future__ import absolute_import
logger = logging.getLogger(__name__)
def extract_metadatas(accessors, sigma, f):
logger.debug("running extract metadatas task")
<|code_end|>
. Write the next line using the current file imports:
import logging
import tkp.steps
from tkp.steps.misc import ImageMetadataForSort
from tkp.steps.forced_fitting import perform_forced_fits
and context from other files:
# Path: tkp/steps/misc.py
# def load_job_config(pipe_config):
# def dump_configs_to_logdir(log_dir, job_config, pipe_config):
# def check_job_configs_match(job_config_1, job_config_2):
# def setup_logging(log_dir, debug, use_colorlog,
# basename='trap'):
# def dump_database_backup(db_config, job_dir):
# def group_per_timestep(metadatas):
#
# Path: tkp/steps/forced_fitting.py
# def perform_forced_fits(fit_posns, fit_ids, accessor, extraction_params):
# """
# Perform forced source measurements on an image based on a list of
# positions.
#
# Args:
# fit_posns (tuple): List of (RA, Dec) tuples: Positions to be fit.
# fit_ids: List of identifiers for each requested fit position.
# image_path (str): path to image for measurements.
# extraction_params (dict): source extraction parameters, as a dictionary.
#
# Returns:
# tuple: A matched pair of lists (serialized_fits, ids), corresponding to
# successfully fitted positions.
# NB returned lists may be shorter than input lists
# if some fits are unsuccessful.
# """
# logger.debug("Forced fitting in image: %s" % (accessor.url))
#
# if not len(fit_ids):
# logging.debug("nothing to force fit")
# return [], []
#
# margin = extraction_params['margin']
# radius = extraction_params['extraction_radius_pix']
# back_size_x = extraction_params['back_size_x']
# back_size_y = extraction_params['back_size_y']
# data_image = sourcefinder_image_from_accessor(accessor, margin=margin,
# radius=radius,
# back_size_x=back_size_x,
# back_size_y=back_size_y)
#
# box_in_beampix = extraction_params['box_in_beampix']
# boxsize = box_in_beampix * max(data_image.beam[0], data_image.beam[1])
# fits = data_image.fit_fixed_positions( fit_posns, boxsize, ids=fit_ids)
# successful_fits, successful_ids = fits
# if successful_fits:
# serialized = [
# f.serialize(
# extraction_params['ew_sys_err'],
# extraction_params['ns_sys_err'])
# for f in successful_fits]
# return serialized, successful_ids
# else:
# return [], []
, which may include functions, classes, or code. Output only the next line. | return tkp.steps.persistence.extract_metadatas(accessors, sigma, f) |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
logger = logging.getLogger(__name__)
def extract_metadatas(accessors, sigma, f):
logger.debug("running extract metadatas task")
return tkp.steps.persistence.extract_metadatas(accessors, sigma, f)
def open_as_fits(images):
logger.debug("opening files as fits objects")
<|code_end|>
with the help of current file imports:
import logging
import tkp.steps
from tkp.steps.misc import ImageMetadataForSort
from tkp.steps.forced_fitting import perform_forced_fits
and context from other files:
# Path: tkp/steps/misc.py
# def load_job_config(pipe_config):
# def dump_configs_to_logdir(log_dir, job_config, pipe_config):
# def check_job_configs_match(job_config_1, job_config_2):
# def setup_logging(log_dir, debug, use_colorlog,
# basename='trap'):
# def dump_database_backup(db_config, job_dir):
# def group_per_timestep(metadatas):
#
# Path: tkp/steps/forced_fitting.py
# def perform_forced_fits(fit_posns, fit_ids, accessor, extraction_params):
# """
# Perform forced source measurements on an image based on a list of
# positions.
#
# Args:
# fit_posns (tuple): List of (RA, Dec) tuples: Positions to be fit.
# fit_ids: List of identifiers for each requested fit position.
# image_path (str): path to image for measurements.
# extraction_params (dict): source extraction parameters, as a dictionary.
#
# Returns:
# tuple: A matched pair of lists (serialized_fits, ids), corresponding to
# successfully fitted positions.
# NB returned lists may be shorter than input lists
# if some fits are unsuccessful.
# """
# logger.debug("Forced fitting in image: %s" % (accessor.url))
#
# if not len(fit_ids):
# logging.debug("nothing to force fit")
# return [], []
#
# margin = extraction_params['margin']
# radius = extraction_params['extraction_radius_pix']
# back_size_x = extraction_params['back_size_x']
# back_size_y = extraction_params['back_size_y']
# data_image = sourcefinder_image_from_accessor(accessor, margin=margin,
# radius=radius,
# back_size_x=back_size_x,
# back_size_y=back_size_y)
#
# box_in_beampix = extraction_params['box_in_beampix']
# boxsize = box_in_beampix * max(data_image.beam[0], data_image.beam[1])
# fits = data_image.fit_fixed_positions( fit_posns, boxsize, ids=fit_ids)
# successful_fits, successful_ids = fits
# if successful_fits:
# serialized = [
# f.serialize(
# extraction_params['ew_sys_err'],
# extraction_params['ns_sys_err'])
# for f in successful_fits]
# return serialized, successful_ids
# else:
# return [], []
, which may contain function names, class names, or code. Output only the next line. | return tkp.steps.persistence.paths_to_fits(images) |
Here is a snippet: <|code_start|>from __future__ import with_statement
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
<|code_end|>
. Write the next line using the current file imports:
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from tkp.db.model import Base
import os
import getpass
and context from other files:
# Path: tkp/db/model.py
# SCHEMA_VERSION = 40
# BLIND_FIT = 0
# FORCED_FIT = 1
# MONITORED_FIT = 2
# class Assocskyrgn(Base):
# class Assocxtrsource(Base):
# class Config(Base):
# class Dataset(Base):
# class Extractedsource(Base):
# class Frequencyband(Base):
# class Image(Base):
# class ImageData(Base):
# class Monitor(Base):
# class Newsource(Base):
# class Node(Base):
# class Rejection(Base):
# class Rejectreason(Base):
# class Runningcatalog(Base):
# class Varmetric(Base):
# class RunningcatalogFlux(Base):
# class Skyregion(Base):
# class Temprunningcatalog(Base):
# class Version(Base):
, which may include functions, classes, or code. Output only the next line. | def get_url(): |
Using the snippet: <|code_start|>
logger = logging.getLogger(__name__)
class AartfaacCasaImage(CasaImage):
def __init__(self, url, plane=0, beam=None):
super(AartfaacCasaImage, self).__init__(url, plane=0, beam=None)
table = casacore_table(self.url.encode(), ack=False)
<|code_end|>
, determine the next line of code. You have imports:
import logging
from tkp.accessors import CasaImage
from casacore.tables import table as casacore_table
and context (class names, function names, or code) available:
# Path: tkp/accessors/casaimage.py
# class CasaImage(DataAccessor):
# """
# Provides common functionality for pulling data from the CASA image format
#
# (Technically known as the 'MeasurementSet' format.)
#
# NB CasaImage does not provide tau_time or taustart_ts, as there was
# no clear standard for these metadata, so cannot be
# instantiated directly - subclass it and extract these attributes
# as appropriate to a given telescope.
# """
# def __init__(self, url, plane=0, beam=None):
# super(CasaImage, self).__init__()
# self.url = url
#
# # we don't want the table as a property since it makes the accessor
# # not serializable
# table = casacore_table(self.url.encode(), ack=False)
# self.data = self.parse_data(table, plane)
# self.wcs = self.parse_coordinates(table)
# self.centre_ra, self.centre_decl = self.parse_phase_centre(table)
# self.freq_eff, self.freq_bw = self.parse_frequency(table)
# self.pixelsize = self.parse_pixelsize()
#
# if beam:
# (bmaj, bmin, bpa) = beam
# else:
# bmaj, bmin, bpa = self.parse_beam(table)
# self.beam = self.degrees2pixels(
# bmaj, bmin, bpa, self.pixelsize[0], self.pixelsize[1])
#
# def parse_data(self, table, plane=0):
# """extract and massage data from CASA table"""
# data = table[0]['map'].squeeze()
# planes = len(data.shape)
# if planes != 2:
# msg = "received datacube with %s planes, assuming Stokes I and taking plane 0" % planes
# logger.warn(msg)
# warnings.warn(msg)
# data = data[plane, :, :]
# data = data.transpose()
# return data
#
# def parse_coordinates(self, table):
# """Returns a WCS object"""
# wcs = WCS()
# my_coordinates = table.getkeyword('coords')['direction0']
# wcs.crval = my_coordinates['crval']
# wcs.crpix = my_coordinates['crpix']
# wcs.cdelt = my_coordinates['cdelt']
# ctype = ['unknown', 'unknown']
# # What about other projections?!
# if my_coordinates['projection'] == "SIN":
# if my_coordinates['axes'][0] == "Right Ascension":
# ctype[0] = "RA---SIN"
# if my_coordinates['axes'][1] == "Declination":
# ctype[1] = "DEC--SIN"
# wcs.ctype = tuple(ctype)
# # Rotation, units? We better set a default
# wcs.crota = (0., 0.)
# wcs.cunit = table.getkeyword('coords')['direction0']['units']
# return wcs
#
# def parse_frequency(self, table):
# """extract frequency related information from headers"""
# freq_eff = table.getkeywords()['coords']['spectral2']['restfreq']
# freq_bw = table.getkeywords()['coords']['spectral2']['wcs']['cdelt']
# return freq_eff, freq_bw
#
# def parse_beam(self, table):
# """
# Returns:
# - Beam parameters, (semimajor, semiminor, parallactic angle) in
# (pixels,pixels, radians).
# """
# def ensure_degrees(quantity):
# if quantity['unit'] == 'deg':
# return quantity['value']
# elif quantity['unit'] == 'arcsec':
# return quantity['value'] / 3600
# elif quantity['unit'] == 'rad':
# return degrees(quantity['value'])
# else:
# raise Exception("Beam units (%s) unknown" % quantity['unit'])
#
# restoringbeam = table.getkeyword('imageinfo')['restoringbeam']
# bmaj = ensure_degrees(restoringbeam['major'])
# bmin = ensure_degrees(restoringbeam['minor'])
# bpa = ensure_degrees(restoringbeam['positionangle'])
# return bmaj, bmin, bpa
#
# def parse_phase_centre(self, table):
# # The units for the pointing centre are not given in either the image
# # cubeitself or in the ICD. Assume radians.
# # Note that we'll return the RA modulo 360 so it's always 0 <= RA < 360
# centre_ra, centre_decl = table.getkeyword('coords')['pointingcenter']['value']
# return degrees(centre_ra) % 360, degrees(centre_decl)
#
# def parse_taustartts(self, table):
# """
# Extract integration start-time from CASA table header.
#
# This applies to some CASA images (typically those created from uvFITS
# files) but not all, and so should be called for each sub-class.
#
# Arguments:
# table: MAIN table of CASA image.
#
# Returns:
# Time of image start as a instance of ``datetime.datetime``
# """
# obsdate = table.getkeyword('coords')['obsdate']['m0']['value']
# return mjd2datetime(obsdate)
#
#
# @staticmethod
# def unique_column_values(table, column_name):
# """
# Find all the unique values in a particular column of a CASA table.
#
# Arguments:
# - table: ``casacore.tables.table``
# - column_name: ``str``
#
# Returns:
# - ``numpy.ndarray`` containing unique values in column.
# """
# return table.query(
# columns=column_name, sortlist="unique %s" % (column_name)
# ).getcol(column_name)
. Output only the next line. | self.taustart_ts = self.parse_taustartts(table) |
Next line prediction: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
self.session.flush()
self.session.commit()
<|code_end|>
. Use current file imports:
(import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric)
and context including class names, function names, or small code snippets from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
. Output only the next line. | def test_execute_store_varmetric(self): |
Continue the code snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
self.session.flush()
self.session.commit()
<|code_end|>
. Use current file imports:
import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric
and context (classes, functions, or code) from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
. Output only the next line. | def test_execute_store_varmetric(self): |
Continue the code snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
<|code_end|>
. Use current file imports:
import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric
and context (classes, functions, or code) from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
. Output only the next line. | @classmethod |
Given the code snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric
and context (functions, classes, or occasionally code) from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
. Output only the next line. | self.session.flush() |
Given snippet: <|code_start|>
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
self.session.flush()
self.session.commit()
def test_execute_store_varmetric(self):
session = self.db.Session()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
def test_execute_store_varmetric_twice(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric
and context:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
which might include code, classes, or functions. Output only the next line. | session = self.db.Session() |
Predict the next line for this snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
<|code_end|>
with the help of current file imports:
import unittest
import logging
import tkp.db.model
import tkp.db
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
from tkp.steps.varmetric import execute_store_varmetric
and context from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
#
# Path: tkp/steps/varmetric.py
# def execute_store_varmetric(dataset_id, session=None):
# """
# Executes the storing varmetric function. Will create a database session
# if none is supplied.
#
# args:
# dataset_id: the ID of the dataset for which you want to store the
# varmetrics
# session: An optional SQLAlchemy session
# """
# if not session:
# database = Database()
# session = database.Session()
#
# dataset = Dataset(id=dataset_id)
# delete_ = del_duplicate_varmetric(session=session, dataset=dataset)
# session.execute(delete_)
# insert_ = store_varmetric(session, dataset=dataset)
# session.execute(insert_)
# session.commit()
, which may contain function names, class names, or code. Output only the next line. | def setUpClass(cls): |
Next line prediction: <|code_start|>
class TestStream(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.hdu = create_fits_hdu()
<|code_end|>
. Use current file imports:
(import unittest
import dateutil
import tkp.stream
from datetime import datetime
from tkp.testutil.stream_emu import create_fits_hdu, serialize_hdu, make_window)
and context including class names, function names, or small code snippets from other files:
# Path: tkp/testutil/stream_emu.py
# def create_fits_hdu():
# """
# Create a fake AARTFAAC file used as a base for the emulated servers. Could
# be anything but for now we just take the fits file from the test data.
#
# returns:
# astropy.io.fits.HDUList: a fits object
# """
# hdulist = fits.open(path.join(DATAPATH, 'accessors/aartfaac.fits'))
# hdu = hdulist[0]
# return hdu
#
# def serialize_hdu(hdu):
# """
# Serialize a fits object.
#
# args:
# hdu (astropy.io.fits.HDUList): a fits object
# returns:
# str: a serialized fits object.
# """
# data = struct.pack('=%sf' % hdu.data.size, *hdu.data.flatten('F'))
# header = hdu.header.tostring()
# return data, header
#
# def make_window(hdu):
# """
# Construct a complete serialised image including aartfaac header
#
# args:
# hdu (astropy.io.fits.HDUList): the first header
# returns:
# str: serialised fits file
# """
# result = StringIO.StringIO()
# data, fits_header = serialize_hdu(hdu)
# header = create_header(len(fits_header), len(data))
# result.write(header)
# result.write(fits_header)
# result.write(data)
# return result.getvalue()
. Output only the next line. | now = datetime.now() |
Predict the next line after this snippet: <|code_start|>
class TestStream(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.hdu = create_fits_hdu()
now = datetime.now()
cls.hdu.header['date-obs'] = now.isoformat()
def test_reconstruct(self):
data, header = serialize_hdu(self.hdu)
<|code_end|>
using the current file's imports:
import unittest
import dateutil
import tkp.stream
from datetime import datetime
from tkp.testutil.stream_emu import create_fits_hdu, serialize_hdu, make_window
and any relevant context from other files:
# Path: tkp/testutil/stream_emu.py
# def create_fits_hdu():
# """
# Create a fake AARTFAAC file used as a base for the emulated servers. Could
# be anything but for now we just take the fits file from the test data.
#
# returns:
# astropy.io.fits.HDUList: a fits object
# """
# hdulist = fits.open(path.join(DATAPATH, 'accessors/aartfaac.fits'))
# hdu = hdulist[0]
# return hdu
#
# def serialize_hdu(hdu):
# """
# Serialize a fits object.
#
# args:
# hdu (astropy.io.fits.HDUList): a fits object
# returns:
# str: a serialized fits object.
# """
# data = struct.pack('=%sf' % hdu.data.size, *hdu.data.flatten('F'))
# header = hdu.header.tostring()
# return data, header
#
# def make_window(hdu):
# """
# Construct a complete serialised image including aartfaac header
#
# args:
# hdu (astropy.io.fits.HDUList): the first header
# returns:
# str: serialised fits file
# """
# result = StringIO.StringIO()
# data, fits_header = serialize_hdu(hdu)
# header = create_header(len(fits_header), len(data))
# result.write(header)
# result.write(fits_header)
# result.write(data)
# return result.getvalue()
. Output only the next line. | hdulist = tkp.stream.reconstruct_fits(header, data) |
Continue the code snippet: <|code_start|>
class TestVersion(unittest.TestCase):
def setUp(self):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
<|code_end|>
. Use current file imports:
import unittest
from tkp.db.model import Version, SCHEMA_VERSION
from tkp.db.database import Database
from tkp.testutil.decorators import database_disabled
and context (classes, functions, or code) from other files:
# Path: tkp/db/model.py
# class Version(Base):
# __tablename__ = 'version'
#
# name = Column(String(12), primary_key=True)
# value = Column(Integer, nullable=False)
#
# SCHEMA_VERSION = 40
#
# Path: tkp/db/database.py
# class Database(object):
# """
# An object representing a database connection.
# """
# _connection = None
# _configured = False
# transaction = None
# cursor = None
# session = None
#
# # this makes this class a singleton
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = object.__new__(cls)
# return cls._instance
#
# def __init__(self, **kwargs):
# if self._configured:
# if kwargs:
# logger.warning("Not configuring pre-configured database")
# return
# elif not kwargs:
# kwargs = tkp.config.get_database_config()
#
# self.engine = kwargs['engine']
# self.database = kwargs['database']
# self.user = kwargs['user']
# self.password = kwargs['password']
# self.host = kwargs['host']
# self.port = kwargs['port']
# logger.info("Database config: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
# self._configured = True
#
# self.alchemy_engine = create_engine('%s://%s:%s@%s:%s/%s' %
# (self.engine,
# self.user,
# self.password,
# self.host,
# self.port,
# self.database),
# echo=False,
# poolclass=NullPool,
# )
# self.Session = sessionmaker(bind=self.alchemy_engine)
# self.session = self.Session()
#
# def connect(self, check=True):
# """
# connect to the configured database
#
# args:
# check (bool): check if schema version is correct
# """
# logger.info("connecting to database...")
#
# self._connection = self.alchemy_engine.connect()
# self._connection.execution_options(autocommit=False)
#
# if check:
# # Check that our database revision matches that expected by the
# # codebase.
# q = "SELECT value FROM version WHERE name='revision'"
# cursor = self.connection.execute(q)
# schema_version = cursor.fetchone()[0]
# if schema_version != SCHEMA_VERSION:
# error = ("Database version incompatibility (needed %d, got %d)" %
# (SCHEMA_VERSION, schema_version))
# logger.error(error)
# self._connection.close()
# self._connection = None
# raise Exception(error)
#
# logger.info("connected to: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
#
# @property
# def connection(self):
# """
# The database connection, will be created if it doesn't exists.
#
# This is a property to be backwards compatible with the rest of TKP.
#
# :return: a database connection
# """
# if not self._connection:
# self.connect()
#
# self.cursor = self._connection.connection.cursor()
#
# return self._connection
#
# def close(self):
# """
# close the connection if open
# """
# if self.session:
# self.session.close()
#
# if self._connection:
# self._connection.close()
#
# self._connection = None
#
# def vacuum(self, table):
# """
# Force a vacuum on a table, which removes dead rows. (Postgres only)
#
# Normally the auto vacuum process does this for you, but in some cases
# (for example when the table receives many insert and deletes) manual
# vacuuming is necessary for performance reasons.
#
# args:
# table: name of the table in the database you want to vacuum
# """
#
# if self.engine != "postgresql":
# return
#
# from psycopg2.extensions import (ISOLATION_LEVEL_AUTOCOMMIT,
# ISOLATION_LEVEL_READ_COMMITTED)
#
# # disable autocommit since can't vacuum in transaction
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
# cursor = self.connection.connection.cursor()
# cursor.execute("VACUUM ANALYZE %s" % table)
# # reset settings
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED)
#
# def execute(self, query, parameters={}, commit=False):
# if commit:
# self.transaction = self.connection.begin()
#
# try:
# cursor = self.connection.execute(query, parameters)
# if commit:
# self.transaction.commit()
# return cursor
# except Exception as e:
# logger.error("Query failed: %s. Query: %s." % (e, query % parameters))
# raise
#
# def rollback(self):
# if self.transaction:
# self.transaction.rollback()
#
# def reconnect(self):
# self._connection.close()
# self.connect()
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
. Output only the next line. | "in configuration.") |
Given the following code snippet before the placeholder: <|code_start|>
class TestVersion(unittest.TestCase):
def setUp(self):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from tkp.db.model import Version, SCHEMA_VERSION
from tkp.db.database import Database
from tkp.testutil.decorators import database_disabled
and context including class names, function names, and sometimes code from other files:
# Path: tkp/db/model.py
# class Version(Base):
# __tablename__ = 'version'
#
# name = Column(String(12), primary_key=True)
# value = Column(Integer, nullable=False)
#
# SCHEMA_VERSION = 40
#
# Path: tkp/db/database.py
# class Database(object):
# """
# An object representing a database connection.
# """
# _connection = None
# _configured = False
# transaction = None
# cursor = None
# session = None
#
# # this makes this class a singleton
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = object.__new__(cls)
# return cls._instance
#
# def __init__(self, **kwargs):
# if self._configured:
# if kwargs:
# logger.warning("Not configuring pre-configured database")
# return
# elif not kwargs:
# kwargs = tkp.config.get_database_config()
#
# self.engine = kwargs['engine']
# self.database = kwargs['database']
# self.user = kwargs['user']
# self.password = kwargs['password']
# self.host = kwargs['host']
# self.port = kwargs['port']
# logger.info("Database config: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
# self._configured = True
#
# self.alchemy_engine = create_engine('%s://%s:%s@%s:%s/%s' %
# (self.engine,
# self.user,
# self.password,
# self.host,
# self.port,
# self.database),
# echo=False,
# poolclass=NullPool,
# )
# self.Session = sessionmaker(bind=self.alchemy_engine)
# self.session = self.Session()
#
# def connect(self, check=True):
# """
# connect to the configured database
#
# args:
# check (bool): check if schema version is correct
# """
# logger.info("connecting to database...")
#
# self._connection = self.alchemy_engine.connect()
# self._connection.execution_options(autocommit=False)
#
# if check:
# # Check that our database revision matches that expected by the
# # codebase.
# q = "SELECT value FROM version WHERE name='revision'"
# cursor = self.connection.execute(q)
# schema_version = cursor.fetchone()[0]
# if schema_version != SCHEMA_VERSION:
# error = ("Database version incompatibility (needed %d, got %d)" %
# (SCHEMA_VERSION, schema_version))
# logger.error(error)
# self._connection.close()
# self._connection = None
# raise Exception(error)
#
# logger.info("connected to: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
#
# @property
# def connection(self):
# """
# The database connection, will be created if it doesn't exists.
#
# This is a property to be backwards compatible with the rest of TKP.
#
# :return: a database connection
# """
# if not self._connection:
# self.connect()
#
# self.cursor = self._connection.connection.cursor()
#
# return self._connection
#
# def close(self):
# """
# close the connection if open
# """
# if self.session:
# self.session.close()
#
# if self._connection:
# self._connection.close()
#
# self._connection = None
#
# def vacuum(self, table):
# """
# Force a vacuum on a table, which removes dead rows. (Postgres only)
#
# Normally the auto vacuum process does this for you, but in some cases
# (for example when the table receives many insert and deletes) manual
# vacuuming is necessary for performance reasons.
#
# args:
# table: name of the table in the database you want to vacuum
# """
#
# if self.engine != "postgresql":
# return
#
# from psycopg2.extensions import (ISOLATION_LEVEL_AUTOCOMMIT,
# ISOLATION_LEVEL_READ_COMMITTED)
#
# # disable autocommit since can't vacuum in transaction
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
# cursor = self.connection.connection.cursor()
# cursor.execute("VACUUM ANALYZE %s" % table)
# # reset settings
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED)
#
# def execute(self, query, parameters={}, commit=False):
# if commit:
# self.transaction = self.connection.begin()
#
# try:
# cursor = self.connection.execute(query, parameters)
# if commit:
# self.transaction.commit()
# return cursor
# except Exception as e:
# logger.error("Query failed: %s. Query: %s." % (e, query % parameters))
# raise
#
# def rollback(self):
# if self.transaction:
# self.transaction.rollback()
#
# def reconnect(self):
# self._connection.close()
# self.connect()
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
. Output only the next line. | raise unittest.SkipTest("Database functionality disabled " |
Given the code snippet: <|code_start|>
class TestVersion(unittest.TestCase):
def setUp(self):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from tkp.db.model import Version, SCHEMA_VERSION
from tkp.db.database import Database
from tkp.testutil.decorators import database_disabled
and context (functions, classes, or occasionally code) from other files:
# Path: tkp/db/model.py
# class Version(Base):
# __tablename__ = 'version'
#
# name = Column(String(12), primary_key=True)
# value = Column(Integer, nullable=False)
#
# SCHEMA_VERSION = 40
#
# Path: tkp/db/database.py
# class Database(object):
# """
# An object representing a database connection.
# """
# _connection = None
# _configured = False
# transaction = None
# cursor = None
# session = None
#
# # this makes this class a singleton
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = object.__new__(cls)
# return cls._instance
#
# def __init__(self, **kwargs):
# if self._configured:
# if kwargs:
# logger.warning("Not configuring pre-configured database")
# return
# elif not kwargs:
# kwargs = tkp.config.get_database_config()
#
# self.engine = kwargs['engine']
# self.database = kwargs['database']
# self.user = kwargs['user']
# self.password = kwargs['password']
# self.host = kwargs['host']
# self.port = kwargs['port']
# logger.info("Database config: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
# self._configured = True
#
# self.alchemy_engine = create_engine('%s://%s:%s@%s:%s/%s' %
# (self.engine,
# self.user,
# self.password,
# self.host,
# self.port,
# self.database),
# echo=False,
# poolclass=NullPool,
# )
# self.Session = sessionmaker(bind=self.alchemy_engine)
# self.session = self.Session()
#
# def connect(self, check=True):
# """
# connect to the configured database
#
# args:
# check (bool): check if schema version is correct
# """
# logger.info("connecting to database...")
#
# self._connection = self.alchemy_engine.connect()
# self._connection.execution_options(autocommit=False)
#
# if check:
# # Check that our database revision matches that expected by the
# # codebase.
# q = "SELECT value FROM version WHERE name='revision'"
# cursor = self.connection.execute(q)
# schema_version = cursor.fetchone()[0]
# if schema_version != SCHEMA_VERSION:
# error = ("Database version incompatibility (needed %d, got %d)" %
# (SCHEMA_VERSION, schema_version))
# logger.error(error)
# self._connection.close()
# self._connection = None
# raise Exception(error)
#
# logger.info("connected to: %s://%s@%s:%s/%s" % (self.engine,
# self.user,
# self.host,
# self.port,
# self.database))
#
# @property
# def connection(self):
# """
# The database connection, will be created if it doesn't exists.
#
# This is a property to be backwards compatible with the rest of TKP.
#
# :return: a database connection
# """
# if not self._connection:
# self.connect()
#
# self.cursor = self._connection.connection.cursor()
#
# return self._connection
#
# def close(self):
# """
# close the connection if open
# """
# if self.session:
# self.session.close()
#
# if self._connection:
# self._connection.close()
#
# self._connection = None
#
# def vacuum(self, table):
# """
# Force a vacuum on a table, which removes dead rows. (Postgres only)
#
# Normally the auto vacuum process does this for you, but in some cases
# (for example when the table receives many insert and deletes) manual
# vacuuming is necessary for performance reasons.
#
# args:
# table: name of the table in the database you want to vacuum
# """
#
# if self.engine != "postgresql":
# return
#
# from psycopg2.extensions import (ISOLATION_LEVEL_AUTOCOMMIT,
# ISOLATION_LEVEL_READ_COMMITTED)
#
# # disable autocommit since can't vacuum in transaction
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
# cursor = self.connection.connection.cursor()
# cursor.execute("VACUUM ANALYZE %s" % table)
# # reset settings
# self.connection.connection.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED)
#
# def execute(self, query, parameters={}, commit=False):
# if commit:
# self.transaction = self.connection.begin()
#
# try:
# cursor = self.connection.execute(query, parameters)
# if commit:
# self.transaction.commit()
# return cursor
# except Exception as e:
# logger.error("Query failed: %s. Query: %s." % (e, query % parameters))
# raise
#
# def rollback(self):
# if self.transaction:
# self.transaction.rollback()
#
# def reconnect(self):
# self._connection.close()
# self.connect()
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
. Output only the next line. | raise unittest.SkipTest("Database functionality disabled " |
Predict the next line for this snippet: <|code_start|> cls.db = tkp.db.Database()
def setUp(self):
self.session = self.db.Session()
self.fake_images = db_subs.generate_timespaced_dbimages_data(n_images=1)
self.dataset = tkp.db.DataSet(data={'description':
"Reject:" + self._testMethodName})
self.image = tkp.db.Image(data=self.fake_images[0],
dataset=self.dataset)
def tearDown(self):
self.session.rollback()
tkp.db.rollback()
pass
def test_rejectrms_and_unreject(self):
dbqual.reject(self.image.id,
dbqual.reject_reasons['rms'],
"10 times too high",
self.session)
image_rejections_q = self.session.query(Rejection).filter(
Rejection.image_id == self.image.id)
self.assertEqual(image_rejections_q.count(), 1)
dbqual.unreject(self.image.id, self.session)
self.assertEqual(image_rejections_q.count(), 0)
def test_unknownreason(self):
with self.assertRaises(IntegrityError):
dbqual.reject(self.image.id,
Rejectreason(id=666666, description="foobar"),
<|code_end|>
with the help of current file imports:
import unittest
import tkp.quality
import tkp.db
import tkp.db.quality as dbqual
import tkp.db.database
from tkp.db.model import Rejection, Rejectreason
from sqlalchemy.exc import DatabaseError, IntegrityError
from tkp.testutil.decorators import requires_database
from tkp.testutil import db_subs
and context from other files:
# Path: tkp/db/model.py
# class Rejection(Base):
# __tablename__ = 'rejection'
#
# id = Column(Integer, primary_key=True)
#
# image_id = Column('image', ForeignKey('image.id'), index=True)
# image = relationship('Image')
#
# # TO DO: Rename this column to 'rejectreason_id',
# # (rather than just 'rejectreason') so the model attribute matches
# # the SQL column name, avoiding the current confusing name-shadowing
# # between the SQL columns and the model attributes. (Issue #508)
# rejectreason_id = Column('rejectreason', ForeignKey('rejectreason.id'), index=True)
# rejectreason = relationship('Rejectreason')
#
# comment = Column(String(512))
#
# class Rejectreason(Base):
# __tablename__ = 'rejectreason'
#
# id = Column(Integer, primary_key=True)
# description = Column(String(512))
#
# Path: tkp/testutil/decorators.py
# def requires_database():
# if database_disabled():
# return unittest.skip("Database functionality disabled in configuration")
# return lambda func: func
#
# Path: tkp/testutil/db_subs.py
# def delete_test_database(database):
# def example_dbimage_data_dict(**kwargs):
# def generate_timespaced_dbimages_data(n_images,
# timedelta_between_images=datetime.timedelta(days=1),
# **kwargs):
# def example_extractedsource_tuple(ra=123.123, dec=10.5, # Arbitrarily picked defaults
# ra_fit_err=5. / 3600, dec_fit_err=6. / 3600,
# peak=15e-3, peak_err=5e-4,
# flux=15e-3, flux_err=5e-4,
# sigma=15.,
# beam_maj=100., beam_min=100., beam_angle=45.,
# ew_sys_err=20., ns_sys_err=20.,
# error_radius=10.0, fit_type=0,
# chisq=5., reduced_chisq=1.5):
# def deRuiter_radius(src1, src2):
# def lightcurve_metrics(src_list):
# def __init__(self,
# template_extractedsource,
# lightcurve,
# ):
# def value_at_dtime(self, dtime, image_rms):
# def simulate_extraction(self, db_image, extraction_type,
# rms_attribute='rms_min'):
# def insert_image_and_simulated_sources(dataset, image_params, mock_sources,
# new_source_sigma_margin,
# deruiter_radius=3.7):
# def get_newsources_for_dataset(dsid):
# def get_sources_filtered_by_final_variability(dataset_id,
# eta_min,
# v_min,
# # minpoints
# ):
# N = i + 1
# class MockSource(object):
, which may contain function names, class names, or code. Output only the next line. | comment="bad reason", |
Here is a snippet: <|code_start|> dbqual.reject_reasons['rms'],
"10 times too high",
self.session)
image_rejections_q = self.session.query(Rejection).filter(
Rejection.image_id == self.image.id)
self.assertEqual(image_rejections_q.count(), 1)
dbqual.unreject(self.image.id, self.session)
self.assertEqual(image_rejections_q.count(), 0)
def test_unknownreason(self):
with self.assertRaises(IntegrityError):
dbqual.reject(self.image.id,
Rejectreason(id=666666, description="foobar"),
comment="bad reason",
session=self.session)
self.session.flush()
def test_all_reasons_present_in_database(self):
for reason in dbqual.reject_reasons.values():
dbqual.reject(self.image.id, reason, "comment", self.session)
dbqual.unreject(self.image.id, self.session)
def test_isrejected(self):
dbqual.unreject(self.image.id, self.session)
self.assertFalse(dbqual.isrejected(self.image.id, self.session))
rms_reason = dbqual.reject_reasons['rms']
comment = "10 times too high"
reason_comment_str = "{}: {}".format(rms_reason.description, comment)
<|code_end|>
. Write the next line using the current file imports:
import unittest
import tkp.quality
import tkp.db
import tkp.db.quality as dbqual
import tkp.db.database
from tkp.db.model import Rejection, Rejectreason
from sqlalchemy.exc import DatabaseError, IntegrityError
from tkp.testutil.decorators import requires_database
from tkp.testutil import db_subs
and context from other files:
# Path: tkp/db/model.py
# class Rejection(Base):
# __tablename__ = 'rejection'
#
# id = Column(Integer, primary_key=True)
#
# image_id = Column('image', ForeignKey('image.id'), index=True)
# image = relationship('Image')
#
# # TO DO: Rename this column to 'rejectreason_id',
# # (rather than just 'rejectreason') so the model attribute matches
# # the SQL column name, avoiding the current confusing name-shadowing
# # between the SQL columns and the model attributes. (Issue #508)
# rejectreason_id = Column('rejectreason', ForeignKey('rejectreason.id'), index=True)
# rejectreason = relationship('Rejectreason')
#
# comment = Column(String(512))
#
# class Rejectreason(Base):
# __tablename__ = 'rejectreason'
#
# id = Column(Integer, primary_key=True)
# description = Column(String(512))
#
# Path: tkp/testutil/decorators.py
# def requires_database():
# if database_disabled():
# return unittest.skip("Database functionality disabled in configuration")
# return lambda func: func
#
# Path: tkp/testutil/db_subs.py
# def delete_test_database(database):
# def example_dbimage_data_dict(**kwargs):
# def generate_timespaced_dbimages_data(n_images,
# timedelta_between_images=datetime.timedelta(days=1),
# **kwargs):
# def example_extractedsource_tuple(ra=123.123, dec=10.5, # Arbitrarily picked defaults
# ra_fit_err=5. / 3600, dec_fit_err=6. / 3600,
# peak=15e-3, peak_err=5e-4,
# flux=15e-3, flux_err=5e-4,
# sigma=15.,
# beam_maj=100., beam_min=100., beam_angle=45.,
# ew_sys_err=20., ns_sys_err=20.,
# error_radius=10.0, fit_type=0,
# chisq=5., reduced_chisq=1.5):
# def deRuiter_radius(src1, src2):
# def lightcurve_metrics(src_list):
# def __init__(self,
# template_extractedsource,
# lightcurve,
# ):
# def value_at_dtime(self, dtime, image_rms):
# def simulate_extraction(self, db_image, extraction_type,
# rms_attribute='rms_min'):
# def insert_image_and_simulated_sources(dataset, image_params, mock_sources,
# new_source_sigma_margin,
# deruiter_radius=3.7):
# def get_newsources_for_dataset(dsid):
# def get_sources_filtered_by_final_variability(dataset_id,
# eta_min,
# v_min,
# # minpoints
# ):
# N = i + 1
# class MockSource(object):
, which may include functions, classes, or code. Output only the next line. | dbqual.reject(self.image.id, |
Predict the next line after this snippet: <|code_start|>
@requires_database()
class TestReject(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db = tkp.db.Database()
def setUp(self):
self.session = self.db.Session()
self.fake_images = db_subs.generate_timespaced_dbimages_data(n_images=1)
self.dataset = tkp.db.DataSet(data={'description':
"Reject:" + self._testMethodName})
self.image = tkp.db.Image(data=self.fake_images[0],
<|code_end|>
using the current file's imports:
import unittest
import tkp.quality
import tkp.db
import tkp.db.quality as dbqual
import tkp.db.database
from tkp.db.model import Rejection, Rejectreason
from sqlalchemy.exc import DatabaseError, IntegrityError
from tkp.testutil.decorators import requires_database
from tkp.testutil import db_subs
and any relevant context from other files:
# Path: tkp/db/model.py
# class Rejection(Base):
# __tablename__ = 'rejection'
#
# id = Column(Integer, primary_key=True)
#
# image_id = Column('image', ForeignKey('image.id'), index=True)
# image = relationship('Image')
#
# # TO DO: Rename this column to 'rejectreason_id',
# # (rather than just 'rejectreason') so the model attribute matches
# # the SQL column name, avoiding the current confusing name-shadowing
# # between the SQL columns and the model attributes. (Issue #508)
# rejectreason_id = Column('rejectreason', ForeignKey('rejectreason.id'), index=True)
# rejectreason = relationship('Rejectreason')
#
# comment = Column(String(512))
#
# class Rejectreason(Base):
# __tablename__ = 'rejectreason'
#
# id = Column(Integer, primary_key=True)
# description = Column(String(512))
#
# Path: tkp/testutil/decorators.py
# def requires_database():
# if database_disabled():
# return unittest.skip("Database functionality disabled in configuration")
# return lambda func: func
#
# Path: tkp/testutil/db_subs.py
# def delete_test_database(database):
# def example_dbimage_data_dict(**kwargs):
# def generate_timespaced_dbimages_data(n_images,
# timedelta_between_images=datetime.timedelta(days=1),
# **kwargs):
# def example_extractedsource_tuple(ra=123.123, dec=10.5, # Arbitrarily picked defaults
# ra_fit_err=5. / 3600, dec_fit_err=6. / 3600,
# peak=15e-3, peak_err=5e-4,
# flux=15e-3, flux_err=5e-4,
# sigma=15.,
# beam_maj=100., beam_min=100., beam_angle=45.,
# ew_sys_err=20., ns_sys_err=20.,
# error_radius=10.0, fit_type=0,
# chisq=5., reduced_chisq=1.5):
# def deRuiter_radius(src1, src2):
# def lightcurve_metrics(src_list):
# def __init__(self,
# template_extractedsource,
# lightcurve,
# ):
# def value_at_dtime(self, dtime, image_rms):
# def simulate_extraction(self, db_image, extraction_type,
# rms_attribute='rms_min'):
# def insert_image_and_simulated_sources(dataset, image_params, mock_sources,
# new_source_sigma_margin,
# deruiter_radius=3.7):
# def get_newsources_for_dataset(dsid):
# def get_sources_filtered_by_final_variability(dataset_id,
# eta_min,
# v_min,
# # minpoints
# ):
# N = i + 1
# class MockSource(object):
. Output only the next line. | dataset=self.dataset) |
Based on the snippet: <|code_start|> self.assertEqual(image_rejections_q.count(), 0)
def test_unknownreason(self):
with self.assertRaises(IntegrityError):
dbqual.reject(self.image.id,
Rejectreason(id=666666, description="foobar"),
comment="bad reason",
session=self.session)
self.session.flush()
def test_all_reasons_present_in_database(self):
for reason in dbqual.reject_reasons.values():
dbqual.reject(self.image.id, reason, "comment", self.session)
dbqual.unreject(self.image.id, self.session)
def test_isrejected(self):
dbqual.unreject(self.image.id, self.session)
self.assertFalse(dbqual.isrejected(self.image.id, self.session))
rms_reason = dbqual.reject_reasons['rms']
comment = "10 times too high"
reason_comment_str = "{}: {}".format(rms_reason.description, comment)
dbqual.reject(self.image.id,
rms_reason,
comment,
self.session)
self.assertEqual(dbqual.isrejected(self.image.id, self.session),
[ reason_comment_str ])
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import tkp.quality
import tkp.db
import tkp.db.quality as dbqual
import tkp.db.database
from tkp.db.model import Rejection, Rejectreason
from sqlalchemy.exc import DatabaseError, IntegrityError
from tkp.testutil.decorators import requires_database
from tkp.testutil import db_subs
and context (classes, functions, sometimes code) from other files:
# Path: tkp/db/model.py
# class Rejection(Base):
# __tablename__ = 'rejection'
#
# id = Column(Integer, primary_key=True)
#
# image_id = Column('image', ForeignKey('image.id'), index=True)
# image = relationship('Image')
#
# # TO DO: Rename this column to 'rejectreason_id',
# # (rather than just 'rejectreason') so the model attribute matches
# # the SQL column name, avoiding the current confusing name-shadowing
# # between the SQL columns and the model attributes. (Issue #508)
# rejectreason_id = Column('rejectreason', ForeignKey('rejectreason.id'), index=True)
# rejectreason = relationship('Rejectreason')
#
# comment = Column(String(512))
#
# class Rejectreason(Base):
# __tablename__ = 'rejectreason'
#
# id = Column(Integer, primary_key=True)
# description = Column(String(512))
#
# Path: tkp/testutil/decorators.py
# def requires_database():
# if database_disabled():
# return unittest.skip("Database functionality disabled in configuration")
# return lambda func: func
#
# Path: tkp/testutil/db_subs.py
# def delete_test_database(database):
# def example_dbimage_data_dict(**kwargs):
# def generate_timespaced_dbimages_data(n_images,
# timedelta_between_images=datetime.timedelta(days=1),
# **kwargs):
# def example_extractedsource_tuple(ra=123.123, dec=10.5, # Arbitrarily picked defaults
# ra_fit_err=5. / 3600, dec_fit_err=6. / 3600,
# peak=15e-3, peak_err=5e-4,
# flux=15e-3, flux_err=5e-4,
# sigma=15.,
# beam_maj=100., beam_min=100., beam_angle=45.,
# ew_sys_err=20., ns_sys_err=20.,
# error_radius=10.0, fit_type=0,
# chisq=5., reduced_chisq=1.5):
# def deRuiter_radius(src1, src2):
# def lightcurve_metrics(src_list):
# def __init__(self,
# template_extractedsource,
# lightcurve,
# ):
# def value_at_dtime(self, dtime, image_rms):
# def simulate_extraction(self, db_image, extraction_type,
# rms_attribute='rms_min'):
# def insert_image_and_simulated_sources(dataset, image_params, mock_sources,
# new_source_sigma_margin,
# deruiter_radius=3.7):
# def get_newsources_for_dataset(dsid):
# def get_sources_filtered_by_final_variability(dataset_id,
# eta_min,
# v_min,
# # minpoints
# ):
# N = i + 1
# class MockSource(object):
. Output only the next line. | def test_rejectreasons_sync(self): |
Predict the next line for this snippet: <|code_start|>
config = {
'engine': os.environ.get('TKP_DBENGINE', 'postgresql'),
'database': 'test_management',
'user': os.environ.get('TKP_DBUSER', getpass.getuser()),
'password': os.environ.get('TKP_DBPASSWORD', getpass.getuser()),
'host': os.environ.get('TKP_DBHOST', 'localhost'),
'port': os.environ.get('TKP_DBPORT', '5432'),
'yes': True,
'destroy': True,
<|code_end|>
with the help of current file imports:
import unittest
import tkp.db.sql.populate
import os
import getpass
from tkp.testutil.decorators import requires_test_db_managed
and context from other files:
# Path: tkp/testutil/decorators.py
# def requires_test_db_managed():
# """
# This decorator is used to disable tests that do potentially low level
# database management operations like destroy and create. You can enable
# these tests by setting the TKP_TESTDBMANAGEMENT environment variable.
# """
#
# if os.environ.get("TKP_TESTDBMANAGEMENT", False):
# return lambda func: func
# return unittest.skip("DB management tests disabled, TKP_TESTDBMANAGEMENT"
# " not set")
, which may contain function names, class names, or code. Output only the next line. | } |
Here is a snippet: <|code_start|> rms = tkp.quality.rms.rms(clip)
self.assertEqual(rms, tkp.quality.rms.rms_with_clipped_subregion(o))
def test_calculate_theoreticalnoise(self):
# Sample data from a LOFAR image header.
integration_time = 18654.3 # s
bandwidth = 200 * 10**3 # Hz
frequency = 66308593.75 # Hz
ncore = 23
nremote = 8
nintl = 0
configuration = "LBA_INNER"
self.assertAlmostEqual(
lofar.noise.noise_level(frequency, bandwidth, integration_time,
configuration, ncore, nremote, nintl),
0.01590154516819521 ,# with a calculator!
places=7
)
def test_rms_too_low(self):
theoretical_noise = 1
measured_rms = 1e-9
self.assertTrue(rms_invalid(measured_rms, theoretical_noise))
def test_rms_too_high(self):
theoretical_noise = 1
measured_rms = 1e9
self.assertTrue(rms_invalid(measured_rms, theoretical_noise))
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy
import tkp.quality.rms
import unittest
import tkp.quality
import tkp.telescope.lofar as lofar
from numpy.testing import assert_array_equal, assert_array_almost_equal
from tkp.quality.rms import rms_invalid
from tkp.testutil.decorators import requires_data
from tkp.testutil.data import DATAPATH
and context from other files:
# Path: tkp/quality/rms.py
# def rms_invalid(rms, noise, low_bound=1, high_bound=50):
# """
# Is the RMS value of an image outside the plausible range?
#
# :param rms: RMS value of an image, can be computed with
# tkp.quality.statistics.rms
# :param noise: Theoretical noise level of instrument, can be calculated with
# tkp.lofar.noise.noise_level
# :param low_bound: multiplied with noise to define lower threshold
# :param high_bound: multiplied with noise to define upper threshold
# :returns: True/False
# """
# if (rms < noise * low_bound) or (rms > noise * high_bound):
# ratio = rms / noise
# return "rms value (%s) is %s times theoretical noise (%s)" % \
# (nice_format(rms), nice_format(ratio), nice_format(noise))
# else:
# return False
#
# Path: tkp/testutil/decorators.py
# def requires_data(*args):
# for filename in args:
# if not os.path.exists(filename):
# return unittest.skip("Test data (%s) not available" % filename)
# return lambda func: func
, which may include functions, classes, or code. Output only the next line. | def test_rms_valid(self): |
Next line prediction: <|code_start|>
core_antennas = os.path.join(DATAPATH, 'lofar/CS001-AntennaArrays.conf')
intl_antennas = os.path.join(DATAPATH, 'lofar/DE601-AntennaArrays.conf')
remote_antennas = os.path.join(DATAPATH, 'lofar/RS106-AntennaArrays.conf')
class TestRms(unittest.TestCase):
def test_subrgion(self):
sub = tkp.quality.rms.subregion(numpy.ones((800, 800)))
self.assertEqual(sub.shape, (400, 400))
def test_rms(self):
self.assertEquals(tkp.quality.rms.rms(numpy.ones([4, 4]) * 4), 0)
def test_clip(self):
a = numpy.ones([50, 50]) * 10
a[20, 20] = 20
clipped = tkp.quality.rms.clip(a)
check = numpy.array([10] * (50*50-1))
assert_array_equal(clipped, check)
<|code_end|>
. Use current file imports:
(import os
import numpy
import tkp.quality.rms
import unittest
import tkp.quality
import tkp.telescope.lofar as lofar
from numpy.testing import assert_array_equal, assert_array_almost_equal
from tkp.quality.rms import rms_invalid
from tkp.testutil.decorators import requires_data
from tkp.testutil.data import DATAPATH)
and context including class names, function names, or small code snippets from other files:
# Path: tkp/quality/rms.py
# def rms_invalid(rms, noise, low_bound=1, high_bound=50):
# """
# Is the RMS value of an image outside the plausible range?
#
# :param rms: RMS value of an image, can be computed with
# tkp.quality.statistics.rms
# :param noise: Theoretical noise level of instrument, can be calculated with
# tkp.lofar.noise.noise_level
# :param low_bound: multiplied with noise to define lower threshold
# :param high_bound: multiplied with noise to define upper threshold
# :returns: True/False
# """
# if (rms < noise * low_bound) or (rms > noise * high_bound):
# ratio = rms / noise
# return "rms value (%s) is %s times theoretical noise (%s)" % \
# (nice_format(rms), nice_format(ratio), nice_format(noise))
# else:
# return False
#
# Path: tkp/testutil/decorators.py
# def requires_data(*args):
# for filename in args:
# if not os.path.exists(filename):
# return unittest.skip("Test data (%s) not available" % filename)
# return lambda func: func
. Output only the next line. | def test_rmsclippedsubregion(self): |
Predict the next line for this snippet: <|code_start|> self.session.flush()
self.session.commit()
def test_last_assoc_timestamps(self):
q = tkp.db.alchemy.varmetric._last_assoc_timestamps(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_assoc_per_band(self):
q = tkp.db.alchemy.varmetric._last_assoc_per_band(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_ts_fmax(self):
q = tkp.db.alchemy.varmetric._last_ts_fmax(self.session, self.dataset1)
r = self.session.query(q).all()[0]
self.assertEqual(r.max_flux, 0.01)
def test_newsrc_trigger(self):
q = tkp.db.alchemy.varmetric._newsrc_trigger(self.session, self.dataset1)
self.session.query(q).all()
def test_combined(self):
q = tkp.db.alchemy.varmetric._combined(self.session, self.dataset1)
r = list(self.session.query(q).all()[0])
r = [item for i, item in enumerate(r) if i not in (0, 5, 6, 10, 11, 16)]
shouldbe = [1.0, 1.0, 1.0, 1.0, 1, 0.0, 0.0, None, None, 0.01, 0.01]
self.assertEqual(r, shouldbe)
def test_calculate_varmetric(self):
<|code_end|>
with the help of current file imports:
import unittest
import logging
import tkp.db
import tkp.db.alchemy.varmetric
import tkp.db.model
from datetime import datetime, timedelta
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion, \
gen_lightcurve
from tkp.testutil.decorators import database_disabled
and context from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
, which may contain function names, class names, or code. Output only the next line. | r = tkp.db.alchemy.varmetric.calculate_varmetric(self.session, self.dataset1).all() |
Continue the code snippet: <|code_start|> lightcurve1 = gen_lightcurve(d1_b1, self.dataset1, skyregion1)
lightcurve2 = gen_lightcurve(d1_b2, self.dataset1, skyregion1)
lightcurve3 = gen_lightcurve(d2_b1, self.dataset2, skyregion2)
lightcurve4 = gen_lightcurve(d2_b2, self.dataset2, skyregion2)
db_objecsts = lightcurve1 + lightcurve2 + lightcurve3 + lightcurve4
self.session.add_all(db_objecsts)
self.session.flush()
self.session.commit()
def test_last_assoc_timestamps(self):
q = tkp.db.alchemy.varmetric._last_assoc_timestamps(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_assoc_per_band(self):
q = tkp.db.alchemy.varmetric._last_assoc_per_band(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_ts_fmax(self):
q = tkp.db.alchemy.varmetric._last_ts_fmax(self.session, self.dataset1)
r = self.session.query(q).all()[0]
self.assertEqual(r.max_flux, 0.01)
def test_newsrc_trigger(self):
q = tkp.db.alchemy.varmetric._newsrc_trigger(self.session, self.dataset1)
self.session.query(q).all()
def test_combined(self):
q = tkp.db.alchemy.varmetric._combined(self.session, self.dataset1)
<|code_end|>
. Use current file imports:
import unittest
import logging
import tkp.db
import tkp.db.alchemy.varmetric
import tkp.db.model
from datetime import datetime, timedelta
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion, \
gen_lightcurve
from tkp.testutil.decorators import database_disabled
and context (classes, functions, or code) from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
. Output only the next line. | r = list(self.session.query(q).all()[0]) |
Predict the next line for this snippet: <|code_start|>class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
# make 2 datasets with 2 lightcurves each. Lightcurves have different
# band
self.dataset1 = gen_dataset('sqlalchemy test')
self.dataset2 = gen_dataset('sqlalchemy test')
d1_b1 = gen_band(dataset=self.dataset1, central=150**6)
d1_b2 = gen_band(dataset=self.dataset1, central=160**6)
d2_b1 = gen_band(dataset=self.dataset2, central=150**6)
d2_b2 = gen_band(dataset=self.dataset2, central=160**6)
skyregion1 = gen_skyregion(self.dataset1)
skyregion2 = gen_skyregion(self.dataset2)
lightcurve1 = gen_lightcurve(d1_b1, self.dataset1, skyregion1)
lightcurve2 = gen_lightcurve(d1_b2, self.dataset1, skyregion1)
lightcurve3 = gen_lightcurve(d2_b1, self.dataset2, skyregion2)
lightcurve4 = gen_lightcurve(d2_b2, self.dataset2, skyregion2)
db_objecsts = lightcurve1 + lightcurve2 + lightcurve3 + lightcurve4
<|code_end|>
with the help of current file imports:
import unittest
import logging
import tkp.db
import tkp.db.alchemy.varmetric
import tkp.db.model
from datetime import datetime, timedelta
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion, \
gen_lightcurve
from tkp.testutil.decorators import database_disabled
and context from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
, which may contain function names, class names, or code. Output only the next line. | self.session.add_all(db_objecsts) |
Given snippet: <|code_start|>
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import logging
import tkp.db
import tkp.db.alchemy.varmetric
import tkp.db.model
from datetime import datetime, timedelta
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion, \
gen_lightcurve
from tkp.testutil.decorators import database_disabled
and context:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
which might include code, classes, or functions. Output only the next line. | self.session = self.db.Session() |
Next line prediction: <|code_start|> skyregion2 = gen_skyregion(self.dataset2)
lightcurve1 = gen_lightcurve(d1_b1, self.dataset1, skyregion1)
lightcurve2 = gen_lightcurve(d1_b2, self.dataset1, skyregion1)
lightcurve3 = gen_lightcurve(d2_b1, self.dataset2, skyregion2)
lightcurve4 = gen_lightcurve(d2_b2, self.dataset2, skyregion2)
db_objecsts = lightcurve1 + lightcurve2 + lightcurve3 + lightcurve4
self.session.add_all(db_objecsts)
self.session.flush()
self.session.commit()
def test_last_assoc_timestamps(self):
q = tkp.db.alchemy.varmetric._last_assoc_timestamps(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_assoc_per_band(self):
q = tkp.db.alchemy.varmetric._last_assoc_per_band(self.session, self.dataset1)
r = self.session.query(q).all()
self.assertEqual(len(r), 2) # we have two bands
def test_last_ts_fmax(self):
q = tkp.db.alchemy.varmetric._last_ts_fmax(self.session, self.dataset1)
r = self.session.query(q).all()[0]
self.assertEqual(r.max_flux, 0.01)
def test_newsrc_trigger(self):
q = tkp.db.alchemy.varmetric._newsrc_trigger(self.session, self.dataset1)
self.session.query(q).all()
def test_combined(self):
<|code_end|>
. Use current file imports:
(import unittest
import logging
import tkp.db
import tkp.db.alchemy.varmetric
import tkp.db.model
from datetime import datetime, timedelta
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion, \
gen_lightcurve
from tkp.testutil.decorators import database_disabled)
and context including class names, function names, or small code snippets from other files:
# Path: tkp/testutil/alchemy.py
# def gen_band(dataset, central=150**6, low=None, high=None):
# if not low:
# low = central * .9
# if not high:
# high = central * 1.1
# return tkp.db.model.Frequencyband(dataset=dataset, freq_low=low, freq_central=central,
# freq_high=high)
#
# def gen_dataset(description='A test dataset without a description'):
# return tkp.db.model.Dataset(process_start_ts=datetime.now(),
# description=description)
#
# def gen_skyregion(dataset):
# return tkp.db.model.Skyregion(dataset=dataset, centre_ra=1, centre_decl=1,
# xtr_radius=1, x=1, y=1, z=1)
#
# def gen_lightcurve(band, dataset, skyregion, datapoints=10):
# """
# returns: a list of created SQLAlchemy objects
# """
# start = datetime.fromtimestamp(0)
# ten_sec = timedelta(seconds=10)
# xtrsrcs = []
# images = []
# assocs = []
# for i in range(datapoints):
# taustart_ts = start + ten_sec * i
# image = gen_image(band, dataset, skyregion, taustart_ts)
#
# if i == 5:
# image.int = 10
# images.append(image)
# xtrsrcs.append(gen_extractedsource(image))
#
# # now we can make runningcatalog, we use first xtrsrc as trigger src
# runningcatalog = gen_runningcatalog(xtrsrcs[0], dataset)
# assocskyrgn = gen_assocskyrgn(runningcatalog, skyregion)
#
# # create the associations. Can't do this directly since the
# # association table has non nullable columns
# for xtrsrc in xtrsrcs:
# assocs.append(gen_assocxtrsource(runningcatalog, xtrsrc))
#
# newsource = gen_newsource(runningcatalog, xtrsrcs[5], images[4])
#
# # just return all db objects we created
# return [dataset, band, skyregion, runningcatalog, assocskyrgn, newsource] + \
# images + xtrsrcs + assocs
#
# Path: tkp/testutil/decorators.py
# def database_disabled():
# """Return ``True`` if the database is disabled for test purposes."""
# return os.environ.get("TKP_DISABLEDB", False)
. Output only the next line. | q = tkp.db.alchemy.varmetric._combined(self.session, self.dataset1) |
Based on the snippet: <|code_start|> def test_invalid_ephemeris(self):
dm = measures()
# No(?) ephemeris we're likely to come across is valid at MJD 0.
dm.do_frame(dm.epoch("UTC", "0.0d"))
self.assertFalse(tkp.quality.brightsource.check_for_valid_ephemeris(dm))
class TestBrightsource(unittest.TestCase):
def test_brightsource(self):
wcs = make_wcs(crval=(212.83583333333334, 52.2025))
image = SyntheticImage(
wcs = wcs,
tau_time=58141509,
taustart_ts=datetime.datetime(2012, 4, 6, 3, 42, 1),
freq_eff=128613281.25,
freq_bw=1940917.96875,
beam= (1.9211971282958984, 1.7578132629394532, 1.503223674140207),
)
# this image is not near any bright sources
result = tkp.quality.brightsource.is_bright_source_near(image)
self.assertFalse(result)
# there is nothing bright here
image.centre_ra = 90
image.centre_decl = 0
result = tkp.quality.brightsource.is_bright_source_near(image)
self.assertFalse(result)
# this is near the sun
<|code_end|>
, predict the immediate next line with the help of imports:
from math import degrees
from casacore.measures import measures
from tkp.testutil.mock import SyntheticImage, make_wcs
import unittest
import datetime
import tkp.quality.brightsource
import tkp.accessors
and context (classes, functions, sometimes code) from other files:
# Path: tkp/testutil/mock.py
# class SyntheticImage(DataAccessor):
# def __init__(self,
# wcs=None,
# data=None,
# beam=(1.5,1.5,0),
# freq_eff=150e6,
# freq_bw=2e6,
# tau_time=1800,
# taustart_ts=datetime.datetime(2015,1,1)
# ):
# """
# Generate a synthetic image for use in tests
#
# Args:
# wcs (tkp.utility.coordinates.WCS): WCS for the image.
# data (array_like): Data for the image. Default is a 512x512 array of
# zeroes.
# beam (tuple): Beamsemi-major axis (in pixels), semi-minor axis (pixels)
# and position angle (radians).
# freq_eff(float): Effective frequency of the image in Hz.
# That is, the mean frequency of all the visibility data which
# comprises this image.
# freq_bw(float): The frequency bandwidth of this image in Hz.
# tau_time(float): Total time on sky in seconds.
# taustart_ts(float): Timestamp of the first integration which
# constitutes part of this image. MJD in seconds.
# """
# self.url = "SyntheticImage"
# self.wcs = wcs
# if self.wcs is None:
# self.wcs = make_wcs()
# self.data = data
# if self.data is None:
# self.data = np.zeros((512,512))
# self.beam = beam
# self.freq_eff = freq_eff
# self.freq_bw = freq_bw
# self.tau_time = tau_time
# self.taustart_ts = taustart_ts
#
# self.pixelsize = self.parse_pixelsize()
# self.centre_ra, self.centre_decl = self.calculate_phase_centre()
#
#
# def calculate_phase_centre(self):
# x, y = self.data.shape
# centre_ra, centre_decl = self.wcs.p2s((x / 2, y / 2))
# return centre_ra, centre_decl
#
# def make_wcs(crval=None,
# cdelt=None,
# crpix=None
# ):
# """
# Make a WCS object for insertion into a synthetic image.
#
# Args:
# crval (tuple): Tuple of (RA, Dec) in decimal degrees at the reference
# position.
# crpix (tuple): Tuple of (x,y) co-ordinates describing the reference
# pixel location corresponding to the crval sky-position.
# cdelt (tuple): Tuple of (cdelt0, cdelt1) in decimal degrees.
# This is the pixel width in degrees of arc, but not necessarily
# aligned to RA, Dec unless `crota` is (0,0). If that *is* the case,
# then typically cdelt0 is negative since the x-axis is in direction
# of West (decreasing RA).
#
# """
# # For any arguments not set we simply assign an arbitrary valid value:
# if crval is None:
# crval = 100., 45.
# if cdelt is None:
# pixel_width_arcsec = 40
# pixel_width_deg = pixel_width_arcsec / 3600.
# cdelt = (-pixel_width_deg, pixel_width_deg)
# if crpix is None:
# crpix = (256.0, 256.0)
# wcs = WCS()
# wcs.cdelt = cdelt
# wcs.crota = (0.0, 0.0)
# wcs.crpix = crpix
# wcs.crval = crval
# wcs.ctype = ('RA---SIN', 'DEC--SIN')
# wcs.cunit = ('deg', 'deg')
# return wcs
. Output only the next line. | image.centre_ra = 0 |
Given snippet: <|code_start|>class TestEphemeris(unittest.TestCase):
# Tests whether we can correctly identify that an ephemeris is invalid.
# I don't think it's possible to test that we can correctly identify a
# valid ephemeris, because we can't be sure that the user actually has one
# on disk (unless we ship one with the test case, but I don't think it's
# worth it.)
def test_invalid_ephemeris(self):
dm = measures()
# No(?) ephemeris we're likely to come across is valid at MJD 0.
dm.do_frame(dm.epoch("UTC", "0.0d"))
self.assertFalse(tkp.quality.brightsource.check_for_valid_ephemeris(dm))
class TestBrightsource(unittest.TestCase):
def test_brightsource(self):
wcs = make_wcs(crval=(212.83583333333334, 52.2025))
image = SyntheticImage(
wcs = wcs,
tau_time=58141509,
taustart_ts=datetime.datetime(2012, 4, 6, 3, 42, 1),
freq_eff=128613281.25,
freq_bw=1940917.96875,
beam= (1.9211971282958984, 1.7578132629394532, 1.503223674140207),
)
# this image is not near any bright sources
result = tkp.quality.brightsource.is_bright_source_near(image)
self.assertFalse(result)
# there is nothing bright here
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from math import degrees
from casacore.measures import measures
from tkp.testutil.mock import SyntheticImage, make_wcs
import unittest
import datetime
import tkp.quality.brightsource
import tkp.accessors
and context:
# Path: tkp/testutil/mock.py
# class SyntheticImage(DataAccessor):
# def __init__(self,
# wcs=None,
# data=None,
# beam=(1.5,1.5,0),
# freq_eff=150e6,
# freq_bw=2e6,
# tau_time=1800,
# taustart_ts=datetime.datetime(2015,1,1)
# ):
# """
# Generate a synthetic image for use in tests
#
# Args:
# wcs (tkp.utility.coordinates.WCS): WCS for the image.
# data (array_like): Data for the image. Default is a 512x512 array of
# zeroes.
# beam (tuple): Beamsemi-major axis (in pixels), semi-minor axis (pixels)
# and position angle (radians).
# freq_eff(float): Effective frequency of the image in Hz.
# That is, the mean frequency of all the visibility data which
# comprises this image.
# freq_bw(float): The frequency bandwidth of this image in Hz.
# tau_time(float): Total time on sky in seconds.
# taustart_ts(float): Timestamp of the first integration which
# constitutes part of this image. MJD in seconds.
# """
# self.url = "SyntheticImage"
# self.wcs = wcs
# if self.wcs is None:
# self.wcs = make_wcs()
# self.data = data
# if self.data is None:
# self.data = np.zeros((512,512))
# self.beam = beam
# self.freq_eff = freq_eff
# self.freq_bw = freq_bw
# self.tau_time = tau_time
# self.taustart_ts = taustart_ts
#
# self.pixelsize = self.parse_pixelsize()
# self.centre_ra, self.centre_decl = self.calculate_phase_centre()
#
#
# def calculate_phase_centre(self):
# x, y = self.data.shape
# centre_ra, centre_decl = self.wcs.p2s((x / 2, y / 2))
# return centre_ra, centre_decl
#
# def make_wcs(crval=None,
# cdelt=None,
# crpix=None
# ):
# """
# Make a WCS object for insertion into a synthetic image.
#
# Args:
# crval (tuple): Tuple of (RA, Dec) in decimal degrees at the reference
# position.
# crpix (tuple): Tuple of (x,y) co-ordinates describing the reference
# pixel location corresponding to the crval sky-position.
# cdelt (tuple): Tuple of (cdelt0, cdelt1) in decimal degrees.
# This is the pixel width in degrees of arc, but not necessarily
# aligned to RA, Dec unless `crota` is (0,0). If that *is* the case,
# then typically cdelt0 is negative since the x-axis is in direction
# of West (decreasing RA).
#
# """
# # For any arguments not set we simply assign an arbitrary valid value:
# if crval is None:
# crval = 100., 45.
# if cdelt is None:
# pixel_width_arcsec = 40
# pixel_width_deg = pixel_width_arcsec / 3600.
# cdelt = (-pixel_width_deg, pixel_width_deg)
# if crpix is None:
# crpix = (256.0, 256.0)
# wcs = WCS()
# wcs.cdelt = cdelt
# wcs.crota = (0.0, 0.0)
# wcs.crpix = crpix
# wcs.crval = crval
# wcs.ctype = ('RA---SIN', 'DEC--SIN')
# wcs.cunit = ('deg', 'deg')
# return wcs
which might include code, classes, or functions. Output only the next line. | image.centre_ra = 90 |
Continue the code snippet: <|code_start|>
def update_skyregion_members(session, skyregion):
"""
This function performs a simple distance-check against current members of the
runningcatalog to find sources that should be visible in the given skyregion,
and updates the assocskyrgn table accordingly.
Any previous entries in assocskyrgn relating to this skyregion are
deleted first.
Note 1. We use the variable 'inter' to cache the extraction_radius as transformed
onto the unit sphere, so this does not have to be recalculated for every
comparison.
Note 2. (To Do:) This distance check could be made more efficient by
restricting to a range of RA values, as we do with the Dec.
However, this optimization is complicated by the meridian wrap-around issue.
"""
inter = 2. * math.sin(math.radians(skyregion.xtr_radius) / 2.)
inter_sq = inter * inter
q = """
INSERT INTO assocskyrgn
(
runcat
,skyrgn
,distance_deg
)
SELECT rc.id as runcat
<|code_end|>
. Use current file imports:
import math
from datetime import datetime
from tkp.db.model import Frequencyband, Skyregion, Image, Dataset
from tkp.utility.coordinates import eq_to_cart
from sqlalchemy import func, cast
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION as Double
and context (classes, functions, or code) from other files:
# Path: tkp/db/model.py
# class Frequencyband(Base):
# __tablename__ = 'frequencyband'
#
# id = Column(Integer, seq_frequencyband, primary_key=True,
# server_default=seq_frequencyband.next_value())
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'),
# nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('frequencybands', cascade="all,delete"))
# freq_central = Column(Double)
# freq_low = Column(Double)
# freq_high = Column(Double)
#
# class Skyregion(Base):
# __tablename__ = 'skyregion'
#
# id = Column(Integer, seq_skyregion, primary_key=True,
# server_default=seq_skyregion.next_value())
#
# dataset_id = Column('dataset', ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset',
# backref=backref('skyregions',cascade="all,delete"))
#
# centre_ra = Column(Double, nullable=False)
# centre_decl = Column(Double, nullable=False)
# xtr_radius = Column(Double, nullable=False)
# x = Column(Double, nullable=False)
# y = Column(Double, nullable=False)
# z = Column(Double, nullable=False)
#
# class Image(Base):
# __tablename__ = 'image'
#
# id = Column(Integer, seq_image, primary_key=True,
# server_default=seq_image.next_value())
#
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('images', cascade="delete"))
#
# band_id = Column('band', ForeignKey('frequencyband.id'), nullable=False, index=True)
# band = relationship('Frequencyband', cascade="delete")
#
# skyrgn_id = Column('skyrgn', Integer, ForeignKey('skyregion.id'), nullable=False, index=True)
# skyrgn = relationship('Skyregion', backref=backref('images', cascade="delete"))
#
# tau = Column(Integer)
# stokes = Column(SmallInteger, nullable=False, server_default=text("1"))
# tau_time = Column(Double)
# freq_eff = Column(Double, nullable=False)
# freq_bw = Column(Double)
# taustart_ts = Column(DateTime, nullable=False, index=True)
# rb_smaj = Column(Double, nullable=False)
# rb_smin = Column(Double, nullable=False)
# rb_pa = Column(Double, nullable=False)
# deltax = Column(Double, nullable=False)
# deltay = Column(Double, nullable=False)
# fwhm_arcsec = Column(Double)
# fov_degrees = Column(Double)
# rms_qc = Column(Double, nullable=False)
# rms_min = Column(Double)
# rms_max = Column(Double)
# detection_thresh = Column(Double)
# analysis_thresh = Column(Double)
# url = Column(String(1024))
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# data = relationship("ImageData", uselist=False, back_populates="image")
#
# class Dataset(Base):
# __tablename__ = 'dataset'
#
# id = Column(Integer, seq_dataset, server_default=seq_dataset.next_value(), primary_key=True)
# rerun = Column(Integer, nullable=False, server_default=text("0"))
# type = Column(SmallInteger, nullable=False, server_default=text("1"))
# process_start_ts = Column(DateTime, nullable=False)
# process_end_ts = Column(DateTime)
# detection_threshold = Column(Double)
# analysis_threshold = Column(Double)
# assoc_radius = Column(Double)
# backsize_x = Column(SmallInteger)
# backsize_y = Column(SmallInteger)
# margin_width = Column(Double)
# description = Column(String(100), nullable=False)
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | ,sky.id as skyrgn |
Predict the next line after this snippet: <|code_start|> session.add(band)
return band
def update_skyregion_members(session, skyregion):
"""
This function performs a simple distance-check against current members of the
runningcatalog to find sources that should be visible in the given skyregion,
and updates the assocskyrgn table accordingly.
Any previous entries in assocskyrgn relating to this skyregion are
deleted first.
Note 1. We use the variable 'inter' to cache the extraction_radius as transformed
onto the unit sphere, so this does not have to be recalculated for every
comparison.
Note 2. (To Do:) This distance check could be made more efficient by
restricting to a range of RA values, as we do with the Dec.
However, this optimization is complicated by the meridian wrap-around issue.
"""
inter = 2. * math.sin(math.radians(skyregion.xtr_radius) / 2.)
inter_sq = inter * inter
q = """
INSERT INTO assocskyrgn
(
runcat
,skyrgn
<|code_end|>
using the current file's imports:
import math
from datetime import datetime
from tkp.db.model import Frequencyband, Skyregion, Image, Dataset
from tkp.utility.coordinates import eq_to_cart
from sqlalchemy import func, cast
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION as Double
and any relevant context from other files:
# Path: tkp/db/model.py
# class Frequencyband(Base):
# __tablename__ = 'frequencyband'
#
# id = Column(Integer, seq_frequencyband, primary_key=True,
# server_default=seq_frequencyband.next_value())
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'),
# nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('frequencybands', cascade="all,delete"))
# freq_central = Column(Double)
# freq_low = Column(Double)
# freq_high = Column(Double)
#
# class Skyregion(Base):
# __tablename__ = 'skyregion'
#
# id = Column(Integer, seq_skyregion, primary_key=True,
# server_default=seq_skyregion.next_value())
#
# dataset_id = Column('dataset', ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset',
# backref=backref('skyregions',cascade="all,delete"))
#
# centre_ra = Column(Double, nullable=False)
# centre_decl = Column(Double, nullable=False)
# xtr_radius = Column(Double, nullable=False)
# x = Column(Double, nullable=False)
# y = Column(Double, nullable=False)
# z = Column(Double, nullable=False)
#
# class Image(Base):
# __tablename__ = 'image'
#
# id = Column(Integer, seq_image, primary_key=True,
# server_default=seq_image.next_value())
#
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('images', cascade="delete"))
#
# band_id = Column('band', ForeignKey('frequencyband.id'), nullable=False, index=True)
# band = relationship('Frequencyband', cascade="delete")
#
# skyrgn_id = Column('skyrgn', Integer, ForeignKey('skyregion.id'), nullable=False, index=True)
# skyrgn = relationship('Skyregion', backref=backref('images', cascade="delete"))
#
# tau = Column(Integer)
# stokes = Column(SmallInteger, nullable=False, server_default=text("1"))
# tau_time = Column(Double)
# freq_eff = Column(Double, nullable=False)
# freq_bw = Column(Double)
# taustart_ts = Column(DateTime, nullable=False, index=True)
# rb_smaj = Column(Double, nullable=False)
# rb_smin = Column(Double, nullable=False)
# rb_pa = Column(Double, nullable=False)
# deltax = Column(Double, nullable=False)
# deltay = Column(Double, nullable=False)
# fwhm_arcsec = Column(Double)
# fov_degrees = Column(Double)
# rms_qc = Column(Double, nullable=False)
# rms_min = Column(Double)
# rms_max = Column(Double)
# detection_thresh = Column(Double)
# analysis_thresh = Column(Double)
# url = Column(String(1024))
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# data = relationship("ImageData", uselist=False, back_populates="image")
#
# class Dataset(Base):
# __tablename__ = 'dataset'
#
# id = Column(Integer, seq_dataset, server_default=seq_dataset.next_value(), primary_key=True)
# rerun = Column(Integer, nullable=False, server_default=text("0"))
# type = Column(SmallInteger, nullable=False, server_default=text("1"))
# process_start_ts = Column(DateTime, nullable=False)
# process_end_ts = Column(DateTime)
# detection_threshold = Column(Double)
# analysis_threshold = Column(Double)
# assoc_radius = Column(Double)
# backsize_x = Column(SmallInteger)
# backsize_y = Column(SmallInteger)
# margin_width = Column(Double)
# description = Column(String(100), nullable=False)
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | ,distance_deg |
Using the snippet: <|code_start|>
def update_skyregion_members(session, skyregion):
"""
This function performs a simple distance-check against current members of the
runningcatalog to find sources that should be visible in the given skyregion,
and updates the assocskyrgn table accordingly.
Any previous entries in assocskyrgn relating to this skyregion are
deleted first.
Note 1. We use the variable 'inter' to cache the extraction_radius as transformed
onto the unit sphere, so this does not have to be recalculated for every
comparison.
Note 2. (To Do:) This distance check could be made more efficient by
restricting to a range of RA values, as we do with the Dec.
However, this optimization is complicated by the meridian wrap-around issue.
"""
inter = 2. * math.sin(math.radians(skyregion.xtr_radius) / 2.)
inter_sq = inter * inter
q = """
INSERT INTO assocskyrgn
(
runcat
,skyrgn
,distance_deg
)
SELECT rc.id as runcat
<|code_end|>
, determine the next line of code. You have imports:
import math
from datetime import datetime
from tkp.db.model import Frequencyband, Skyregion, Image, Dataset
from tkp.utility.coordinates import eq_to_cart
from sqlalchemy import func, cast
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION as Double
and context (class names, function names, or code) available:
# Path: tkp/db/model.py
# class Frequencyband(Base):
# __tablename__ = 'frequencyband'
#
# id = Column(Integer, seq_frequencyband, primary_key=True,
# server_default=seq_frequencyband.next_value())
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'),
# nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('frequencybands', cascade="all,delete"))
# freq_central = Column(Double)
# freq_low = Column(Double)
# freq_high = Column(Double)
#
# class Skyregion(Base):
# __tablename__ = 'skyregion'
#
# id = Column(Integer, seq_skyregion, primary_key=True,
# server_default=seq_skyregion.next_value())
#
# dataset_id = Column('dataset', ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset',
# backref=backref('skyregions',cascade="all,delete"))
#
# centre_ra = Column(Double, nullable=False)
# centre_decl = Column(Double, nullable=False)
# xtr_radius = Column(Double, nullable=False)
# x = Column(Double, nullable=False)
# y = Column(Double, nullable=False)
# z = Column(Double, nullable=False)
#
# class Image(Base):
# __tablename__ = 'image'
#
# id = Column(Integer, seq_image, primary_key=True,
# server_default=seq_image.next_value())
#
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('images', cascade="delete"))
#
# band_id = Column('band', ForeignKey('frequencyband.id'), nullable=False, index=True)
# band = relationship('Frequencyband', cascade="delete")
#
# skyrgn_id = Column('skyrgn', Integer, ForeignKey('skyregion.id'), nullable=False, index=True)
# skyrgn = relationship('Skyregion', backref=backref('images', cascade="delete"))
#
# tau = Column(Integer)
# stokes = Column(SmallInteger, nullable=False, server_default=text("1"))
# tau_time = Column(Double)
# freq_eff = Column(Double, nullable=False)
# freq_bw = Column(Double)
# taustart_ts = Column(DateTime, nullable=False, index=True)
# rb_smaj = Column(Double, nullable=False)
# rb_smin = Column(Double, nullable=False)
# rb_pa = Column(Double, nullable=False)
# deltax = Column(Double, nullable=False)
# deltay = Column(Double, nullable=False)
# fwhm_arcsec = Column(Double)
# fov_degrees = Column(Double)
# rms_qc = Column(Double, nullable=False)
# rms_min = Column(Double)
# rms_max = Column(Double)
# detection_thresh = Column(Double)
# analysis_thresh = Column(Double)
# url = Column(String(1024))
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# data = relationship("ImageData", uselist=False, back_populates="image")
#
# class Dataset(Base):
# __tablename__ = 'dataset'
#
# id = Column(Integer, seq_dataset, server_default=seq_dataset.next_value(), primary_key=True)
# rerun = Column(Integer, nullable=False, server_default=text("0"))
# type = Column(SmallInteger, nullable=False, server_default=text("1"))
# process_start_ts = Column(DateTime, nullable=False)
# process_end_ts = Column(DateTime)
# detection_threshold = Column(Double)
# analysis_threshold = Column(Double)
# assoc_radius = Column(Double)
# backsize_x = Column(SmallInteger)
# backsize_y = Column(SmallInteger)
# margin_width = Column(Double)
# description = Column(String(100), nullable=False)
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | ,sky.id as skyrgn |
Given the following code snippet before the placeholder: <|code_start|> and updates the assocskyrgn table accordingly.
Any previous entries in assocskyrgn relating to this skyregion are
deleted first.
Note 1. We use the variable 'inter' to cache the extraction_radius as transformed
onto the unit sphere, so this does not have to be recalculated for every
comparison.
Note 2. (To Do:) This distance check could be made more efficient by
restricting to a range of RA values, as we do with the Dec.
However, this optimization is complicated by the meridian wrap-around issue.
"""
inter = 2. * math.sin(math.radians(skyregion.xtr_radius) / 2.)
inter_sq = inter * inter
q = """
INSERT INTO assocskyrgn
(
runcat
,skyrgn
,distance_deg
)
SELECT rc.id as runcat
,sky.id as skyrgn
,DEGREES(2 * ASIN(SQRT( (rc.x - sky.x) * (rc.x - sky.x)
+ (rc.y - sky.y) * (rc.y - sky.y)
+ (rc.z - sky.z) * (rc.z - sky.z)
) / 2 )
)
<|code_end|>
, predict the next line using imports from the current file:
import math
from datetime import datetime
from tkp.db.model import Frequencyband, Skyregion, Image, Dataset
from tkp.utility.coordinates import eq_to_cart
from sqlalchemy import func, cast
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION as Double
and context including class names, function names, and sometimes code from other files:
# Path: tkp/db/model.py
# class Frequencyband(Base):
# __tablename__ = 'frequencyband'
#
# id = Column(Integer, seq_frequencyband, primary_key=True,
# server_default=seq_frequencyband.next_value())
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'),
# nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('frequencybands', cascade="all,delete"))
# freq_central = Column(Double)
# freq_low = Column(Double)
# freq_high = Column(Double)
#
# class Skyregion(Base):
# __tablename__ = 'skyregion'
#
# id = Column(Integer, seq_skyregion, primary_key=True,
# server_default=seq_skyregion.next_value())
#
# dataset_id = Column('dataset', ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset',
# backref=backref('skyregions',cascade="all,delete"))
#
# centre_ra = Column(Double, nullable=False)
# centre_decl = Column(Double, nullable=False)
# xtr_radius = Column(Double, nullable=False)
# x = Column(Double, nullable=False)
# y = Column(Double, nullable=False)
# z = Column(Double, nullable=False)
#
# class Image(Base):
# __tablename__ = 'image'
#
# id = Column(Integer, seq_image, primary_key=True,
# server_default=seq_image.next_value())
#
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('images', cascade="delete"))
#
# band_id = Column('band', ForeignKey('frequencyband.id'), nullable=False, index=True)
# band = relationship('Frequencyband', cascade="delete")
#
# skyrgn_id = Column('skyrgn', Integer, ForeignKey('skyregion.id'), nullable=False, index=True)
# skyrgn = relationship('Skyregion', backref=backref('images', cascade="delete"))
#
# tau = Column(Integer)
# stokes = Column(SmallInteger, nullable=False, server_default=text("1"))
# tau_time = Column(Double)
# freq_eff = Column(Double, nullable=False)
# freq_bw = Column(Double)
# taustart_ts = Column(DateTime, nullable=False, index=True)
# rb_smaj = Column(Double, nullable=False)
# rb_smin = Column(Double, nullable=False)
# rb_pa = Column(Double, nullable=False)
# deltax = Column(Double, nullable=False)
# deltay = Column(Double, nullable=False)
# fwhm_arcsec = Column(Double)
# fov_degrees = Column(Double)
# rms_qc = Column(Double, nullable=False)
# rms_min = Column(Double)
# rms_max = Column(Double)
# detection_thresh = Column(Double)
# analysis_thresh = Column(Double)
# url = Column(String(1024))
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# data = relationship("ImageData", uselist=False, back_populates="image")
#
# class Dataset(Base):
# __tablename__ = 'dataset'
#
# id = Column(Integer, seq_dataset, server_default=seq_dataset.next_value(), primary_key=True)
# rerun = Column(Integer, nullable=False, server_default=text("0"))
# type = Column(SmallInteger, nullable=False, server_default=text("1"))
# process_start_ts = Column(DateTime, nullable=False)
# process_end_ts = Column(DateTime)
# detection_threshold = Column(Double)
# analysis_threshold = Column(Double)
# assoc_radius = Column(Double)
# backsize_x = Column(SmallInteger)
# backsize_y = Column(SmallInteger)
# margin_width = Column(Double)
# description = Column(String(100), nullable=False)
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | FROM skyregion sky |
Given the code snippet: <|code_start|>
Note 2. (To Do:) This distance check could be made more efficient by
restricting to a range of RA values, as we do with the Dec.
However, this optimization is complicated by the meridian wrap-around issue.
"""
inter = 2. * math.sin(math.radians(skyregion.xtr_radius) / 2.)
inter_sq = inter * inter
q = """
INSERT INTO assocskyrgn
(
runcat
,skyrgn
,distance_deg
)
SELECT rc.id as runcat
,sky.id as skyrgn
,DEGREES(2 * ASIN(SQRT( (rc.x - sky.x) * (rc.x - sky.x)
+ (rc.y - sky.y) * (rc.y - sky.y)
+ (rc.z - sky.z) * (rc.z - sky.z)
) / 2 )
)
FROM skyregion sky
,runningcatalog rc
WHERE sky.id = %(skyregion_id)s
AND rc.dataset = sky.dataset
AND rc.wm_decl BETWEEN sky.centre_decl - sky.xtr_radius
AND sky.centre_decl + sky.xtr_radius
AND ( (rc.x - sky.x) * (rc.x - sky.x)
+ (rc.y - sky.y) * (rc.y - sky.y)
<|code_end|>
, generate the next line using the imports in this file:
import math
from datetime import datetime
from tkp.db.model import Frequencyband, Skyregion, Image, Dataset
from tkp.utility.coordinates import eq_to_cart
from sqlalchemy import func, cast
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION as Double
and context (functions, classes, or occasionally code) from other files:
# Path: tkp/db/model.py
# class Frequencyband(Base):
# __tablename__ = 'frequencyband'
#
# id = Column(Integer, seq_frequencyband, primary_key=True,
# server_default=seq_frequencyband.next_value())
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'),
# nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('frequencybands', cascade="all,delete"))
# freq_central = Column(Double)
# freq_low = Column(Double)
# freq_high = Column(Double)
#
# class Skyregion(Base):
# __tablename__ = 'skyregion'
#
# id = Column(Integer, seq_skyregion, primary_key=True,
# server_default=seq_skyregion.next_value())
#
# dataset_id = Column('dataset', ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset',
# backref=backref('skyregions',cascade="all,delete"))
#
# centre_ra = Column(Double, nullable=False)
# centre_decl = Column(Double, nullable=False)
# xtr_radius = Column(Double, nullable=False)
# x = Column(Double, nullable=False)
# y = Column(Double, nullable=False)
# z = Column(Double, nullable=False)
#
# class Image(Base):
# __tablename__ = 'image'
#
# id = Column(Integer, seq_image, primary_key=True,
# server_default=seq_image.next_value())
#
# dataset_id = Column('dataset', Integer, ForeignKey('dataset.id'), nullable=False, index=True)
# dataset = relationship('Dataset', backref=backref('images', cascade="delete"))
#
# band_id = Column('band', ForeignKey('frequencyband.id'), nullable=False, index=True)
# band = relationship('Frequencyband', cascade="delete")
#
# skyrgn_id = Column('skyrgn', Integer, ForeignKey('skyregion.id'), nullable=False, index=True)
# skyrgn = relationship('Skyregion', backref=backref('images', cascade="delete"))
#
# tau = Column(Integer)
# stokes = Column(SmallInteger, nullable=False, server_default=text("1"))
# tau_time = Column(Double)
# freq_eff = Column(Double, nullable=False)
# freq_bw = Column(Double)
# taustart_ts = Column(DateTime, nullable=False, index=True)
# rb_smaj = Column(Double, nullable=False)
# rb_smin = Column(Double, nullable=False)
# rb_pa = Column(Double, nullable=False)
# deltax = Column(Double, nullable=False)
# deltay = Column(Double, nullable=False)
# fwhm_arcsec = Column(Double)
# fov_degrees = Column(Double)
# rms_qc = Column(Double, nullable=False)
# rms_min = Column(Double)
# rms_max = Column(Double)
# detection_thresh = Column(Double)
# analysis_thresh = Column(Double)
# url = Column(String(1024))
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# data = relationship("ImageData", uselist=False, back_populates="image")
#
# class Dataset(Base):
# __tablename__ = 'dataset'
#
# id = Column(Integer, seq_dataset, server_default=seq_dataset.next_value(), primary_key=True)
# rerun = Column(Integer, nullable=False, server_default=text("0"))
# type = Column(SmallInteger, nullable=False, server_default=text("1"))
# process_start_ts = Column(DateTime, nullable=False)
# process_end_ts = Column(DateTime)
# detection_threshold = Column(Double)
# analysis_threshold = Column(Double)
# assoc_radius = Column(Double)
# backsize_x = Column(SmallInteger)
# backsize_y = Column(SmallInteger)
# margin_width = Column(Double)
# description = Column(String(100), nullable=False)
# node = Column(SmallInteger, nullable=False, server_default=text("1"))
# nodes = Column(SmallInteger, nullable=False, server_default=text("1"))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | + (rc.z - sky.z) * (rc.z - sky.z) |
Using the snippet: <|code_start|>"""
A collection of back end subroutines (mostly SQL queries).
In this module we collect together various routines
that don't fit into a more specific collection.
"""
logger = logging.getLogger(__name__)
lightcurve_query = """
SELECT im.taustart_ts
,im.tau_time
,ex.f_int
,ex.f_int_err
,ex.id
,im.band
,im.stokes
,bd.freq_central
FROM extractedsource ex
<|code_end|>
, determine the next line of code. You have imports:
import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart
and context (class names, function names, or code) available:
# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
# rerun = session.query(func.max(Dataset.rerun)). \
# select_from(Dataset). \
# filter(Dataset.description == "description"). \
# one()[0]
#
# if not rerun:
# rerun = 0
# else:
# rerun += 1
#
# dataset = Dataset(rerun=rerun,
# process_start_ts=datetime.now(),
# description=description)
# session.add(dataset)
# return dataset
#
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
# order=None):
# """Obtain specific column (keywords) values from 'table', with
# kwargs limitations.
#
# A very simple helper function, that builds an SQL query to obtain
# the specified columns from 'table', and then executes that
# query. Optionally, the WHERE clause can be specified using the
# where dictionary. It returns a list of a
# dict (with the originally supplied keywords as dictionary keys),
# which can be empty.
#
# Example:
#
# >>> columns_from_table('image', \
# keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
# [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
#
# This builds the SQL query:
# "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
#
# This function is implemented mainly to abstract and hide the SQL
# functionality from the Python interface.
#
# Args:
#
# conn: database connection object
#
# table (string): database table name
#
# Kwargs:
#
# keywords (uple): column names to select from the table. None indicates all ('*')
#
# where (dict): where clause for the query, specified as a set
# of 'key = value' comparisons. Comparisons are and-ed
# together. Obviously, only 'is equal' comparisons are
# possible.
#
# alias (dict): Chosen aliases for the column names,
# used when constructing the returned list of dictionaries
#
# order (string): ORDER BY key.
#
# Returns:
#
# (tuple): list of dicts. Each dict contains the given keywords,
# or all if keywords=None. Each element of the list
# corresponds to a table row.
#
# """
# if keywords is None:
# query = "SELECT * FROM " + table
# else:
# query = "SELECT " + ", ".join(keywords) + " FROM " + table
# if where is None:
# where = {}
# where_args = tuple(where.itervalues())
# where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
# if where:
# query += " WHERE " + where
# if order:
# query += " ORDER BY " + order
#
# cursor = tkp.db.execute(query, where_args)
# results = cursor.fetchall()
# results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
# return results_dict
#
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
# """Compute the ra expansion for a given theta at a given declination
#
# Keyword arguments:
# theta, decl are both in decimal degrees.
#
# Return value:
# alpha -- RA inflation in decimal degrees
#
# For a derivation, see MSR TR 2006 52, Section 2.1
# http://research.microsoft.com/apps/pubs/default.aspx?id=64524
#
# """
# if abs(decl) + theta > 89.9:
# return 180.0
# else:
# return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | ,assocxtrsource ax |
Here is a snippet: <|code_start|>"""
A collection of back end subroutines (mostly SQL queries).
In this module we collect together various routines
that don't fit into a more specific collection.
"""
logger = logging.getLogger(__name__)
lightcurve_query = """
SELECT im.taustart_ts
,im.tau_time
,ex.f_int
,ex.f_int_err
,ex.id
,im.band
,im.stokes
,bd.freq_central
FROM extractedsource ex
,assocxtrsource ax
,image im
<|code_end|>
. Write the next line using the current file imports:
import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart
and context from other files:
# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
# rerun = session.query(func.max(Dataset.rerun)). \
# select_from(Dataset). \
# filter(Dataset.description == "description"). \
# one()[0]
#
# if not rerun:
# rerun = 0
# else:
# rerun += 1
#
# dataset = Dataset(rerun=rerun,
# process_start_ts=datetime.now(),
# description=description)
# session.add(dataset)
# return dataset
#
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
# order=None):
# """Obtain specific column (keywords) values from 'table', with
# kwargs limitations.
#
# A very simple helper function, that builds an SQL query to obtain
# the specified columns from 'table', and then executes that
# query. Optionally, the WHERE clause can be specified using the
# where dictionary. It returns a list of a
# dict (with the originally supplied keywords as dictionary keys),
# which can be empty.
#
# Example:
#
# >>> columns_from_table('image', \
# keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
# [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
#
# This builds the SQL query:
# "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
#
# This function is implemented mainly to abstract and hide the SQL
# functionality from the Python interface.
#
# Args:
#
# conn: database connection object
#
# table (string): database table name
#
# Kwargs:
#
# keywords (uple): column names to select from the table. None indicates all ('*')
#
# where (dict): where clause for the query, specified as a set
# of 'key = value' comparisons. Comparisons are and-ed
# together. Obviously, only 'is equal' comparisons are
# possible.
#
# alias (dict): Chosen aliases for the column names,
# used when constructing the returned list of dictionaries
#
# order (string): ORDER BY key.
#
# Returns:
#
# (tuple): list of dicts. Each dict contains the given keywords,
# or all if keywords=None. Each element of the list
# corresponds to a table row.
#
# """
# if keywords is None:
# query = "SELECT * FROM " + table
# else:
# query = "SELECT " + ", ".join(keywords) + " FROM " + table
# if where is None:
# where = {}
# where_args = tuple(where.itervalues())
# where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
# if where:
# query += " WHERE " + where
# if order:
# query += " ORDER BY " + order
#
# cursor = tkp.db.execute(query, where_args)
# results = cursor.fetchall()
# results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
# return results_dict
#
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
# """Compute the ra expansion for a given theta at a given declination
#
# Keyword arguments:
# theta, decl are both in decimal degrees.
#
# Return value:
# alpha -- RA inflation in decimal degrees
#
# For a derivation, see MSR TR 2006 52, Section 2.1
# http://research.microsoft.com/apps/pubs/default.aspx?id=64524
#
# """
# if abs(decl) + theta > 89.9:
# return 180.0
# else:
# return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
, which may include functions, classes, or code. Output only the next line. | ,frequencyband bd |
Continue the code snippet: <|code_start|>"""
A collection of back end subroutines (mostly SQL queries).
In this module we collect together various routines
that don't fit into a more specific collection.
"""
logger = logging.getLogger(__name__)
lightcurve_query = """
<|code_end|>
. Use current file imports:
import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart
and context (classes, functions, or code) from other files:
# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
# rerun = session.query(func.max(Dataset.rerun)). \
# select_from(Dataset). \
# filter(Dataset.description == "description"). \
# one()[0]
#
# if not rerun:
# rerun = 0
# else:
# rerun += 1
#
# dataset = Dataset(rerun=rerun,
# process_start_ts=datetime.now(),
# description=description)
# session.add(dataset)
# return dataset
#
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
# order=None):
# """Obtain specific column (keywords) values from 'table', with
# kwargs limitations.
#
# A very simple helper function, that builds an SQL query to obtain
# the specified columns from 'table', and then executes that
# query. Optionally, the WHERE clause can be specified using the
# where dictionary. It returns a list of a
# dict (with the originally supplied keywords as dictionary keys),
# which can be empty.
#
# Example:
#
# >>> columns_from_table('image', \
# keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
# [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
#
# This builds the SQL query:
# "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
#
# This function is implemented mainly to abstract and hide the SQL
# functionality from the Python interface.
#
# Args:
#
# conn: database connection object
#
# table (string): database table name
#
# Kwargs:
#
# keywords (uple): column names to select from the table. None indicates all ('*')
#
# where (dict): where clause for the query, specified as a set
# of 'key = value' comparisons. Comparisons are and-ed
# together. Obviously, only 'is equal' comparisons are
# possible.
#
# alias (dict): Chosen aliases for the column names,
# used when constructing the returned list of dictionaries
#
# order (string): ORDER BY key.
#
# Returns:
#
# (tuple): list of dicts. Each dict contains the given keywords,
# or all if keywords=None. Each element of the list
# corresponds to a table row.
#
# """
# if keywords is None:
# query = "SELECT * FROM " + table
# else:
# query = "SELECT " + ", ".join(keywords) + " FROM " + table
# if where is None:
# where = {}
# where_args = tuple(where.itervalues())
# where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
# if where:
# query += " WHERE " + where
# if order:
# query += " ORDER BY " + order
#
# cursor = tkp.db.execute(query, where_args)
# results = cursor.fetchall()
# results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
# return results_dict
#
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
# """Compute the ra expansion for a given theta at a given declination
#
# Keyword arguments:
# theta, decl are both in decimal degrees.
#
# Return value:
# alpha -- RA inflation in decimal degrees
#
# For a derivation, see MSR TR 2006 52, Section 2.1
# http://research.microsoft.com/apps/pubs/default.aspx?id=64524
#
# """
# if abs(decl) + theta > 89.9:
# return 180.0
# else:
# return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | SELECT im.taustart_ts |
Predict the next line after this snippet: <|code_start|>"""
A collection of back end subroutines (mostly SQL queries).
In this module we collect together various routines
that don't fit into a more specific collection.
"""
logger = logging.getLogger(__name__)
lightcurve_query = """
SELECT im.taustart_ts
,im.tau_time
,ex.f_int
,ex.f_int_err
,ex.id
,im.band
,im.stokes
,bd.freq_central
FROM extractedsource ex
,assocxtrsource ax
,image im
,frequencyband bd
WHERE ax.runcat IN (SELECT runcat
FROM assocxtrsource
WHERE xtrsrc = %(xtrsrc)s
<|code_end|>
using the current file's imports:
import itertools
import logging
import math
import tkp.db
from datetime import datetime
from tkp.db.alchemy.image import insert_dataset as alchemy_insert_dataset
from tkp.db.generic import columns_from_table
from tkp.utility import substitute_inf
from tkp.utility.coordinates import alpha_inflate
from tkp.utility.coordinates import eq_to_cart
and any relevant context from other files:
# Path: tkp/db/alchemy/image.py
# def insert_dataset(session, description):
# rerun = session.query(func.max(Dataset.rerun)). \
# select_from(Dataset). \
# filter(Dataset.description == "description"). \
# one()[0]
#
# if not rerun:
# rerun = 0
# else:
# rerun += 1
#
# dataset = Dataset(rerun=rerun,
# process_start_ts=datetime.now(),
# description=description)
# session.add(dataset)
# return dataset
#
# Path: tkp/db/generic.py
# def columns_from_table(table, keywords=None, alias=None, where=None,
# order=None):
# """Obtain specific column (keywords) values from 'table', with
# kwargs limitations.
#
# A very simple helper function, that builds an SQL query to obtain
# the specified columns from 'table', and then executes that
# query. Optionally, the WHERE clause can be specified using the
# where dictionary. It returns a list of a
# dict (with the originally supplied keywords as dictionary keys),
# which can be empty.
#
# Example:
#
# >>> columns_from_table('image', \
# keywords=['taustart_ts', 'tau_time', 'freq_eff', 'freq_bw'], where={'imageid': 1})
# [{'freq_eff': 133984375.0, 'taustart_ts': datetime.datetime(2010, 10, 9, 9, 4, 2), 'tau_time': 14400.0, 'freq_bw': 1953125.0}]
#
# This builds the SQL query:
# "SELECT taustart_ts, tau_time, freq_eff, freq_bw FROM image WHERE imageid=1"
#
# This function is implemented mainly to abstract and hide the SQL
# functionality from the Python interface.
#
# Args:
#
# conn: database connection object
#
# table (string): database table name
#
# Kwargs:
#
# keywords (uple): column names to select from the table. None indicates all ('*')
#
# where (dict): where clause for the query, specified as a set
# of 'key = value' comparisons. Comparisons are and-ed
# together. Obviously, only 'is equal' comparisons are
# possible.
#
# alias (dict): Chosen aliases for the column names,
# used when constructing the returned list of dictionaries
#
# order (string): ORDER BY key.
#
# Returns:
#
# (tuple): list of dicts. Each dict contains the given keywords,
# or all if keywords=None. Each element of the list
# corresponds to a table row.
#
# """
# if keywords is None:
# query = "SELECT * FROM " + table
# else:
# query = "SELECT " + ", ".join(keywords) + " FROM " + table
# if where is None:
# where = {}
# where_args = tuple(where.itervalues())
# where = " AND ".join(["%s=%%s" % key for key in where.iterkeys()])
# if where:
# query += " WHERE " + where
# if order:
# query += " ORDER BY " + order
#
# cursor = tkp.db.execute(query, where_args)
# results = cursor.fetchall()
# results_dict = convert_db_rows_to_dicts(results, alias_map=alias)
# return results_dict
#
# Path: tkp/utility/coordinates.py
# def alpha_inflate(theta, decl):
# """Compute the ra expansion for a given theta at a given declination
#
# Keyword arguments:
# theta, decl are both in decimal degrees.
#
# Return value:
# alpha -- RA inflation in decimal degrees
#
# For a derivation, see MSR TR 2006 52, Section 2.1
# http://research.microsoft.com/apps/pubs/default.aspx?id=64524
#
# """
# if abs(decl) + theta > 89.9:
# return 180.0
# else:
# return math.degrees(abs(math.atan(math.sin(math.radians(theta)) / math.sqrt(abs(math.cos(math.radians(decl - theta)) * math.cos(math.radians(decl + theta)))))))
#
# Path: tkp/utility/coordinates.py
# def eq_to_cart(ra, dec):
# """Find the cartesian co-ordinates on the unit sphere given the eq. co-ords.
#
# ra, dec should be in degrees.
# """
# return (math.cos(math.radians(dec)) * math.cos(math.radians(ra)), # Cartesian x
# math.cos(math.radians(dec)) * math.sin(math.radians(ra)), # Cartesian y
# math.sin(math.radians(dec))) # Cartesian z
. Output only the next line. | ) |
Using the snippet: <|code_start|> rms_est_sigma=rms_est_sigma,
rms_est_fraction=rms_est_fraction)
noise = noise_level(accessor.freq_eff, accessor.freq_bw, accessor.tau_time,
accessor.antenna_set, accessor.ncore, accessor.nremote, accessor.nintl
)
rms_check = rms_invalid(rms_qc, noise, low_bound, high_bound)
if not rms_check:
logger.info("image %s accepted: rms: %s, theoretical noise: %s" % \
(accessor.url, nice_format(rms_qc),
nice_format(noise)))
else:
logger.info("image %s REJECTED: %s " % (accessor.url, rms_check))
return (dbquality.reject_reasons['rms'], rms_check)
# beam shape check
(semimaj, semimin, theta) = accessor.beam
beam_check = beam_invalid(semimaj, semimin, theta, oversampled_x, elliptical_x)
if not beam_check:
logger.info("image %s accepted: semimaj: %s, semimin: %s" % (accessor.url,
nice_format(semimaj),
nice_format(semimin)))
else:
logger.info("image %s REJECTED: %s " % (accessor.url, beam_check))
return (dbquality.reject_reasons['beam'], beam_check)
# Bright source check
bright = tkp.quality.brightsource.is_bright_source_near(accessor, min_separation)
if bright:
<|code_end|>
, determine the next line of code. You have imports:
import logging
import tkp.db
import tkp.db.quality as dbquality
from tkp.quality.restoringbeam import beam_invalid
from tkp.quality.rms import rms_invalid, rms_with_clipped_subregion
from tkp.telescope.lofar.noise import noise_level
from tkp.utility import nice_format
and context (class names, function names, or code) available:
# Path: tkp/quality/restoringbeam.py
# def beam_invalid(semibmaj, semibmin, theta, oversampled_x=30, elliptical_x=2.0):
# """ Are the beam shape properties ok?
#
# :param semibmaj/semibmin: size of the beam in pixels
#
# :returns: True/False
# """
#
# formatted = "bmaj=%s and bmin=%s (pixels)" % (nice_format(semibmaj),
# nice_format(semibmin))
#
# if tkp.quality.restoringbeam.infinite(semibmaj, semibmin, theta):
# return "Beam infinte. %s" % formatted
# if tkp.quality.restoringbeam.undersampled(semibmaj, semibmin):
# return "Beam undersampled. %s" % formatted
# elif tkp.quality.restoringbeam.oversampled(semibmaj, semibmin,
# oversampled_x):
# return "Beam oversampled. %s" % formatted
# elif tkp.quality.restoringbeam.highly_elliptical(semibmaj, semibmin, elliptical_x):
# return "Beam too elliptical. %s" % formatted
#
# #TODO: this test has been disabled untill antonia solves issue discribed in #3802
# #elif not tkp.quality.restoringbeam.full_fieldofview(nx, ny, cellsize, fov):
# # return "Full field of view not imaged. Imaged FoV=XXdegrees, Observed FoV=XXdegrees"
#
# else:
# return False
#
# Path: tkp/quality/rms.py
# def rms_invalid(rms, noise, low_bound=1, high_bound=50):
# """
# Is the RMS value of an image outside the plausible range?
#
# :param rms: RMS value of an image, can be computed with
# tkp.quality.statistics.rms
# :param noise: Theoretical noise level of instrument, can be calculated with
# tkp.lofar.noise.noise_level
# :param low_bound: multiplied with noise to define lower threshold
# :param high_bound: multiplied with noise to define upper threshold
# :returns: True/False
# """
# if (rms < noise * low_bound) or (rms > noise * high_bound):
# ratio = rms / noise
# return "rms value (%s) is %s times theoretical noise (%s)" % \
# (nice_format(rms), nice_format(ratio), nice_format(noise))
# else:
# return False
#
# def rms_with_clipped_subregion(data, rms_est_sigma=3, rms_est_fraction=4):
# """
# RMS for quality-control.
#
# Root mean square value calculated from central region of an image.
# We sigma-clip the input-data in an attempt to exclude source-pixels
# and keep only background-pixels.
#
# Args:
# data: A numpy array
# rms_est_sigma: sigma value used for clipping
# rms_est_fraction: determines size of subsection, result will be
# 1/fth of the image size where f=rms_est_fraction
# returns the rms value of a iterative sigma clipped subsection of an image
# """
# return rms(clip(subregion(data, rms_est_fraction), rms_est_sigma))
. Output only the next line. | logger.info("image %s REJECTED: %s " % (accessor.url, bright)) |
Using the snippet: <|code_start|>
logger = logging.getLogger(__name__)
def reject_check_lofar(accessor, job_config):
lofar_quality_params = job_config['quality_lofar']
quality_params = job_config['quality']
low_bound = lofar_quality_params['low_bound']
high_bound = lofar_quality_params['high_bound']
oversampled_x = quality_params['oversampled_x']
elliptical_x = quality_params['elliptical_x']
min_separation = lofar_quality_params['min_separation']
if accessor.tau_time == 0:
logger.info("image %s REJECTED: tau_time is 0, should be > 0" % accessor.url)
return dbquality.reject_reasons['tau_time'], "tau_time is 0"
rms_est_sigma = job_config.persistence.rms_est_sigma
rms_est_fraction = job_config.persistence.rms_est_fraction
rms_qc = rms_with_clipped_subregion(accessor.data,
rms_est_sigma=rms_est_sigma,
rms_est_fraction=rms_est_fraction)
noise = noise_level(accessor.freq_eff, accessor.freq_bw, accessor.tau_time,
accessor.antenna_set, accessor.ncore, accessor.nremote, accessor.nintl
)
rms_check = rms_invalid(rms_qc, noise, low_bound, high_bound)
<|code_end|>
, determine the next line of code. You have imports:
import logging
import tkp.db
import tkp.db.quality as dbquality
from tkp.quality.restoringbeam import beam_invalid
from tkp.quality.rms import rms_invalid, rms_with_clipped_subregion
from tkp.telescope.lofar.noise import noise_level
from tkp.utility import nice_format
and context (class names, function names, or code) available:
# Path: tkp/quality/restoringbeam.py
# def beam_invalid(semibmaj, semibmin, theta, oversampled_x=30, elliptical_x=2.0):
# """ Are the beam shape properties ok?
#
# :param semibmaj/semibmin: size of the beam in pixels
#
# :returns: True/False
# """
#
# formatted = "bmaj=%s and bmin=%s (pixels)" % (nice_format(semibmaj),
# nice_format(semibmin))
#
# if tkp.quality.restoringbeam.infinite(semibmaj, semibmin, theta):
# return "Beam infinte. %s" % formatted
# if tkp.quality.restoringbeam.undersampled(semibmaj, semibmin):
# return "Beam undersampled. %s" % formatted
# elif tkp.quality.restoringbeam.oversampled(semibmaj, semibmin,
# oversampled_x):
# return "Beam oversampled. %s" % formatted
# elif tkp.quality.restoringbeam.highly_elliptical(semibmaj, semibmin, elliptical_x):
# return "Beam too elliptical. %s" % formatted
#
# #TODO: this test has been disabled untill antonia solves issue discribed in #3802
# #elif not tkp.quality.restoringbeam.full_fieldofview(nx, ny, cellsize, fov):
# # return "Full field of view not imaged. Imaged FoV=XXdegrees, Observed FoV=XXdegrees"
#
# else:
# return False
#
# Path: tkp/quality/rms.py
# def rms_invalid(rms, noise, low_bound=1, high_bound=50):
# """
# Is the RMS value of an image outside the plausible range?
#
# :param rms: RMS value of an image, can be computed with
# tkp.quality.statistics.rms
# :param noise: Theoretical noise level of instrument, can be calculated with
# tkp.lofar.noise.noise_level
# :param low_bound: multiplied with noise to define lower threshold
# :param high_bound: multiplied with noise to define upper threshold
# :returns: True/False
# """
# if (rms < noise * low_bound) or (rms > noise * high_bound):
# ratio = rms / noise
# return "rms value (%s) is %s times theoretical noise (%s)" % \
# (nice_format(rms), nice_format(ratio), nice_format(noise))
# else:
# return False
#
# def rms_with_clipped_subregion(data, rms_est_sigma=3, rms_est_fraction=4):
# """
# RMS for quality-control.
#
# Root mean square value calculated from central region of an image.
# We sigma-clip the input-data in an attempt to exclude source-pixels
# and keep only background-pixels.
#
# Args:
# data: A numpy array
# rms_est_sigma: sigma value used for clipping
# rms_est_fraction: determines size of subsection, result will be
# 1/fth of the image size where f=rms_est_fraction
# returns the rms value of a iterative sigma clipped subsection of an image
# """
# return rms(clip(subregion(data, rms_est_fraction), rms_est_sigma))
. Output only the next line. | if not rms_check: |
Given the following code snippet before the placeholder: <|code_start|>
logger = logging.getLogger(__name__)
def reject_check_lofar(accessor, job_config):
lofar_quality_params = job_config['quality_lofar']
quality_params = job_config['quality']
low_bound = lofar_quality_params['low_bound']
high_bound = lofar_quality_params['high_bound']
oversampled_x = quality_params['oversampled_x']
elliptical_x = quality_params['elliptical_x']
min_separation = lofar_quality_params['min_separation']
if accessor.tau_time == 0:
logger.info("image %s REJECTED: tau_time is 0, should be > 0" % accessor.url)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import tkp.db
import tkp.db.quality as dbquality
from tkp.quality.restoringbeam import beam_invalid
from tkp.quality.rms import rms_invalid, rms_with_clipped_subregion
from tkp.telescope.lofar.noise import noise_level
from tkp.utility import nice_format
and context including class names, function names, and sometimes code from other files:
# Path: tkp/quality/restoringbeam.py
# def beam_invalid(semibmaj, semibmin, theta, oversampled_x=30, elliptical_x=2.0):
# """ Are the beam shape properties ok?
#
# :param semibmaj/semibmin: size of the beam in pixels
#
# :returns: True/False
# """
#
# formatted = "bmaj=%s and bmin=%s (pixels)" % (nice_format(semibmaj),
# nice_format(semibmin))
#
# if tkp.quality.restoringbeam.infinite(semibmaj, semibmin, theta):
# return "Beam infinte. %s" % formatted
# if tkp.quality.restoringbeam.undersampled(semibmaj, semibmin):
# return "Beam undersampled. %s" % formatted
# elif tkp.quality.restoringbeam.oversampled(semibmaj, semibmin,
# oversampled_x):
# return "Beam oversampled. %s" % formatted
# elif tkp.quality.restoringbeam.highly_elliptical(semibmaj, semibmin, elliptical_x):
# return "Beam too elliptical. %s" % formatted
#
# #TODO: this test has been disabled untill antonia solves issue discribed in #3802
# #elif not tkp.quality.restoringbeam.full_fieldofview(nx, ny, cellsize, fov):
# # return "Full field of view not imaged. Imaged FoV=XXdegrees, Observed FoV=XXdegrees"
#
# else:
# return False
#
# Path: tkp/quality/rms.py
# def rms_invalid(rms, noise, low_bound=1, high_bound=50):
# """
# Is the RMS value of an image outside the plausible range?
#
# :param rms: RMS value of an image, can be computed with
# tkp.quality.statistics.rms
# :param noise: Theoretical noise level of instrument, can be calculated with
# tkp.lofar.noise.noise_level
# :param low_bound: multiplied with noise to define lower threshold
# :param high_bound: multiplied with noise to define upper threshold
# :returns: True/False
# """
# if (rms < noise * low_bound) or (rms > noise * high_bound):
# ratio = rms / noise
# return "rms value (%s) is %s times theoretical noise (%s)" % \
# (nice_format(rms), nice_format(ratio), nice_format(noise))
# else:
# return False
#
# def rms_with_clipped_subregion(data, rms_est_sigma=3, rms_est_fraction=4):
# """
# RMS for quality-control.
#
# Root mean square value calculated from central region of an image.
# We sigma-clip the input-data in an attempt to exclude source-pixels
# and keep only background-pixels.
#
# Args:
# data: A numpy array
# rms_est_sigma: sigma value used for clipping
# rms_est_fraction: determines size of subsection, result will be
# 1/fth of the image size where f=rms_est_fraction
# returns the rms value of a iterative sigma clipped subsection of an image
# """
# return rms(clip(subregion(data, rms_est_fraction), rms_est_sigma))
. Output only the next line. | return dbquality.reject_reasons['tau_time'], "tau_time is 0" |
Next line prediction: <|code_start|> compare = (alpha / C_n) * numpy.arange(lengthprob+1)[1:] / lengthprob
# Find the last undercrossing, see, e.g., fig. 9 in Miller et al., AJ
# 122, 3492 (2001). Searchsorted is not used because the array is not
# sorted.
try:
index = (numpy.where(prob-compare < 0.)[0]).max()
except ValueError:
# Everything below threshold
return containers.ExtractionResults()
fdr_threshold = numpy.sqrt(-2.0 * numpy.log(n1 * prob[index]))
# Default we require that all source pixels are above the threshold,
# not only the peak pixel. This gives a better guarantee that indeed
# the fraction of false positives is less than fdr_alpha in config.py.
# See, e.g., Hopkins et al., AJ 123, 1086 (2002).
if not anl:
anl = fdr_threshold
return self._pyse(fdr_threshold * self.rmsmap, anl * self.rmsmap,
deblend_nthresh, force_beam)
def flux_at_pixel(self, x, y, numpix=1):
"""Return the background-subtracted flux at a certain position
in the map"""
# numpix is the number of pixels to look around the target.
# e.g. numpix = 1 means a total of 9 pixels, 1 in each direction.
return self.data_bgsubbed[y-numpix:y+numpix+1,
x-numpix:x+numpix+1].max()
@staticmethod
<|code_end|>
. Use current file imports:
(import logging
import itertools
import numpy
import ndimage
from tkp.utility import containers
from tkp.utility.memoize import Memoize
from tkp.sourcefinder import utils
from tkp.sourcefinder import stats
from tkp.sourcefinder import extract
from scipy import ndimage)
and context including class names, function names, or small code snippets from other files:
# Path: tkp/sourcefinder/extract.py
# BIGNUM = 99999.0
# class Island(object):
# class ParamSet(DictMixin):
# class Detection(object):
# def __init__(self, data, rms, chunk, analysis_threshold, detection_map,
# beam, deblend_nthresh, deblend_mincont, structuring_element,
# rms_orig=None, flux_orig=None, subthrrange=None
# ):
# def deblend(self, niter=0):
# def threshold(self):
# def noise(self):
# def sig(self):
# def fit(self, fixed=None):
# def __init__(self, clean_bias=0.0, clean_bias_error=0.0,
# frac_flux_cal_error=0.0, alpha_maj1=2.5, alpha_min1=0.5,
# alpha_maj2=0.5, alpha_min2=2.5, alpha_maj3=1.5, alpha_min3=1.5):
# def __getitem__(self, item):
# def __setitem__(self, item, value):
# def keys(self):
# def calculate_errors(self, noise, beam, threshold):
# def _condon_formulae(self, noise, beam):
# def _error_bars_from_moments(self, noise, beam, threshold):
# def deconvolve_from_clean_beam(self, beam):
# def source_profile_and_errors(data, threshold, noise,
# beam, fixed=None):
# def __init__(self, paramset, imagedata, chunk=None, eps_ra=0, eps_dec=0):
# def __getstate__(self):
# def __setstate__(self, attrdict):
# def __getattr__(self, attrname):
# def __str__(self):
# def __repr__(self):
# def _physical_coordinates(self):
# def pixel_to_spatial(x, y):
# def distance_from(self, x, y):
# def serialize(self, ew_sys_err, ns_sys_err):
. Output only the next line. | def box_slice_about_pixel(x, y, box_radius): |
Using the snippet: <|code_start|> """
insert_rows = 0
total_pages = 0
logging.basicConfig(filename=log_file, level=logging.DEBUG)
print("Starting page data loading at %s." % (
time.strftime("%Y-%m-%d %H:%M:%S %Z",
time.localtime())))
logging.info("Starting page data loading at %s." % (
time.strftime("%Y-%m-%d %H:%M:%S %Z",
time.localtime())))
insert_pages = """LOAD DATA INFILE '%s' INTO TABLE page
FIELDS OPTIONALLY ENCLOSED BY '"'
TERMINATED BY '\t' ESCAPED BY '"'
LINES TERMINATED BY '\n'"""
path_file_page = os.path.join(tmp_dir, etl_prefix + '_page.csv')
# Delete previous versions of tmp files if present
if os.path.isfile(path_file_page):
os.remove(path_file_page)
for page in pages_iter:
total_pages += 1
if insert_rows == 0:
file_page = open(path_file_page, 'w')
writer = csv.writer(file_page, dialect='excel-tab',
lineterminator='\n')
# Write data to tmp file
<|code_end|>
, determine the next line of code. You have imports:
import time
import logging
import csv
import os
from .data_item import DataItem
and context (class names, function names, or code) available:
# Path: wikidat/retrieval/data_item.py
# class DataItem(dict):
# """
# Abstract class for data items to be processed by the system. Must be
# instantiated for any subclass describing a processable data item.
# Example data items: page, revision, user, logitem, etc.
# """
# def __init__(self, *args, **kwargs):
# """
# Constructor method for DataItem objects
# """
# super(DataItem, self).__init__(*args, **kwargs)
#
# def __setitem__(self, key, value):
# # optional processing for data items will go here
# super(DataItem, self).__setitem__(key, value)
. Output only the next line. | try: |
Continue the code snippet: <|code_start|> TERMINATED BY '\t' ESCAPED BY '"'
LINES TERMINATED BY '\n'"""
insert_newuser = """LOAD DATA INFILE '%s' INTO TABLE user_new
FIELDS OPTIONALLY ENCLOSED BY '"'
TERMINATED BY '\t' ESCAPED BY '"'
LINES TERMINATED BY '\n'"""
insert_rights = """LOAD DATA INFILE '%s' INTO TABLE user_level
FIELDS OPTIONALLY ENCLOSED BY '"'
TERMINATED BY '\t' ESCAPED BY '"'
LINES TERMINATED BY '\n'"""
path_file_logitem = os.path.join(tmp_dir, etl_prefix + '_logging.csv')
path_file_block = os.path.join(tmp_dir, etl_prefix + '_block.csv')
path_file_newuser = os.path.join(tmp_dir, etl_prefix + '_user_new.csv')
path_file_rights = os.path.join(tmp_dir, etl_prefix + '_user_level.csv')
# Delete previous versions of tmp files if present
if os.path.isfile(path_file_logitem):
os.remove(path_file_logitem)
if os.path.isfile(path_file_block):
os.remove(path_file_block)
if os.path.isfile(path_file_newuser):
os.remove(path_file_newuser)
if os.path.isfile(path_file_rights):
os.remove(path_file_rights)
for logdict in log_iter:
total_logs += 1
<|code_end|>
. Use current file imports:
from .data_item import DataItem
import dateutil.parser
import ipaddress
import datetime
import re
import os
import csv
import time
import logging
and context (classes, functions, or code) from other files:
# Path: wikidat/retrieval/data_item.py
# class DataItem(dict):
# """
# Abstract class for data items to be processed by the system. Must be
# instantiated for any subclass describing a processable data item.
# Example data items: page, revision, user, logitem, etc.
# """
# def __init__(self, *args, **kwargs):
# """
# Constructor method for DataItem objects
# """
# super(DataItem, self).__init__(*args, **kwargs)
#
# def __setitem__(self, key, value):
# # optional processing for data items will go here
# super(DataItem, self).__setitem__(key, value)
. Output only the next line. | logitem = logdict['logitem'] |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Apr 10 18:02:16 2014
Download manager for dump files
@author: jfelipe
"""
class DumpIntegrityError(Exception):
"""Exception raised for errors in the input.
Attributes:
msg -- explanation of the error
"""
def __init__(self, file_path):
self.file_path = file_path
self.msg = ("""Dump file integrity error detected!\n File: {0}"""
<|code_end|>
using the current file's imports:
from bs4 import BeautifulSoup
from wikidat.utils import misc
import multiprocessing as mp
import itertools
import requests
import re
import os
import sys
import hashlib
import logging
and any relevant context from other files:
# Path: wikidat/utils/misc.py
# SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
# 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
# def hfile_size(size, kb_1024_bytes=True):
. Output only the next line. | .format(file_path)) |
Continue the code snippet: <|code_start|>
class RequestError(Exception):
pass
def error_on_request(url, request):
raise RequestError("CIM Request")
<|code_end|>
. Use current file imports:
from httmock import HTTMock, with_httmock
from xml.dom.minidom import parseString
from django.test import TestCase
from authorizenet.models import CustomerProfile
from .utils import create_user, xml_to_dict
from .mocks import cim_url_match, customer_profile_success, delete_success
from .test_data import create_empty_profile_success, delete_profile_success
and context (classes, functions, or code) from other files:
# Path: authorizenet/models.py
# class CustomerProfile(models.Model):
#
# """Authorize.NET customer profile"""
#
# customer = models.OneToOneField(settings.CUSTOMER_MODEL,
# related_name='customer_profile')
# profile_id = models.CharField(max_length=50)
#
# def save(self, *args, **kwargs):
# """If creating new instance, create profile on Authorize.NET also"""
# data = kwargs.pop('data', {})
# sync = kwargs.pop('sync', True)
# if not self.id and sync:
# self.push_to_server(data)
# super(CustomerProfile, self).save(*args, **kwargs)
#
# def delete(self):
# """Delete the customer profile remotely and locally"""
# response = delete_profile(self.profile_id)
# response.raise_if_error()
# super(CustomerProfile, self).delete()
#
# def push_to_server(self, data):
# """Create customer profile for given ``customer`` on Authorize.NET"""
# output = add_profile(self.customer.pk, data, data)
# output['response'].raise_if_error()
# self.profile_id = output['profile_id']
# self.payment_profile_ids = output['payment_profile_ids']
#
# def sync(self):
# """Overwrite local customer profile data with remote data"""
# output = get_profile(self.profile_id)
# output['response'].raise_if_error()
# for payment_profile in output['payment_profiles']:
# instance, created = CustomerPaymentProfile.objects.get_or_create(
# customer_profile=self,
# payment_profile_id=payment_profile['payment_profile_id']
# )
# instance.sync(payment_profile)
#
# objects = CustomerProfileManager()
#
# def __unicode__(self):
# return self.profile_id
#
# Path: tests/tests/utils.py
# def create_user(id=None, username='', password=''):
# user = User(username=username)
# user.id = id
# user.set_password(password)
# user.save()
# return user
#
# def xml_to_dict(node):
# """Recursively convert minidom XML node to dictionary"""
# node_data = {}
# if node.nodeType == node.TEXT_NODE:
# node_data = node.data
# elif node.nodeType not in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
# node_data.update(node.attributes.items())
# if node.nodeType not in (node.TEXT_NODE, node.DOCUMENT_TYPE_NODE):
# for child in node.childNodes:
# child_name, child_data = xml_to_dict(child)
# if not child_data:
# child_data = ''
# if child_name not in node_data:
# node_data[child_name] = child_data
# else:
# if not isinstance(node_data[child_name], list):
# node_data[child_name] = [node_data[child_name]]
# node_data[child_name].append(child_data)
# if node_data.keys() == ['#text']:
# node_data = node_data['#text']
# if node.nodeType == node.DOCUMENT_NODE:
# return node_data
# else:
# return node.nodeName, node_data
#
# Path: tests/tests/mocks.py
#
# Path: tests/tests/test_data.py
. Output only the next line. | class CustomerProfileModelTests(TestCase): |
Here is a snippet: <|code_start|>
class RequestError(Exception):
pass
def error_on_request(url, request):
<|code_end|>
. Write the next line using the current file imports:
from httmock import HTTMock, with_httmock
from xml.dom.minidom import parseString
from django.test import TestCase
from authorizenet.models import CustomerProfile
from .utils import create_user, xml_to_dict
from .mocks import cim_url_match, customer_profile_success, delete_success
from .test_data import create_empty_profile_success, delete_profile_success
and context from other files:
# Path: authorizenet/models.py
# class CustomerProfile(models.Model):
#
# """Authorize.NET customer profile"""
#
# customer = models.OneToOneField(settings.CUSTOMER_MODEL,
# related_name='customer_profile')
# profile_id = models.CharField(max_length=50)
#
# def save(self, *args, **kwargs):
# """If creating new instance, create profile on Authorize.NET also"""
# data = kwargs.pop('data', {})
# sync = kwargs.pop('sync', True)
# if not self.id and sync:
# self.push_to_server(data)
# super(CustomerProfile, self).save(*args, **kwargs)
#
# def delete(self):
# """Delete the customer profile remotely and locally"""
# response = delete_profile(self.profile_id)
# response.raise_if_error()
# super(CustomerProfile, self).delete()
#
# def push_to_server(self, data):
# """Create customer profile for given ``customer`` on Authorize.NET"""
# output = add_profile(self.customer.pk, data, data)
# output['response'].raise_if_error()
# self.profile_id = output['profile_id']
# self.payment_profile_ids = output['payment_profile_ids']
#
# def sync(self):
# """Overwrite local customer profile data with remote data"""
# output = get_profile(self.profile_id)
# output['response'].raise_if_error()
# for payment_profile in output['payment_profiles']:
# instance, created = CustomerPaymentProfile.objects.get_or_create(
# customer_profile=self,
# payment_profile_id=payment_profile['payment_profile_id']
# )
# instance.sync(payment_profile)
#
# objects = CustomerProfileManager()
#
# def __unicode__(self):
# return self.profile_id
#
# Path: tests/tests/utils.py
# def create_user(id=None, username='', password=''):
# user = User(username=username)
# user.id = id
# user.set_password(password)
# user.save()
# return user
#
# def xml_to_dict(node):
# """Recursively convert minidom XML node to dictionary"""
# node_data = {}
# if node.nodeType == node.TEXT_NODE:
# node_data = node.data
# elif node.nodeType not in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
# node_data.update(node.attributes.items())
# if node.nodeType not in (node.TEXT_NODE, node.DOCUMENT_TYPE_NODE):
# for child in node.childNodes:
# child_name, child_data = xml_to_dict(child)
# if not child_data:
# child_data = ''
# if child_name not in node_data:
# node_data[child_name] = child_data
# else:
# if not isinstance(node_data[child_name], list):
# node_data[child_name] = [node_data[child_name]]
# node_data[child_name].append(child_data)
# if node_data.keys() == ['#text']:
# node_data = node_data['#text']
# if node.nodeType == node.DOCUMENT_NODE:
# return node_data
# else:
# return node.nodeName, node_data
#
# Path: tests/tests/mocks.py
#
# Path: tests/tests/test_data.py
, which may include functions, classes, or code. Output only the next line. | raise RequestError("CIM Request") |
Continue the code snippet: <|code_start|>
class RequestError(Exception):
pass
def error_on_request(url, request):
<|code_end|>
. Use current file imports:
from httmock import HTTMock, with_httmock
from xml.dom.minidom import parseString
from django.test import TestCase
from authorizenet.models import CustomerProfile
from .utils import create_user, xml_to_dict
from .mocks import cim_url_match, customer_profile_success, delete_success
from .test_data import create_empty_profile_success, delete_profile_success
and context (classes, functions, or code) from other files:
# Path: authorizenet/models.py
# class CustomerProfile(models.Model):
#
# """Authorize.NET customer profile"""
#
# customer = models.OneToOneField(settings.CUSTOMER_MODEL,
# related_name='customer_profile')
# profile_id = models.CharField(max_length=50)
#
# def save(self, *args, **kwargs):
# """If creating new instance, create profile on Authorize.NET also"""
# data = kwargs.pop('data', {})
# sync = kwargs.pop('sync', True)
# if not self.id and sync:
# self.push_to_server(data)
# super(CustomerProfile, self).save(*args, **kwargs)
#
# def delete(self):
# """Delete the customer profile remotely and locally"""
# response = delete_profile(self.profile_id)
# response.raise_if_error()
# super(CustomerProfile, self).delete()
#
# def push_to_server(self, data):
# """Create customer profile for given ``customer`` on Authorize.NET"""
# output = add_profile(self.customer.pk, data, data)
# output['response'].raise_if_error()
# self.profile_id = output['profile_id']
# self.payment_profile_ids = output['payment_profile_ids']
#
# def sync(self):
# """Overwrite local customer profile data with remote data"""
# output = get_profile(self.profile_id)
# output['response'].raise_if_error()
# for payment_profile in output['payment_profiles']:
# instance, created = CustomerPaymentProfile.objects.get_or_create(
# customer_profile=self,
# payment_profile_id=payment_profile['payment_profile_id']
# )
# instance.sync(payment_profile)
#
# objects = CustomerProfileManager()
#
# def __unicode__(self):
# return self.profile_id
#
# Path: tests/tests/utils.py
# def create_user(id=None, username='', password=''):
# user = User(username=username)
# user.id = id
# user.set_password(password)
# user.save()
# return user
#
# def xml_to_dict(node):
# """Recursively convert minidom XML node to dictionary"""
# node_data = {}
# if node.nodeType == node.TEXT_NODE:
# node_data = node.data
# elif node.nodeType not in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
# node_data.update(node.attributes.items())
# if node.nodeType not in (node.TEXT_NODE, node.DOCUMENT_TYPE_NODE):
# for child in node.childNodes:
# child_name, child_data = xml_to_dict(child)
# if not child_data:
# child_data = ''
# if child_name not in node_data:
# node_data[child_name] = child_data
# else:
# if not isinstance(node_data[child_name], list):
# node_data[child_name] = [node_data[child_name]]
# node_data[child_name].append(child_data)
# if node_data.keys() == ['#text']:
# node_data = node_data['#text']
# if node.nodeType == node.DOCUMENT_NODE:
# return node_data
# else:
# return node.nodeName, node_data
#
# Path: tests/tests/mocks.py
#
# Path: tests/tests/test_data.py
. Output only the next line. | raise RequestError("CIM Request") |
Predict the next line for this snippet: <|code_start|>
class RequestError(Exception):
pass
def error_on_request(url, request):
raise RequestError("CIM Request")
<|code_end|>
with the help of current file imports:
from httmock import HTTMock, with_httmock
from xml.dom.minidom import parseString
from django.test import TestCase
from authorizenet.models import CustomerProfile
from .utils import create_user, xml_to_dict
from .mocks import cim_url_match, customer_profile_success, delete_success
from .test_data import create_empty_profile_success, delete_profile_success
and context from other files:
# Path: authorizenet/models.py
# class CustomerProfile(models.Model):
#
# """Authorize.NET customer profile"""
#
# customer = models.OneToOneField(settings.CUSTOMER_MODEL,
# related_name='customer_profile')
# profile_id = models.CharField(max_length=50)
#
# def save(self, *args, **kwargs):
# """If creating new instance, create profile on Authorize.NET also"""
# data = kwargs.pop('data', {})
# sync = kwargs.pop('sync', True)
# if not self.id and sync:
# self.push_to_server(data)
# super(CustomerProfile, self).save(*args, **kwargs)
#
# def delete(self):
# """Delete the customer profile remotely and locally"""
# response = delete_profile(self.profile_id)
# response.raise_if_error()
# super(CustomerProfile, self).delete()
#
# def push_to_server(self, data):
# """Create customer profile for given ``customer`` on Authorize.NET"""
# output = add_profile(self.customer.pk, data, data)
# output['response'].raise_if_error()
# self.profile_id = output['profile_id']
# self.payment_profile_ids = output['payment_profile_ids']
#
# def sync(self):
# """Overwrite local customer profile data with remote data"""
# output = get_profile(self.profile_id)
# output['response'].raise_if_error()
# for payment_profile in output['payment_profiles']:
# instance, created = CustomerPaymentProfile.objects.get_or_create(
# customer_profile=self,
# payment_profile_id=payment_profile['payment_profile_id']
# )
# instance.sync(payment_profile)
#
# objects = CustomerProfileManager()
#
# def __unicode__(self):
# return self.profile_id
#
# Path: tests/tests/utils.py
# def create_user(id=None, username='', password=''):
# user = User(username=username)
# user.id = id
# user.set_password(password)
# user.save()
# return user
#
# def xml_to_dict(node):
# """Recursively convert minidom XML node to dictionary"""
# node_data = {}
# if node.nodeType == node.TEXT_NODE:
# node_data = node.data
# elif node.nodeType not in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
# node_data.update(node.attributes.items())
# if node.nodeType not in (node.TEXT_NODE, node.DOCUMENT_TYPE_NODE):
# for child in node.childNodes:
# child_name, child_data = xml_to_dict(child)
# if not child_data:
# child_data = ''
# if child_name not in node_data:
# node_data[child_name] = child_data
# else:
# if not isinstance(node_data[child_name], list):
# node_data[child_name] = [node_data[child_name]]
# node_data[child_name].append(child_data)
# if node_data.keys() == ['#text']:
# node_data = node_data['#text']
# if node.nodeType == node.DOCUMENT_NODE:
# return node_data
# else:
# return node.nodeName, node_data
#
# Path: tests/tests/mocks.py
#
# Path: tests/tests/test_data.py
, which may contain function names, class names, or code. Output only the next line. | class CustomerProfileModelTests(TestCase): |
Given the code snippet: <|code_start|>
def get_fingerprint(x_fp_sequence, x_fp_timestamp, x_amount):
msg = '^'.join([settings.LOGIN_ID,
x_fp_sequence,
x_fp_timestamp,
x_amount
]) + '^'
return hmac.new(settings.TRANSACTION_KEY, msg).hexdigest()
def extract_form_data(form_data):
return dict(map(lambda x: ('x_' + x[0], x[1]),
form_data.items()))
AIM_DEFAULT_DICT = {
'x_login': settings.LOGIN_ID,
'x_tran_key': settings.TRANSACTION_KEY,
<|code_end|>
, generate the next line using the imports in this file:
import hmac
from django.core.exceptions import ImproperlyConfigured
from authorizenet.conf import settings
from authorizenet.helpers import AIMPaymentHelper
from authorizenet.models import Response
from authorizenet.signals import payment_was_successful, payment_was_flagged
and context (functions, classes, or occasionally code) from other files:
# Path: authorizenet/conf.py
# class Settings(object):
# class Default:
# CUSTOMER_MODEL = getattr(
# django_settings, 'AUTH_USER_MODEL', "auth.User")
# DELIM_CHAR = "|"
# FORCE_TEST_REQUEST = False
# EMAIL_CUSTOMER = None
# MD5_HASH = ""
# def __init__(self):
# def __getattr__(self, name):
#
# Path: authorizenet/helpers.py
# class AIMPaymentHelper(object):
# def __init__(self, defaults):
# self.defaults = defaults
# if settings.DEBUG:
# self.endpoint = AUTHNET_TEST_POST_URL
# else:
# self.endpoint = AUTHNET_POST_URL
#
# def get_response(self, data):
# final_data = dict(self.defaults)
# final_data.update(data)
# c = final_data['x_delim_char']
# # Escape delimiter characters in request fields
# for k, v in final_data.items():
# if k != 'x_delim_char':
# final_data[k] = unicode(v).replace(c, "\\%s" % c)
# response = requests.post(self.endpoint, data=final_data)
# # Split response by delimiter,
# # unescaping delimiter characters in fields
# response_list = re.split("(?<!\\\\)\%s" % c, response.text)
# response_list = map(lambda s: s.replace("\\%s" % c, c),
# response_list)
# return response_list
#
# Path: authorizenet/models.py
# class Response(models.Model):
#
# """Transaction Response (See Section 4 of AIM Developer Guide)"""
#
# response_code = models.CharField(max_length=2, choices=RESPONSE_CHOICES)
# response_subcode = models.CharField(max_length=10)
# response_reason_code = models.CharField(max_length=15)
# response_reason_text = models.TextField()
# auth_code = models.CharField(max_length=10)
# avs_code = models.CharField(max_length=10,
# choices=AVS_RESPONSE_CODE_CHOICES)
# trans_id = models.CharField(max_length=255, db_index=True)
# invoice_num = models.CharField(max_length=20, blank=True)
# description = models.CharField(max_length=255)
# amount = models.CharField(max_length=16)
# method = models.CharField(max_length=10, choices=METHOD_CHOICES)
# type = models.CharField(max_length=20,
# choices=TYPE_CHOICES,
# db_index=True)
# cust_id = models.CharField(max_length=20)
# first_name = models.CharField(max_length=50)
# last_name = models.CharField(max_length=50)
# company = models.CharField(max_length=50)
# address = models.CharField(max_length=60)
# city = models.CharField(max_length=40)
# state = models.CharField(max_length=40)
# zip = models.CharField(max_length=20)
# country = models.CharField(max_length=60)
# phone = models.CharField(max_length=25)
# fax = models.CharField(max_length=25)
# email = models.CharField(max_length=255)
# ship_to_first_name = models.CharField(max_length=50, blank=True)
# ship_to_last_name = models.CharField(max_length=50, blank=True)
# ship_to_company = models.CharField(max_length=50, blank=True)
# ship_to_address = models.CharField(max_length=60, blank=True)
# ship_to_city = models.CharField(max_length=40, blank=True)
# ship_to_state = models.CharField(max_length=40, blank=True)
# ship_to_zip = models.CharField(max_length=20, blank=True)
# ship_to_country = models.CharField(max_length=60, blank=True)
# tax = models.CharField(max_length=16, blank=True)
# duty = models.CharField(max_length=16, blank=True)
# freight = models.CharField(max_length=16, blank=True)
# tax_exempt = models.CharField(max_length=16, blank=True)
# po_num = models.CharField(max_length=25, blank=True)
# MD5_Hash = models.CharField(max_length=255)
# cvv2_resp_code = models.CharField(max_length=2,
# choices=CVV2_RESPONSE_CODE_CHOICES,
# blank=True)
# cavv_response = models.CharField(max_length=2,
# choices=CAVV_RESPONSE_CODE_CHOICES,
# blank=True)
#
# test_request = models.CharField(max_length=10, default="FALSE", blank=True)
#
# card_type = models.CharField(max_length=10, default="", blank=True)
# account_number = models.CharField(max_length=10, default="", blank=True)
# created = models.DateTimeField(auto_now_add=True, null=True)
#
# objects = ResponseManager()
#
# @property
# def is_approved(self):
# return self.response_code == '1'
#
# def __unicode__(self):
# return u"response_code: %s, trans_id: %s, amount: %s, type: %s" % \
# (self.response_code, self.trans_id, self.amount, self.type)
#
# Path: authorizenet/signals.py
. Output only the next line. | 'x_delim_data': "TRUE", |
Given snippet: <|code_start|>
def get_fingerprint(x_fp_sequence, x_fp_timestamp, x_amount):
msg = '^'.join([settings.LOGIN_ID,
x_fp_sequence,
x_fp_timestamp,
x_amount
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hmac
from django.core.exceptions import ImproperlyConfigured
from authorizenet.conf import settings
from authorizenet.helpers import AIMPaymentHelper
from authorizenet.models import Response
from authorizenet.signals import payment_was_successful, payment_was_flagged
and context:
# Path: authorizenet/conf.py
# class Settings(object):
# class Default:
# CUSTOMER_MODEL = getattr(
# django_settings, 'AUTH_USER_MODEL', "auth.User")
# DELIM_CHAR = "|"
# FORCE_TEST_REQUEST = False
# EMAIL_CUSTOMER = None
# MD5_HASH = ""
# def __init__(self):
# def __getattr__(self, name):
#
# Path: authorizenet/helpers.py
# class AIMPaymentHelper(object):
# def __init__(self, defaults):
# self.defaults = defaults
# if settings.DEBUG:
# self.endpoint = AUTHNET_TEST_POST_URL
# else:
# self.endpoint = AUTHNET_POST_URL
#
# def get_response(self, data):
# final_data = dict(self.defaults)
# final_data.update(data)
# c = final_data['x_delim_char']
# # Escape delimiter characters in request fields
# for k, v in final_data.items():
# if k != 'x_delim_char':
# final_data[k] = unicode(v).replace(c, "\\%s" % c)
# response = requests.post(self.endpoint, data=final_data)
# # Split response by delimiter,
# # unescaping delimiter characters in fields
# response_list = re.split("(?<!\\\\)\%s" % c, response.text)
# response_list = map(lambda s: s.replace("\\%s" % c, c),
# response_list)
# return response_list
#
# Path: authorizenet/models.py
# class Response(models.Model):
#
# """Transaction Response (See Section 4 of AIM Developer Guide)"""
#
# response_code = models.CharField(max_length=2, choices=RESPONSE_CHOICES)
# response_subcode = models.CharField(max_length=10)
# response_reason_code = models.CharField(max_length=15)
# response_reason_text = models.TextField()
# auth_code = models.CharField(max_length=10)
# avs_code = models.CharField(max_length=10,
# choices=AVS_RESPONSE_CODE_CHOICES)
# trans_id = models.CharField(max_length=255, db_index=True)
# invoice_num = models.CharField(max_length=20, blank=True)
# description = models.CharField(max_length=255)
# amount = models.CharField(max_length=16)
# method = models.CharField(max_length=10, choices=METHOD_CHOICES)
# type = models.CharField(max_length=20,
# choices=TYPE_CHOICES,
# db_index=True)
# cust_id = models.CharField(max_length=20)
# first_name = models.CharField(max_length=50)
# last_name = models.CharField(max_length=50)
# company = models.CharField(max_length=50)
# address = models.CharField(max_length=60)
# city = models.CharField(max_length=40)
# state = models.CharField(max_length=40)
# zip = models.CharField(max_length=20)
# country = models.CharField(max_length=60)
# phone = models.CharField(max_length=25)
# fax = models.CharField(max_length=25)
# email = models.CharField(max_length=255)
# ship_to_first_name = models.CharField(max_length=50, blank=True)
# ship_to_last_name = models.CharField(max_length=50, blank=True)
# ship_to_company = models.CharField(max_length=50, blank=True)
# ship_to_address = models.CharField(max_length=60, blank=True)
# ship_to_city = models.CharField(max_length=40, blank=True)
# ship_to_state = models.CharField(max_length=40, blank=True)
# ship_to_zip = models.CharField(max_length=20, blank=True)
# ship_to_country = models.CharField(max_length=60, blank=True)
# tax = models.CharField(max_length=16, blank=True)
# duty = models.CharField(max_length=16, blank=True)
# freight = models.CharField(max_length=16, blank=True)
# tax_exempt = models.CharField(max_length=16, blank=True)
# po_num = models.CharField(max_length=25, blank=True)
# MD5_Hash = models.CharField(max_length=255)
# cvv2_resp_code = models.CharField(max_length=2,
# choices=CVV2_RESPONSE_CODE_CHOICES,
# blank=True)
# cavv_response = models.CharField(max_length=2,
# choices=CAVV_RESPONSE_CODE_CHOICES,
# blank=True)
#
# test_request = models.CharField(max_length=10, default="FALSE", blank=True)
#
# card_type = models.CharField(max_length=10, default="", blank=True)
# account_number = models.CharField(max_length=10, default="", blank=True)
# created = models.DateTimeField(auto_now_add=True, null=True)
#
# objects = ResponseManager()
#
# @property
# def is_approved(self):
# return self.response_code == '1'
#
# def __unicode__(self):
# return u"response_code: %s, trans_id: %s, amount: %s, type: %s" % \
# (self.response_code, self.trans_id, self.amount, self.type)
#
# Path: authorizenet/signals.py
which might include code, classes, or functions. Output only the next line. | ]) + '^' |
Predict the next line for this snippet: <|code_start|>
def get_fingerprint(x_fp_sequence, x_fp_timestamp, x_amount):
msg = '^'.join([settings.LOGIN_ID,
x_fp_sequence,
x_fp_timestamp,
x_amount
]) + '^'
return hmac.new(settings.TRANSACTION_KEY, msg).hexdigest()
def extract_form_data(form_data):
return dict(map(lambda x: ('x_' + x[0], x[1]),
form_data.items()))
<|code_end|>
with the help of current file imports:
import hmac
from django.core.exceptions import ImproperlyConfigured
from authorizenet.conf import settings
from authorizenet.helpers import AIMPaymentHelper
from authorizenet.models import Response
from authorizenet.signals import payment_was_successful, payment_was_flagged
and context from other files:
# Path: authorizenet/conf.py
# class Settings(object):
# class Default:
# CUSTOMER_MODEL = getattr(
# django_settings, 'AUTH_USER_MODEL', "auth.User")
# DELIM_CHAR = "|"
# FORCE_TEST_REQUEST = False
# EMAIL_CUSTOMER = None
# MD5_HASH = ""
# def __init__(self):
# def __getattr__(self, name):
#
# Path: authorizenet/helpers.py
# class AIMPaymentHelper(object):
# def __init__(self, defaults):
# self.defaults = defaults
# if settings.DEBUG:
# self.endpoint = AUTHNET_TEST_POST_URL
# else:
# self.endpoint = AUTHNET_POST_URL
#
# def get_response(self, data):
# final_data = dict(self.defaults)
# final_data.update(data)
# c = final_data['x_delim_char']
# # Escape delimiter characters in request fields
# for k, v in final_data.items():
# if k != 'x_delim_char':
# final_data[k] = unicode(v).replace(c, "\\%s" % c)
# response = requests.post(self.endpoint, data=final_data)
# # Split response by delimiter,
# # unescaping delimiter characters in fields
# response_list = re.split("(?<!\\\\)\%s" % c, response.text)
# response_list = map(lambda s: s.replace("\\%s" % c, c),
# response_list)
# return response_list
#
# Path: authorizenet/models.py
# class Response(models.Model):
#
# """Transaction Response (See Section 4 of AIM Developer Guide)"""
#
# response_code = models.CharField(max_length=2, choices=RESPONSE_CHOICES)
# response_subcode = models.CharField(max_length=10)
# response_reason_code = models.CharField(max_length=15)
# response_reason_text = models.TextField()
# auth_code = models.CharField(max_length=10)
# avs_code = models.CharField(max_length=10,
# choices=AVS_RESPONSE_CODE_CHOICES)
# trans_id = models.CharField(max_length=255, db_index=True)
# invoice_num = models.CharField(max_length=20, blank=True)
# description = models.CharField(max_length=255)
# amount = models.CharField(max_length=16)
# method = models.CharField(max_length=10, choices=METHOD_CHOICES)
# type = models.CharField(max_length=20,
# choices=TYPE_CHOICES,
# db_index=True)
# cust_id = models.CharField(max_length=20)
# first_name = models.CharField(max_length=50)
# last_name = models.CharField(max_length=50)
# company = models.CharField(max_length=50)
# address = models.CharField(max_length=60)
# city = models.CharField(max_length=40)
# state = models.CharField(max_length=40)
# zip = models.CharField(max_length=20)
# country = models.CharField(max_length=60)
# phone = models.CharField(max_length=25)
# fax = models.CharField(max_length=25)
# email = models.CharField(max_length=255)
# ship_to_first_name = models.CharField(max_length=50, blank=True)
# ship_to_last_name = models.CharField(max_length=50, blank=True)
# ship_to_company = models.CharField(max_length=50, blank=True)
# ship_to_address = models.CharField(max_length=60, blank=True)
# ship_to_city = models.CharField(max_length=40, blank=True)
# ship_to_state = models.CharField(max_length=40, blank=True)
# ship_to_zip = models.CharField(max_length=20, blank=True)
# ship_to_country = models.CharField(max_length=60, blank=True)
# tax = models.CharField(max_length=16, blank=True)
# duty = models.CharField(max_length=16, blank=True)
# freight = models.CharField(max_length=16, blank=True)
# tax_exempt = models.CharField(max_length=16, blank=True)
# po_num = models.CharField(max_length=25, blank=True)
# MD5_Hash = models.CharField(max_length=255)
# cvv2_resp_code = models.CharField(max_length=2,
# choices=CVV2_RESPONSE_CODE_CHOICES,
# blank=True)
# cavv_response = models.CharField(max_length=2,
# choices=CAVV_RESPONSE_CODE_CHOICES,
# blank=True)
#
# test_request = models.CharField(max_length=10, default="FALSE", blank=True)
#
# card_type = models.CharField(max_length=10, default="", blank=True)
# account_number = models.CharField(max_length=10, default="", blank=True)
# created = models.DateTimeField(auto_now_add=True, null=True)
#
# objects = ResponseManager()
#
# @property
# def is_approved(self):
# return self.response_code == '1'
#
# def __unicode__(self):
# return u"response_code: %s, trans_id: %s, amount: %s, type: %s" % \
# (self.response_code, self.trans_id, self.amount, self.type)
#
# Path: authorizenet/signals.py
, which may contain function names, class names, or code. Output only the next line. | AIM_DEFAULT_DICT = { |
Next line prediction: <|code_start|>
urlpatterns = patterns(
'',
url(r"^customers/create$", CreateCustomerView.as_view()),
url(r"^customers/update$", UpdateCustomerView.as_view()),
url(r"^success$", success_view),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url, patterns
from .views import CreateCustomerView, UpdateCustomerView, success_view)
and context including class names, function names, or small code snippets from other files:
# Path: tests/views.py
# class CreateCustomerView(PaymentProfileCreateView):
# def get_success_url(self):
# return '/success'
#
# class UpdateCustomerView(PaymentProfileUpdateView):
#
# def get_object(self):
# return self.request.user.customer_profile.payment_profiles.get()
#
# def get_success_url(self):
# return '/success'
#
# def success_view(request):
# return HttpResponse("success")
. Output only the next line. | ) |
Predict the next line for this snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r"^customers/create$", CreateCustomerView.as_view()),
url(r"^customers/update$", UpdateCustomerView.as_view()),
url(r"^success$", success_view),
<|code_end|>
with the help of current file imports:
from django.conf.urls import url, patterns
from .views import CreateCustomerView, UpdateCustomerView, success_view
and context from other files:
# Path: tests/views.py
# class CreateCustomerView(PaymentProfileCreateView):
# def get_success_url(self):
# return '/success'
#
# class UpdateCustomerView(PaymentProfileUpdateView):
#
# def get_object(self):
# return self.request.user.customer_profile.payment_profiles.get()
#
# def get_success_url(self):
# return '/success'
#
# def success_view(request):
# return HttpResponse("success")
, which may contain function names, class names, or code. Output only the next line. | ) |
Given snippet: <|code_start|>
class CreateCustomerView(PaymentProfileCreateView):
def get_success_url(self):
return '/success'
class UpdateCustomerView(PaymentProfileUpdateView):
def get_object(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http import HttpResponse
from authorizenet.views import PaymentProfileCreateView, PaymentProfileUpdateView
and context:
# Path: authorizenet/views.py
# class PaymentProfileCreateView(CreateView):
# """
# View for creating a CustomerPaymentProfile instance
#
# CustomerProfile instance will be created automatically if needed.
# """
#
# template_name = 'authorizenet/create_payment_profile.html'
# form_class = CustomerPaymentForm
#
# def get_form_kwargs(self):
# kwargs = super(PaymentProfileCreateView, self).get_form_kwargs()
# kwargs['customer'] = self.request.user
# return kwargs
#
# class PaymentProfileUpdateView(UpdateView):
# """
# View for modifying an existing CustomerPaymentProfile instance
# """
#
# template_name = 'authorizenet/update_payment_profile.html'
# form_class = CustomerPaymentForm
#
# def get_form_kwargs(self):
# kwargs = super(PaymentProfileUpdateView, self).get_form_kwargs()
# kwargs['customer'] = self.request.user
# return kwargs
which might include code, classes, or functions. Output only the next line. | return self.request.user.customer_profile.payment_profiles.get() |
Here is a snippet: <|code_start|>
class CreateCustomerView(PaymentProfileCreateView):
def get_success_url(self):
return '/success'
class UpdateCustomerView(PaymentProfileUpdateView):
def get_object(self):
return self.request.user.customer_profile.payment_profiles.get()
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponse
from authorizenet.views import PaymentProfileCreateView, PaymentProfileUpdateView
and context from other files:
# Path: authorizenet/views.py
# class PaymentProfileCreateView(CreateView):
# """
# View for creating a CustomerPaymentProfile instance
#
# CustomerProfile instance will be created automatically if needed.
# """
#
# template_name = 'authorizenet/create_payment_profile.html'
# form_class = CustomerPaymentForm
#
# def get_form_kwargs(self):
# kwargs = super(PaymentProfileCreateView, self).get_form_kwargs()
# kwargs['customer'] = self.request.user
# return kwargs
#
# class PaymentProfileUpdateView(UpdateView):
# """
# View for modifying an existing CustomerPaymentProfile instance
# """
#
# template_name = 'authorizenet/update_payment_profile.html'
# form_class = CustomerPaymentForm
#
# def get_form_kwargs(self):
# kwargs = super(PaymentProfileUpdateView, self).get_form_kwargs()
# kwargs['customer'] = self.request.user
# return kwargs
, which may include functions, classes, or code. Output only the next line. | def get_success_url(self): |
Next line prediction: <|code_start|>class Item(models.Model):
title = models.CharField(max_length=55)
price = models.DecimalField(max_digits=8, decimal_places=2)
def __unicode__(self):
return self.title
class Invoice(models.Model):
customer = models.ForeignKey(Customer)
item = models.ForeignKey(Item)
def __unicode__(self):
return u"<Invoice: %d - %s>" % (self.id, self.customer.user.username)
def create_customer_profile(sender, instance=None, **kwargs):
if instance is None:
return
profile, created = Customer.objects.get_or_create(user=instance)
post_save.connect(create_customer_profile, sender=User)
def successfull_payment(sender, **kwargs):
response = sender
# do something with the response
<|code_end|>
. Use current file imports:
(from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.localflavor.us.models import PhoneNumberField, USStateField
from authorizenet.signals import payment_was_successful, payment_was_flagged)
and context including class names, function names, or small code snippets from other files:
# Path: authorizenet/signals.py
. Output only the next line. | def flagged_payment(sender, **kwargs): |
Given snippet: <|code_start|>
ADDRESS_CHOICES = (
('billing', 'Billing'),
('shipping', 'Shipping'),
)
class Customer(models.Model):
user = models.ForeignKey(User)
shipping_same_as_billing = models.BooleanField(default=True)
cim_profile_id = models.CharField(max_length=10)
def __unicode__(self):
return self.user.username
class Address(models.Model):
type = models.CharField(max_length=10, choices=ADDRESS_CHOICES)
customer = models.ForeignKey(Customer)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
company = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=60)
city = models.CharField(max_length=40)
state = USStateField()
zip_code = models.CharField(max_length=20)
phone = PhoneNumberField(blank=True)
fax = PhoneNumberField(blank=True)
def __unicode__(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.localflavor.us.models import PhoneNumberField, USStateField
from authorizenet.signals import payment_was_successful, payment_was_flagged
and context:
# Path: authorizenet/signals.py
which might include code, classes, or functions. Output only the next line. | return self.customer.user.username |
Based on the snippet: <|code_start|>
COMMANDS_PATH = PATH + "/commands"
VERSION = get_version()
class CommandsManager:
def __init__(self):
self.commands = self.parse()
# This command is used to load the modules when needed
<|code_end|>
, predict the immediate next line with the help of imports:
import inspect
import json
import jsonpickle
import logging
import os
import toml
from argparser import ArgumentsParser
from config import PATH
from util import get_version
and context (classes, functions, sometimes code) from other files:
# Path: argparser.py
# class ArgumentsParser:
# def __init__(self, params, arguments, method):
# if not isinstance(arguments, dict):
# raise Exception("Command arguments is not a dict")
#
# self.params = params
# self.arguments = arguments
# self.method = method
# self._parse()
#
# def _check_required(self, required, key):
# if required == False:
# return
#
# if required == True and key in self.params:
# return
#
# if required == True and key not in self.params:
# raise KeyError(f"{key} is required and was not given")
#
# def _parse(self):
# for key, val in self.arguments.items():
# if isinstance(val, dict):
# if "required" in val:
# required = val["required"]
#
# if isinstance(val["required"], list) and self.method in required:
# self._check_required(True, key)
# else:
# self._check_required(required, key)
#
# if "type" in val:
# type_ = val["type"]
#
# if key in self.params and not isinstance(self.params[key], type_):
# raise TypeError(f"'{key}' is not of type '{type_}'")
#
# if "default" in val and key not in self.params:
# self.params[key] = val["required"]
#
# else:
# if key not in self.params:
# self.params[key] = val
#
# def get_params(self):
# return self.params
#
# Path: util.py
# def get_version():
# confpath = Path(PATH) / "pyproject.toml"
#
# with open(confpath) as f:
# project = toml.load(f)
# version = project["tool"]["poetry"]["version"]
# return version
. Output only the next line. | def get(self, name): |
Predict the next line for this snippet: <|code_start|> if not isinstance(cmd.methods, tuple) and \
not isinstance(cmd.methods, list):
raise Exception("Methods need to be of type tuple or list")
if not cmdmethod:
raise TypeError(f"This command needs one of these methods: {cmd.methods}")
elif cmdmethod not in cmd.methods:
raise Exception("Invalid method for <%s>" % name)
response = cmd.run(params, cmdmethod)
else:
# Check if this command wants the 'params' array or not
spec = inspect.getargspec(cmd.run)
if len(spec.args) == 0:
logging.debug("Command has no arguments, not providing params")
response = cmd.run()
else:
response = cmd.run(params)
return response
def error(self, msg):
return { "error" : msg }
def run(self, cmdname, cmdmethod = None, params = False):
if cmdname not in self.commands:
return False, self.error("unknown command %s" % cmdname)
name = self.commands[cmdname]
<|code_end|>
with the help of current file imports:
import inspect
import json
import jsonpickle
import logging
import os
import toml
from argparser import ArgumentsParser
from config import PATH
from util import get_version
and context from other files:
# Path: argparser.py
# class ArgumentsParser:
# def __init__(self, params, arguments, method):
# if not isinstance(arguments, dict):
# raise Exception("Command arguments is not a dict")
#
# self.params = params
# self.arguments = arguments
# self.method = method
# self._parse()
#
# def _check_required(self, required, key):
# if required == False:
# return
#
# if required == True and key in self.params:
# return
#
# if required == True and key not in self.params:
# raise KeyError(f"{key} is required and was not given")
#
# def _parse(self):
# for key, val in self.arguments.items():
# if isinstance(val, dict):
# if "required" in val:
# required = val["required"]
#
# if isinstance(val["required"], list) and self.method in required:
# self._check_required(True, key)
# else:
# self._check_required(required, key)
#
# if "type" in val:
# type_ = val["type"]
#
# if key in self.params and not isinstance(self.params[key], type_):
# raise TypeError(f"'{key}' is not of type '{type_}'")
#
# if "default" in val and key not in self.params:
# self.params[key] = val["required"]
#
# else:
# if key not in self.params:
# self.params[key] = val
#
# def get_params(self):
# return self.params
#
# Path: util.py
# def get_version():
# confpath = Path(PATH) / "pyproject.toml"
#
# with open(confpath) as f:
# project = toml.load(f)
# version = project["tool"]["poetry"]["version"]
# return version
, which may contain function names, class names, or code. Output only the next line. | cmd = self.get(name) |
Predict the next line for this snippet: <|code_start|> "action" : "query",
"prop" : "linkshere",
"titles" : q,
"lhlimit" : 500
})
data = list(data["query"]["pages"].values())[0]
if "linkshere" in data:
data["total"] = len(data["linkshere"])
else:
data["total"] = 0
return data
def langlinks(q, lang):
data = request(lang, {
"action" : "query",
"prop" : "langlinks",
"titles" : q,
"lllimit" : 500
})
data = list(data["query"]["pages"].values())[0]
if "langlinks" in data:
data["total"] = len(data["langlinks"])
else:
data["total"] = 0
<|code_end|>
with the help of current file imports:
import requests, json, re, time
from pyquery import PyQuery as pq
from commands.wmcommons import wmcommons
from jq import jq
from dataknead import Knead
and context from other files:
# Path: commands/wmcommons/wmcommons.py
# COMMONS_ENDPOINT = "http://commons.wikimedia.org"
# PAGE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/File:%s"
# API_ENDPOINT = COMMONS_ENDPOINT + "/w/api.php";
# RESIZE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/Special:Redirect/file/%s"
# FILE_PREFIX = "File:"
# def parse_imageinfo(data):
# def request(params):
# def imagepage(filename):
# def imageresize(filename, width = None):
# def imageinfo(args):
, which may contain function names, class names, or code. Output only the next line. | return data |
Given snippet: <|code_start|>
[d.remove(selector) for selector in (
".beeldengeluid-infobox",
"#personen-foto",
"#personen-gegevens",
".mw-editsection"
)]
for a in d.find("a"):
pa = pq(a)
href = pa.attr("href")
href = _lookuphref(href)
text = pa.text()
if href:
pa.attr('href', href)
else:
pa.empty().prepend("<span>" + text + "</span>")
# Check if there is still some html left
if not d.html().strip():
return False
return d.html().strip()
def pagetext(q):
r = util.apirequest(WIKI_ENDPOINT, {
"format" : "json",
"action" : "query",
"prop" : "revisions",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import util, requests, xmltodict, urllib.request, urllib.parse, urllib.error
from pyquery import PyQuery as pq
from commands.gtaa import gtaa
and context:
# Path: commands/gtaa/gtaa.py
# API_ENDPOINT = "http://data.beeldengeluid.nl/api/"
# SCHEME_ENDPOINT = "http://data.beeldengeluid.nl/gtaa/%s"
# SCHEMES = (
# "GeografischeNamen",
# "Geografisch",
# "Namen",
# "Persoonsnamen",
# "OnderwerpenBenG",
# "Onderwerpen",
# "Maker",
# "Makers", # This is a hack, see the code below
# "Genre"
# )
# def _format_concept(concept):
# def _combined_iterator():
# def lookupcombined(q, qtype):
# def finditems(q, limit):
# def listcombined():
# def lookup(id_):
which might include code, classes, or functions. Output only the next line. | "titles" : q, |
Predict the next line for this snippet: <|code_start|> "response_time" : response_time
}
return response
@app.route('/')
def root():
return open(config.PATH + "/static/index.html").read()
@app.route('/_commands')
def list_commands():
logging.debug("Listing all commands")
return json_response(commands.listall())
@app.route('/<cmdname>/<cmdmethod>')
def command_with_method(cmdname, cmdmethod):
response = run_command(cmdname, cmdmethod)
return json_response(response)
@app.route('/<cmdname>')
def command(cmdname):
response = run_command(cmdname)
return json_response(response)
def get_cache():
if not config.CACHING.get("enabled", False):
return False
cachemodule = __import__(config.CACHING['type'])
<|code_end|>
with the help of current file imports:
import argparse, os, json, logging, config
from commandsmanager import CommandsManager
from flask import Flask, request, make_response
from urllib.parse import urlparse
from pprint import pprint
from time import time
from util import get_version
and context from other files:
# Path: commandsmanager.py
# class CommandsManager:
# def __init__(self):
# self.commands = self.parse()
#
# # This command is used to load the modules when needed
# def get(self, name):
# # For the reason why we need the fromlist argument see
# # < http://stackoverflow.com/questions/2724260 >
# return __import__("commands.%s.command" % name, fromlist="commands")
#
# # List all commands with arguments and methods
# def listall(self):
# commands = {}
# cmdnames = sorted(list(set(self.commands.values())))
#
# for cmdname in cmdnames:
# cmd = self.get(cmdname)
#
# if cmd.__doc__:
# description = cmd.__doc__.strip()
# else:
# description = None
#
# commands[cmdname] = {
# "aliases" : getattr(cmd, "aliases", None),
# "arguments" : getattr(cmd, "arguments", None),
# "cacheable" : getattr(cmd, "CACHEABLE", None),
# "description" : description,
# "methods" : getattr(cmd, "methods", None),
# "name" : cmdname
# }
#
# return json.loads(jsonpickle.encode(commands, unpicklable = False))
#
# def parse(self):
# commands = {}
#
# logging.info("Parsing commands")
#
# cmddirs = [c for c in os.listdir(COMMANDS_PATH) if c[0] != "_" and c[0] != "."]
#
# logging.info("Commands we're going to load %s" % cmddirs)
#
# for cmdname in cmddirs:
# logging.debug("Parsing <%s>" % cmdname)
#
# command = self.get(cmdname)
# commands[cmdname] = cmdname
#
# if hasattr(command, "aliases"):
# for alias in command.aliases:
# commands[alias] = cmdname
#
# logging.info("Okay, loaded <%s>" % cmdname)
#
# logging.debug("Done loading")
#
# return commands
#
# def execute(self, params, cmd, cmdmethod, name):
# logging.debug("Executing command %s/%s" % (name, cmdmethod))
# logging.debug("With params " + json.dumps(params, indent = 4))
#
# if not hasattr(cmd, "run"):
# raise TypeError("Chantek commands required a 'run' method")
#
# # If there is an 'arguments' dict, use that to fill in default
# # values for the params
# if hasattr(cmd, "arguments"):
# logging.debug(f"Parsing default arguments for <{name}>")
# parser = ArgumentsParser(params, cmd.arguments, cmdmethod)
# params = parser.get_params()
#
# if hasattr(cmd, "methods"):
# # Python casts tuples with one value to a string, so we
# # need to explicitely make it a tuple
# if isinstance(cmd.methods, str):
# cmd.methods = (cmd.methods, )
#
# # Check if methods is not something weird
# if not isinstance(cmd.methods, tuple) and \
# not isinstance(cmd.methods, list):
# raise Exception("Methods need to be of type tuple or list")
#
# if not cmdmethod:
# raise TypeError(f"This command needs one of these methods: {cmd.methods}")
# elif cmdmethod not in cmd.methods:
# raise Exception("Invalid method for <%s>" % name)
#
# response = cmd.run(params, cmdmethod)
# else:
# # Check if this command wants the 'params' array or not
# spec = inspect.getargspec(cmd.run)
#
# if len(spec.args) == 0:
# logging.debug("Command has no arguments, not providing params")
# response = cmd.run()
# else:
# response = cmd.run(params)
#
# return response
#
# def error(self, msg):
# return { "error" : msg }
#
# def run(self, cmdname, cmdmethod = None, params = False):
# if cmdname not in self.commands:
# return False, self.error("unknown command %s" % cmdname)
#
# name = self.commands[cmdname]
# cmd = self.get(name)
#
# if cmdmethod and not hasattr(cmd, 'methods'):
# return False, self.error("<%s> does not have any methods" % name)
#
# data_response = {
# "chantek" : VERSION,
# "command" : name,
# "params" : params,
# }
#
# try:
# response = self.execute(
# params = params,
# cmd = cmd,
# cmdmethod = cmdmethod,
# name = name
# )
# except Exception as e:
# data_response.update({
# "error" : {
# "message" : "<%s>: %s" % (name, e)
# },
# "response" : False
# })
#
# if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
# raise
# else:
# data_response.update({
# "error" : False,
# "response" : response
# })
#
# return cmd, data_response
#
# Path: util.py
# def get_version():
# confpath = Path(PATH) / "pyproject.toml"
#
# with open(confpath) as f:
# project = toml.load(f)
# version = project["tool"]["poetry"]["version"]
# return version
, which may contain function names, class names, or code. Output only the next line. | return cachemodule.Cache(expires = config.CACHING['expires']) |
Next line prediction: <|code_start|>
if snak["snaktype"] == "novalue":
return {
"datatype" : "novalue"
}
else:
value = snak["datavalue"]["value"]
if datatype == "wikibase-item":
qid = "Q" + str(value["numeric-id"])
val["value"] = qid
self.entitycache[qid] = False
elif datatype == "monolingualtext":
# Probably a bit hacky really
val["value"] = value["text"]
else:
val["value"] = value
return val
def get_claimvaluestring(self, val):
datatype = val.get("datatype", None)
value = val.get("value", False)
if not value or not datatype:
return ""
if datatype == "wikibase-item":
return val.get("value_labels", "")
<|code_end|>
. Use current file imports:
(import util, json, time, math, requests
from commands.wmcommons import wmcommons
from .entity_ld import WikidataEntityLD)
and context including class names, function names, or small code snippets from other files:
# Path: commands/wmcommons/wmcommons.py
# COMMONS_ENDPOINT = "http://commons.wikimedia.org"
# PAGE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/File:%s"
# API_ENDPOINT = COMMONS_ENDPOINT + "/w/api.php";
# RESIZE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/Special:Redirect/file/%s"
# FILE_PREFIX = "File:"
# def parse_imageinfo(data):
# def request(params):
# def imagepage(filename):
# def imageresize(filename, width = None):
# def imageinfo(args):
#
# Path: commands/wikidata/entity_ld.py
# class WikidataEntityLD:
# def __init__(self, qid, languages = ""):
# self.qid = qid
# self.languages = languages.split(",")
# self.rdf = self.get_rdf()
#
# def _entityvalues(self, item, idns):
# tree = {
# "uri" : item["@id"]
# }
#
# for ns in (NS_NAME, NS_DESCRIPTION):
# if ns.uri in item:
# tree[ns.name] = { i["@language"]:i["@value"] for i in item[ns.uri] }
#
# # Do we only want a selection of languages?
# if self.languages:
# tree[ns.name] = { k:v for k,v in tree[ns.name].items() if k in self.languages}
#
# return tree
#
# def _get_by_namespace(self, tree, namespace):
# items = Knead(tree).filter(lambda i:i["@id"].startswith(namespace.uri))
# return items.data()
#
# def _statementvalues(self, statement, uri):
# prop = [
# { "property_uri": key, "values" : val }
# for key, val in statement.items() if key.startswith(uri)
# ]
#
# if len(prop) == 1:
# return prop[0]
# else:
# return None
#
# def get_rdf(self):
# r = requests.get(RDF_ENDPOINT % self.qid)
# return r.text
#
# def as_json_ld(self):
# graph = Graph().parse(data=self.rdf, format='xml')
# jsonld = graph.serialize(format='json-ld', indent=4)
# return json.loads(jsonld)
#
# def as_json_ld_simplified(self):
# tree = self.as_json_ld()
#
# entities = self._get_by_namespace(tree, NS_ENTITY)
# entities = { i["@id"]:self._entityvalues(i, NS_ENTITY.uri) for i in entities }
#
# statements = self._get_by_namespace(tree, NS_ENTITY_STATEMENT)
# statements = [self._statementvalues(s, NS_PROP_STATEMENT.uri) for s in statements]
#
# for statement in statements:
# if statement:
# uri = statement["property_uri"].replace("prop/statement", "entity")
# statement["property"] = entities.get(uri, None)
#
# for value in statement["values"]:
# if "@id" in value:
# value["entity"] = entities.get(value["@id"], None)
#
# if "@value" in value:
# value["value"] = value["@value"]
#
#
# return {
# "entities" : entities,
# "statements" : statements
# }
. Output only the next line. | if datatype in ["string", "monolingualtext", "url"]: |
Given snippet: <|code_start|> def __init__(self):
self.entitycache = {}
# If set to 'True' and only one language is given, the value
# is directly given as value for a key instead of an object
#
# e.g.
# {
# "propery_labels" : "Birth name"
# }
#
# vs
# {
# "property_labels" : {
# "en" : "Birth name"
# }
# }
#
self.flattenlanguages = True
def get_claim_values(self, claim):
snak = claim["mainsnak"]
if "datatype" not in snak:
return claim
datatype = snak["datatype"]
val = { "datatype" : datatype }
if snak["snaktype"] == "novalue":
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import util, json, time, math, requests
from commands.wmcommons import wmcommons
from .entity_ld import WikidataEntityLD
and context:
# Path: commands/wmcommons/wmcommons.py
# COMMONS_ENDPOINT = "http://commons.wikimedia.org"
# PAGE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/File:%s"
# API_ENDPOINT = COMMONS_ENDPOINT + "/w/api.php";
# RESIZE_ENDPOINT = COMMONS_ENDPOINT + "/wiki/Special:Redirect/file/%s"
# FILE_PREFIX = "File:"
# def parse_imageinfo(data):
# def request(params):
# def imagepage(filename):
# def imageresize(filename, width = None):
# def imageinfo(args):
#
# Path: commands/wikidata/entity_ld.py
# class WikidataEntityLD:
# def __init__(self, qid, languages = ""):
# self.qid = qid
# self.languages = languages.split(",")
# self.rdf = self.get_rdf()
#
# def _entityvalues(self, item, idns):
# tree = {
# "uri" : item["@id"]
# }
#
# for ns in (NS_NAME, NS_DESCRIPTION):
# if ns.uri in item:
# tree[ns.name] = { i["@language"]:i["@value"] for i in item[ns.uri] }
#
# # Do we only want a selection of languages?
# if self.languages:
# tree[ns.name] = { k:v for k,v in tree[ns.name].items() if k in self.languages}
#
# return tree
#
# def _get_by_namespace(self, tree, namespace):
# items = Knead(tree).filter(lambda i:i["@id"].startswith(namespace.uri))
# return items.data()
#
# def _statementvalues(self, statement, uri):
# prop = [
# { "property_uri": key, "values" : val }
# for key, val in statement.items() if key.startswith(uri)
# ]
#
# if len(prop) == 1:
# return prop[0]
# else:
# return None
#
# def get_rdf(self):
# r = requests.get(RDF_ENDPOINT % self.qid)
# return r.text
#
# def as_json_ld(self):
# graph = Graph().parse(data=self.rdf, format='xml')
# jsonld = graph.serialize(format='json-ld', indent=4)
# return json.loads(jsonld)
#
# def as_json_ld_simplified(self):
# tree = self.as_json_ld()
#
# entities = self._get_by_namespace(tree, NS_ENTITY)
# entities = { i["@id"]:self._entityvalues(i, NS_ENTITY.uri) for i in entities }
#
# statements = self._get_by_namespace(tree, NS_ENTITY_STATEMENT)
# statements = [self._statementvalues(s, NS_PROP_STATEMENT.uri) for s in statements]
#
# for statement in statements:
# if statement:
# uri = statement["property_uri"].replace("prop/statement", "entity")
# statement["property"] = entities.get(uri, None)
#
# for value in statement["values"]:
# if "@id" in value:
# value["entity"] = entities.get(value["@id"], None)
#
# if "@value" in value:
# value["value"] = value["@value"]
#
#
# return {
# "entities" : entities,
# "statements" : statements
# }
which might include code, classes, or functions. Output only the next line. | return { |
Next line prediction: <|code_start|>
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'Market-1501-v15.09.15.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
raise RuntimeError("Please download the dataset manually from {} "
"to {}".format(self.url, fpath))
# Extract the file
exdir = osp.join(raw_dir, 'Market-1501-v15.09.15')
<|code_end|>
. Use current file imports:
(import os.path as osp
import re
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile)
and context including class names, function names, or small code snippets from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | if not osp.isdir(exdir): |
Continue the code snippet: <|code_start|>from __future__ import print_function, absolute_import
class Market1501(Dataset):
url = 'https://drive.google.com/file/d/0B8-rUzbwVRk0c054eEozWG9COHM/view'
md5 = '65005ab7d12ec1c44de4eeafe813e68a'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(Market1501, self).__init__(root, split_id=split_id)
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
<|code_end|>
. Use current file imports:
import os.path as osp
import re
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile
and context (classes, functions, or code) from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | print("Files already downloaded and verified") |
Continue the code snippet: <|code_start|> return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'DukeMTMC-reID.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
raise RuntimeError("Please download the dataset manually from {} "
"to {}".format(self.url, fpath))
# Extract the file
exdir = osp.join(raw_dir, 'DukeMTMC-reID')
if not osp.isdir(exdir):
print("Extracting zip file")
with ZipFile(fpath) as z:
z.extractall(path=raw_dir)
# Format
images_dir = osp.join(self.root, 'images')
mkdir_if_missing(images_dir)
identities = []
all_pids = {}
def register(subdir, pattern=re.compile(r'([-\d]+)_c(\d)')):
<|code_end|>
. Use current file imports:
import os.path as osp
import re
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile
and context (classes, functions, or code) from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | fpaths = sorted(glob(osp.join(exdir, subdir, '*.jpg'))) |
Given the following code snippet before the placeholder: <|code_start|> md5 = '2f93496f9b516d1ee5ef51c1d5e7d601'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(DukeMTMC, self).__init__(root, split_id=split_id)
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. " +
"You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'DukeMTMC-reID.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
raise RuntimeError("Please download the dataset manually from {} "
<|code_end|>
, predict the next line using imports from the current file:
import os.path as osp
import re
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile
and context including class names, function names, and sometimes code from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | "to {}".format(self.url, fpath)) |
Continue the code snippet: <|code_start|>from __future__ import print_function, absolute_import
class CUHK01(Dataset):
url = 'https://docs.google.com/spreadsheet/viewform?formkey=dF9pZ1BFZkNiMG1oZUdtTjZPalR0MGc6MA'
md5 = 'e6d55c0da26d80cda210a2edeb448e98'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(CUHK01, self).__init__(root, split_id=split_id)
if download:
self.download()
<|code_end|>
. Use current file imports:
import os.path as osp
import numpy as np
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile
and context (classes, functions, or code) from other files:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | if not self._check_integrity(): |
Using the snippet: <|code_start|> "You can use download=True to download it.")
self.load(num_val)
def download(self):
if self._check_integrity():
print("Files already downloaded and verified")
return
raw_dir = osp.join(self.root, 'raw')
mkdir_if_missing(raw_dir)
# Download the raw zip file
fpath = osp.join(raw_dir, 'CUHK01.zip')
if osp.isfile(fpath) and \
hashlib.md5(open(fpath, 'rb').read()).hexdigest() == self.md5:
print("Using downloaded file: " + fpath)
else:
raise RuntimeError("Please download the dataset manually from {} "
"to {}".format(self.url, fpath))
# Extract the file
exdir = osp.join(raw_dir, 'campus')
if not osp.isdir(exdir):
print("Extracting zip file")
with ZipFile(fpath) as z:
z.extractall(path=raw_dir)
# Format
<|code_end|>
, determine the next line of code. You have imports:
import os.path as osp
import numpy as np
import hashlib
import shutil
from ..utils.data import Dataset
from ..utils.osutils import mkdir_if_missing
from ..utils.serialization import write_json
from glob import glob
from zipfile import ZipFile
and context (class names, function names, or code) available:
# Path: reid/utils/data/dataset.py
# class Dataset(object):
# def __init__(self, root, split_id=0):
# self.root = root
# self.split_id = split_id
# self.meta = None
# self.split = None
# self.train, self.val, self.trainval = [], [], []
# self.query, self.gallery = [], []
# self.num_train_ids, self.num_val_ids, self.num_trainval_ids = 0, 0, 0
#
# @property
# def images_dir(self):
# return osp.join(self.root, 'images')
#
# def load(self, num_val=0.3, verbose=True):
# splits = read_json(osp.join(self.root, 'splits.json'))
# if self.split_id >= len(splits):
# raise ValueError("split_id exceeds total splits {}"
# .format(len(splits)))
# self.split = splits[self.split_id]
#
# # Randomly split train / val
# trainval_pids = np.asarray(self.split['trainval'])
# np.random.shuffle(trainval_pids)
# num = len(trainval_pids)
# if isinstance(num_val, float):
# num_val = int(round(num * num_val))
# if num_val >= num or num_val < 0:
# raise ValueError("num_val exceeds total identities {}"
# .format(num))
# train_pids = sorted(trainval_pids[:-num_val])
# val_pids = sorted(trainval_pids[-num_val:])
#
# self.meta = read_json(osp.join(self.root, 'meta.json'))
# identities = self.meta['identities']
# self.train = _pluck(identities, train_pids, relabel=True)
# self.val = _pluck(identities, val_pids, relabel=True)
# self.trainval = _pluck(identities, trainval_pids, relabel=True)
# self.query = _pluck(identities, self.split['query'])
# self.gallery = _pluck(identities, self.split['gallery'])
# self.num_train_ids = len(train_pids)
# self.num_val_ids = len(val_pids)
# self.num_trainval_ids = len(trainval_pids)
#
# if verbose:
# print(self.__class__.__name__, "dataset loaded")
# print(" subset | # ids | # images")
# print(" ---------------------------")
# print(" train | {:5d} | {:8d}"
# .format(self.num_train_ids, len(self.train)))
# print(" val | {:5d} | {:8d}"
# .format(self.num_val_ids, len(self.val)))
# print(" trainval | {:5d} | {:8d}"
# .format(self.num_trainval_ids, len(self.trainval)))
# print(" query | {:5d} | {:8d}"
# .format(len(self.split['query']), len(self.query)))
# print(" gallery | {:5d} | {:8d}"
# .format(len(self.split['gallery']), len(self.gallery)))
#
# def _check_integrity(self):
# return osp.isdir(osp.join(self.root, 'images')) and \
# osp.isfile(osp.join(self.root, 'meta.json')) and \
# osp.isfile(osp.join(self.root, 'splits.json'))
#
# Path: reid/utils/osutils.py
# def mkdir_if_missing(dir_path):
# try:
# os.makedirs(dir_path)
# except OSError as e:
# if e.errno != errno.EEXIST:
# raise
. Output only the next line. | images_dir = osp.join(self.root, 'images') |
Using the snippet: <|code_start|>
class TestCMC(TestCase):
def test_only_distmat(self):
distmat = np.array([[0, 1, 2, 3, 4],
[1, 0, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[1, 2, 3, 4, 0]])
ret = cmc(distmat)
self.assertTrue(np.all(ret[:5] == [0.6, 0.6, 0.8, 1.0, 1.0]))
def test_duplicate_ids(self):
distmat = np.tile(np.arange(4), (4, 1))
query_ids = [0, 0, 1, 1]
gallery_ids = [0, 0, 1, 1]
ret = cmc(distmat, query_ids=query_ids, gallery_ids=gallery_ids, topk=4,
separate_camera_set=False, single_gallery_shot=False)
self.assertTrue(np.all(ret == [0.5, 0.5, 1, 1]))
<|code_end|>
, determine the next line of code. You have imports:
from unittest import TestCase
from reid.evaluation_metrics import cmc
import numpy as np
and context (class names, function names, or code) available:
# Path: reid/evaluation_metrics/ranking.py
# def cmc(distmat, query_ids=None, gallery_ids=None,
# query_cams=None, gallery_cams=None, topk=100,
# separate_camera_set=False,
# single_gallery_shot=False,
# first_match_break=False):
# distmat = to_numpy(distmat)
# m, n = distmat.shape
# # Fill up default values
# if query_ids is None:
# query_ids = np.arange(m)
# if gallery_ids is None:
# gallery_ids = np.arange(n)
# if query_cams is None:
# query_cams = np.zeros(m).astype(np.int32)
# if gallery_cams is None:
# gallery_cams = np.ones(n).astype(np.int32)
# # Ensure numpy array
# query_ids = np.asarray(query_ids)
# gallery_ids = np.asarray(gallery_ids)
# query_cams = np.asarray(query_cams)
# gallery_cams = np.asarray(gallery_cams)
# # Sort and find correct matches
# indices = np.argsort(distmat, axis=1)
# matches = (gallery_ids[indices] == query_ids[:, np.newaxis])
# # Compute CMC for each query
# ret = np.zeros(topk)
# num_valid_queries = 0
# for i in range(m):
# # Filter out the same id and same camera
# valid = ((gallery_ids[indices[i]] != query_ids[i]) |
# (gallery_cams[indices[i]] != query_cams[i]))
# if separate_camera_set:
# # Filter out samples from same camera
# valid &= (gallery_cams[indices[i]] != query_cams[i])
# if not np.any(matches[i, valid]): continue
# if single_gallery_shot:
# repeat = 10
# gids = gallery_ids[indices[i][valid]]
# inds = np.where(valid)[0]
# ids_dict = defaultdict(list)
# for j, x in zip(inds, gids):
# ids_dict[x].append(j)
# else:
# repeat = 1
# for _ in range(repeat):
# if single_gallery_shot:
# # Randomly choose one instance for each id
# sampled = (valid & _unique_sample(ids_dict, len(valid)))
# index = np.nonzero(matches[i, sampled])[0]
# else:
# index = np.nonzero(matches[i, valid])[0]
# delta = 1. / (len(index) * repeat)
# for j, k in enumerate(index):
# if k - j >= topk: break
# if first_match_break:
# ret[k - j] += 1
# break
# ret[k - j] += delta
# num_valid_queries += 1
# if num_valid_queries == 0:
# raise RuntimeError("No valid query")
# return ret.cumsum() / num_valid_queries
. Output only the next line. | def test_duplicate_cams(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.