Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> self.tool_name = "Unknown tool"
else:
self.tool_name = tool_name
if fqdn == "":
self.fqdn = get_fqdn()
else:
self.fqdn = fqdn
if user_name == "":
self.user_name = get_name()
else:
self.user_name = user_name
self.cookie = None
#checkpoint received
#A dict of that link with member table
self.checkpoint = 0
#checkpoint sent
self.last_checkpoint = 0
self.seq = 0
#stat
self.last_send = 0
def start(self):
"""If override by daughters must call:
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import subprocess
from rtpmidi.protocols.rtp.rtp_control import RTPControl
and context:
# Path: rtpmidi/protocols/rtp/rtp_control.py
# class RTPControl(Singleton):
# """Control rtp for a payload to implement
# """
# currentRecordings = {}
# cookies = 0
#
# def add_session(self, session):
# #Test type
# if (not(hasattr(session, "incoming_rtp")
# and hasattr(session, "payload")
# and hasattr(session, "host")
# and hasattr(session, "rport")
# and hasattr(session, "drop_call")
# and hasattr(session, "start")
# and hasattr(session, "stop"))):
# raise Exception, "This session type is not supported"
# return
#
# #Cookie related to the rtp session
# cookie = self.make_cookie()
# session.cookie = cookie
#
# #Creating RTP
# self._create_rtp_socket(cookie, session)
# return cookie
#
# def del_session(self, cookie):
# rtp, o = self.currentRecordings[cookie]
# rtp.stopSendingAndReceiving()
# del self.currentRecordings[cookie]
#
# def start_session(self, cookie):
# rtp, session = self.currentRecordings[cookie]
# rtp.start(session.host)
# session.start()
#
# def start(self):
# for cookie in self.currentRecordings:
# self.start_session(cookie)
#
# def _create_rtp_socket(self, cookie, session):
#
# #Init RTPProtocol
# rtp = RTPProtocol(self, cookie, session.payload,
# session.jitter_buffer_size, verbose=session.verbose)
#
# #Creating socket
# rtp.createRTPSocket(session.host, session.rport, session.sport, False)
#
# #Register the session
# self.currentRecordings[cookie] = (rtp, session)
#
# #Registering host and port in used(if default port is in used by another
# #application it will choose another
# if rtp.rport > 0:
# session.host = (session.host, rtp.rport)
#
# else:
# session.host = (session.host, rtp.sport)
#
# def incoming_rtp(self, cookie, timestamp, packet,
# read_recovery_journal = 0):
# """Function called by RTPProtocol when incoming
# data coming out from jitter buffer
# """
# rtp, session = self.currentRecordings[cookie]
# session.incoming_rtp(cookie, timestamp, packet,
# read_recovery_journal)
#
#
# def send_empty_packet(self, cookie, chunk):
# #Selecting RTP session
# rtp, session = self.currentRecordings[cookie]
#
# #sending silent packet with recovery journal
# rtp.handle_data(session.payload, 0 , chunk, 1)
# self.last_send = time.time()
#
#
# def send_data_packet(self, cookie, data, ts):
# #Selecting RTP session
# rtp, session = self.currentRecordings[cookie]
# rtp.handle_data(session.payload, ts , data, 0)
# self.last_send = time.time()
#
#
# def stop_session(self, cookie):
# #Selecting RTP
# rtp, session = self.currentRecordings[cookie]
# rtp.stopSendingAndReceiving()
# session.stop()
#
# def stop(self):
# #Selecting RTP
# for cookie in self.currentRecordings:
# self.stop_session(cookie)
#
# def selectDefaultFormat(self, what):
# """link to sdp??"""
# #TODO pass SDP parameter for the session here ????
# pass
#
# def drop_connection(self, cookie):
# #Selecting RTP session
# rtp, session = self.currentRecordings[cookie]
# session.drop_connection()
#
#
# def get_session(self, cookie):
# rtp, session = self.currentRecordings[cookie]
# return session
#
# def make_cookie(self):
# self.cookies += 1
# return "cookie%s" % (self.cookies,)
which might include code, classes, or functions. Output only the next line. | RTPControl().start_session(self.cookie) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# Copyright (C) 2013 Stéphane Caron <caron@ynl.t.u-tokyo.ac.jp>
#
# This file is part of the Time-Optimal Path Parameterization (TOPP) library.
# TOPP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# at your option, any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class TorqueLimits(RAVEBindings):
"""Bindings for the 'TorqueLimitsRave' problem."""
def __init__(self, robot, traj, taumin, taumax, vmax, discrtimestep=None,
integrationtimestep=None):
constring = str(discrtimestep) + "\n"
<|code_end|>
. Write the next line using the current file imports:
from .TOPPopenravepy import RAVEBindings
from .Utilities import vect2str
and context from other files:
# Path: src/python/TOPPopenravepy.py
# class RAVEBindings(QuadraticConstraints):
# """Wrapper around TOPPbindings for OpenRAVE robot models.
#
# robot -- OpenRAVE robot object
# pbname -- string identifier of the underlying TOPPbindings problem
# constring -- constraints string (problem - dependant)
# trajstring -- trajectory string
#
# """
#
# def __init__(self, robot, pbname, constring, trajstring,
# discrtimestep=None, integrationtimestep=None):
# if discrtimestep is None:
# discrtimestep = 1e-2
# if integrationtimestep is None:
# integrationtimestep = 1e-3
# self.discrtimestep = discrtimestep
# self.integrationtimestep = integrationtimestep
# self.solver = TOPPbindings.TOPPInstance(robot, pbname, constring,
# trajstring)
#
# Path: src/python/Utilities.py
# def vect2str(v):
# return " ".join(map(str, v))
, which may include functions, classes, or code. Output only the next line. | constring += vect2str(taumin) + "\n" |
Given snippet: <|code_start|>
p0a = vector2string(random(ndof) * 2 * bound - bound)
p0b = vector2string(random(ndof) * 2 * bound - bound)
p1a = vector2string(random(ndof) * 2 * bound - bound)
p1b = vector2string(random(ndof) * 2 * bound - bound)
s = '%d' % ncurve
s += '\n1.0 ' + p0a + ' ' + p0b
for k in range(ncurve - 1):
a = random(ndof) * 2 * bound - bound
b = random(ndof) * 2 * bound - bound
c = 2 * b - a
pa = vector2string(a)
pb = vector2string(b)
pc = vector2string(c)
s += ' ' + pa + ' ' + pb + '\n1.0 ' + pb + ' ' + pc
s += ' ' + p1a + ' ' + p1b
Tv, p0v, p1v, p2v, p3v = string2p(s)
return BezierToTrajectoryString(Tv, p0v, p1v, p2v, p3v)
################# Compute Kinematic Constraints #####################
def ComputeKinematicConstraints(traj, amax, discrtimestep):
# Sample the dynamics constraints
ndiscrsteps = int((traj.duration + 1e-10) / discrtimestep) + 1
constraintstring = ""
for i in range(ndiscrsteps):
t = i * discrtimestep
qd = traj.Evald(t)
qdd = traj.Evaldd(t)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .Utilities import vect2str, BezierToTrajectoryString
from pylab import double, array, random
from .TOPPbindings import TOPPInstance
from pylab import figure, clf, hold, plot, gca, axis, title, xlabel, ylabel, cycler
from pylab import axis, linspace, sqrt, plot
from pylab import figure, clf, hold, gca, title, xlabel, ylabel, plot, axis, cycler
and context:
# Path: src/python/Utilities.py
# def vect2str(v):
# return " ".join(map(str, v))
#
# def BezierToTrajectoryString(Tv, p0v, p1v, p2v, p3v):
# nchunks = len(Tv)
# dimension = len(p0v[0])
# trajectorystring = ""
# for i in range(nchunks):
# if i > 0:
# trajectorystring += "\n"
# trajectorystring += str(Tv[i]) + "\n" + str(dimension)
# for j in range(dimension):
# a, b, c, d = BezierToPolynomial(Tv[i], p0v[i][j], p1v[i][j],
# p2v[i][j], p3v[i][j])
# trajectorystring += "\n%f %f %f %f" % (d, c, b, a)
# return trajectorystring
which might include code, classes, or functions. Output only the next line. | constraintstring += "\n" + vect2str(+qd) + " " + vect2str(-qd) |
Predict the next line for this snippet: <|code_start|>def VectorFromString(s):
# left for compatibility TODO: remove?
s = s.strip(" \n")
return array([double(x) for x in s.split(' ')])
def GenerateRandomTrajectory(ncurve, ndof, bound):
def vector2string(v):
ndof = len(v)
s = str(ndof)
for a in v:
s += ' %f' % a
return s
p0a = vector2string(random(ndof) * 2 * bound - bound)
p0b = vector2string(random(ndof) * 2 * bound - bound)
p1a = vector2string(random(ndof) * 2 * bound - bound)
p1b = vector2string(random(ndof) * 2 * bound - bound)
s = '%d' % ncurve
s += '\n1.0 ' + p0a + ' ' + p0b
for k in range(ncurve - 1):
a = random(ndof) * 2 * bound - bound
b = random(ndof) * 2 * bound - bound
c = 2 * b - a
pa = vector2string(a)
pb = vector2string(b)
pc = vector2string(c)
s += ' ' + pa + ' ' + pb + '\n1.0 ' + pb + ' ' + pc
s += ' ' + p1a + ' ' + p1b
Tv, p0v, p1v, p2v, p3v = string2p(s)
<|code_end|>
with the help of current file imports:
from .Utilities import vect2str, BezierToTrajectoryString
from pylab import double, array, random
from .TOPPbindings import TOPPInstance
from pylab import figure, clf, hold, plot, gca, axis, title, xlabel, ylabel, cycler
from pylab import axis, linspace, sqrt, plot
from pylab import figure, clf, hold, gca, title, xlabel, ylabel, plot, axis, cycler
and context from other files:
# Path: src/python/Utilities.py
# def vect2str(v):
# return " ".join(map(str, v))
#
# def BezierToTrajectoryString(Tv, p0v, p1v, p2v, p3v):
# nchunks = len(Tv)
# dimension = len(p0v[0])
# trajectorystring = ""
# for i in range(nchunks):
# if i > 0:
# trajectorystring += "\n"
# trajectorystring += str(Tv[i]) + "\n" + str(dimension)
# for j in range(dimension):
# a, b, c, d = BezierToPolynomial(Tv[i], p0v[i][j], p1v[i][j],
# p2v[i][j], p3v[i][j])
# trajectorystring += "\n%f %f %f %f" % (d, c, b, a)
# return trajectorystring
, which may contain function names, class names, or code. Output only the next line. | return BezierToTrajectoryString(Tv, p0v, p1v, p2v, p3v) |
Here is a snippet: <|code_start|> Complex visibility data as a function of time, frequency and baseline
flags : :class:`dask.array.Array` of uint8, shape (*T*, *F*, *B*)
Flags as a function of time, frequency and baseline
weights : :class:`dask.array.Array` of float32, shape (*T*, *F*, *B*)
Visibility weights as a function of time, frequency and baseline
unscaled_weights : :class:`dask.array.Array` of float32, shape (*T*, *F*, *B*)
Weights that are not scaled by autocorrelations, thereby representing
the number of voltage samples that constitutes each visibility (optional)
name : string, optional
Identifier that describes the origin of the data (backend-specific)
"""
def __init__(self, vis, flags, weights, unscaled_weights=None):
if not (vis.shape == flags.shape == weights.shape):
raise ValueError(f'Shapes of vis {vis.shape}, flags {flags.shape} '
f'and weights {weights.shape} differ')
if unscaled_weights is not None and (unscaled_weights.shape != vis.shape):
raise ValueError(f'Shapes of unscaled weights {unscaled_weights.shape} '
f'and vis {vis.shape} differ')
self.vis = vis
self.flags = flags
self.weights = weights
self.unscaled_weights = unscaled_weights
@property
def shape(self):
return self.vis.shape
def _default_zero(array):
<|code_end|>
. Write the next line using the current file imports:
import itertools
import logging
import dask.array as da
import numba
import numpy as np
import toolz
from dask.array.rechunk import intersect_chunks
from dask.highlevelgraph import HighLevelGraph
from .chunkstore import PlaceholderChunk
from .flags import DATA_LOST
from .van_vleck import autocorr_lookup_table
and context from other files:
# Path: katdal/chunkstore.py
# class PlaceholderChunk:
# """Chunk returned to indicate missing data."""
#
# def __init__(self, shape, dtype):
# self.shape = shape
# self.dtype = np.dtype(dtype)
#
# def __getitem__(self, index):
# # Create an array with a zero-sized dtype, so that it takes no memory
# dummy = np.empty(self.shape, dtype=[])
# new_shape = dummy[index].shape
# return PlaceholderChunk(new_shape, self.dtype)
#
# Path: katdal/flags.py
# DATA_LOST = 1 << DATA_LOST_BIT
#
# Path: katdal/van_vleck.py
# def autocorr_lookup_table(levels, size=4000):
# """Lookup table that corrects complex autocorrelation quantisation effects.
#
# This maps the variance of a quantised complex voltage signal to the variance
# of the unquantised signal under the assumption that the signal is proper
# (circularly-symmetric) complex normally distributed.
#
# Parameters
# ----------
# levels : sequence of float
# Quantisation levels for real and imaginary components of voltage signal
# size : int, optional
# Size of lookup table
#
# Returns
# -------
# quantised_autocorr_table, true_autocorr_table : array of float, shape (`size`,)
# Lookup table associating quantised autocorrelations and unquantised
# autocorrelations (i.e. power/variance of complex signals)
# """
# # Terminology:
# # x = Proper complex normal voltage signal (zero-mean)
# # rxx = Power (variance) *per* real/imag component of unquantised / true x
# # sxx = Power (variance) *per* real/imag component of quantised x
# abs_levels = np.abs(levels)
# sxx_min_nonzero = abs_levels[abs_levels > 0].min() ** 2
# sxx_max = abs_levels.max() ** 2
# # Sweep across range of true power values, placing more table entries at tricky lower end
# rxx_grid = np.r_[np.logspace(-2.4, 0, size // 2, endpoint=False),
# np.logspace(0, np.log10(sxx_max / sxx_min_nonzero) + 8, size - 2 - size // 2)]
# # Shift the table to place inflection point at minimum non-zero sxx
# rxx_grid *= sxx_min_nonzero
# # Map true power to expected quantised power
# sxx_mean = _squared_quant_norm0_mean(levels, rxx_grid)
# # Extend quantised power values to its maximum range
# sxx_table = np.r_[0., sxx_mean, sxx_max]
# # Replace asymptotic with linear decay at bottom end, and clip unbounded growth at top end
# rxx_table = np.r_[0., rxx_grid, rxx_grid[-1]]
# # The factor 2 converts power per real/imag component to power/variance of complex signal
# return 2. * sxx_table, 2. * rxx_table
, which may include functions, classes, or code. Output only the next line. | if isinstance(array, PlaceholderChunk): |
Next line prediction: <|code_start|> raise ValueError(f'Shapes of vis {vis.shape}, flags {flags.shape} '
f'and weights {weights.shape} differ')
if unscaled_weights is not None and (unscaled_weights.shape != vis.shape):
raise ValueError(f'Shapes of unscaled weights {unscaled_weights.shape} '
f'and vis {vis.shape} differ')
self.vis = vis
self.flags = flags
self.weights = weights
self.unscaled_weights = unscaled_weights
@property
def shape(self):
return self.vis.shape
def _default_zero(array):
if isinstance(array, PlaceholderChunk):
return np.zeros(array.shape, array.dtype)
else:
return array
def _apply_data_lost(orig_flags, lost):
if not lost:
return orig_flags
flags = orig_flags
for chunk, slices in toolz.partition(2, lost):
if isinstance(chunk, PlaceholderChunk):
if flags is orig_flags:
flags = orig_flags.copy()
<|code_end|>
. Use current file imports:
(import itertools
import logging
import dask.array as da
import numba
import numpy as np
import toolz
from dask.array.rechunk import intersect_chunks
from dask.highlevelgraph import HighLevelGraph
from .chunkstore import PlaceholderChunk
from .flags import DATA_LOST
from .van_vleck import autocorr_lookup_table)
and context including class names, function names, or small code snippets from other files:
# Path: katdal/chunkstore.py
# class PlaceholderChunk:
# """Chunk returned to indicate missing data."""
#
# def __init__(self, shape, dtype):
# self.shape = shape
# self.dtype = np.dtype(dtype)
#
# def __getitem__(self, index):
# # Create an array with a zero-sized dtype, so that it takes no memory
# dummy = np.empty(self.shape, dtype=[])
# new_shape = dummy[index].shape
# return PlaceholderChunk(new_shape, self.dtype)
#
# Path: katdal/flags.py
# DATA_LOST = 1 << DATA_LOST_BIT
#
# Path: katdal/van_vleck.py
# def autocorr_lookup_table(levels, size=4000):
# """Lookup table that corrects complex autocorrelation quantisation effects.
#
# This maps the variance of a quantised complex voltage signal to the variance
# of the unquantised signal under the assumption that the signal is proper
# (circularly-symmetric) complex normally distributed.
#
# Parameters
# ----------
# levels : sequence of float
# Quantisation levels for real and imaginary components of voltage signal
# size : int, optional
# Size of lookup table
#
# Returns
# -------
# quantised_autocorr_table, true_autocorr_table : array of float, shape (`size`,)
# Lookup table associating quantised autocorrelations and unquantised
# autocorrelations (i.e. power/variance of complex signals)
# """
# # Terminology:
# # x = Proper complex normal voltage signal (zero-mean)
# # rxx = Power (variance) *per* real/imag component of unquantised / true x
# # sxx = Power (variance) *per* real/imag component of quantised x
# abs_levels = np.abs(levels)
# sxx_min_nonzero = abs_levels[abs_levels > 0].min() ** 2
# sxx_max = abs_levels.max() ** 2
# # Sweep across range of true power values, placing more table entries at tricky lower end
# rxx_grid = np.r_[np.logspace(-2.4, 0, size // 2, endpoint=False),
# np.logspace(0, np.log10(sxx_max / sxx_min_nonzero) + 8, size - 2 - size // 2)]
# # Shift the table to place inflection point at minimum non-zero sxx
# rxx_grid *= sxx_min_nonzero
# # Map true power to expected quantised power
# sxx_mean = _squared_quant_norm0_mean(levels, rxx_grid)
# # Extend quantised power values to its maximum range
# sxx_table = np.r_[0., sxx_mean, sxx_max]
# # Replace asymptotic with linear decay at bottom end, and clip unbounded growth at top end
# rxx_table = np.r_[0., rxx_grid, rxx_grid[-1]]
# # The factor 2 converts power per real/imag component to power/variance of complex signal
# return 2. * sxx_table, 2. * rxx_table
. Output only the next line. | flags[slices] |= DATA_LOST |
Predict the next line for this snippet: <|code_start|> """Correct autocorrelations for quantisation effects (Van Vleck correction).
This is a first-order correction that only adjusts the mean autocorrelations,
which in turn affects the autocorrelation and crosscorrelation weights.
A complete correction would also adjust the mean crosscorrelations, and
further improve the weight estimates based on Bayesian statistics.
Parameters
----------
vis : :class:`dask.array.Array` of complex64, shape (*T*, *F*, *B*)
Complex visibility data as function of time, frequency, correlation product
corrprods : sequence of 2-tuples or ndarray, containing str
Input labels of the correlation products, used to find autocorrelations
levels : sequence of float, optional
Quantisation levels of real/imag components of complex digital signal
entering correlator (defaults to MeerKAT F-engine output levels)
Returns
-------
corrected_vis : :class:`dask.array.Array` of complex64, shape (*T*, *F*, *B*)
Complex visibility data with autocorrelations corrected for quantisation
"""
assert len(corrprods) == vis.shape[2]
# Ensure that we have only a single chunk on the baseline axis.
if len(vis.chunks[2]) > 1:
vis = vis.rechunk({2: vis.shape[2]})
auto_indices, _, _ = corrprod_to_autocorr(corrprods)
if levels is None:
# 255-level "8-bit" output of MeerKAT F-engine requantiser
levels = np.arange(-127., 128.)
<|code_end|>
with the help of current file imports:
import itertools
import logging
import dask.array as da
import numba
import numpy as np
import toolz
from dask.array.rechunk import intersect_chunks
from dask.highlevelgraph import HighLevelGraph
from .chunkstore import PlaceholderChunk
from .flags import DATA_LOST
from .van_vleck import autocorr_lookup_table
and context from other files:
# Path: katdal/chunkstore.py
# class PlaceholderChunk:
# """Chunk returned to indicate missing data."""
#
# def __init__(self, shape, dtype):
# self.shape = shape
# self.dtype = np.dtype(dtype)
#
# def __getitem__(self, index):
# # Create an array with a zero-sized dtype, so that it takes no memory
# dummy = np.empty(self.shape, dtype=[])
# new_shape = dummy[index].shape
# return PlaceholderChunk(new_shape, self.dtype)
#
# Path: katdal/flags.py
# DATA_LOST = 1 << DATA_LOST_BIT
#
# Path: katdal/van_vleck.py
# def autocorr_lookup_table(levels, size=4000):
# """Lookup table that corrects complex autocorrelation quantisation effects.
#
# This maps the variance of a quantised complex voltage signal to the variance
# of the unquantised signal under the assumption that the signal is proper
# (circularly-symmetric) complex normally distributed.
#
# Parameters
# ----------
# levels : sequence of float
# Quantisation levels for real and imaginary components of voltage signal
# size : int, optional
# Size of lookup table
#
# Returns
# -------
# quantised_autocorr_table, true_autocorr_table : array of float, shape (`size`,)
# Lookup table associating quantised autocorrelations and unquantised
# autocorrelations (i.e. power/variance of complex signals)
# """
# # Terminology:
# # x = Proper complex normal voltage signal (zero-mean)
# # rxx = Power (variance) *per* real/imag component of unquantised / true x
# # sxx = Power (variance) *per* real/imag component of quantised x
# abs_levels = np.abs(levels)
# sxx_min_nonzero = abs_levels[abs_levels > 0].min() ** 2
# sxx_max = abs_levels.max() ** 2
# # Sweep across range of true power values, placing more table entries at tricky lower end
# rxx_grid = np.r_[np.logspace(-2.4, 0, size // 2, endpoint=False),
# np.logspace(0, np.log10(sxx_max / sxx_min_nonzero) + 8, size - 2 - size // 2)]
# # Shift the table to place inflection point at minimum non-zero sxx
# rxx_grid *= sxx_min_nonzero
# # Map true power to expected quantised power
# sxx_mean = _squared_quant_norm0_mean(levels, rxx_grid)
# # Extend quantised power values to its maximum range
# sxx_table = np.r_[0., sxx_mean, sxx_max]
# # Replace asymptotic with linear decay at bottom end, and clip unbounded growth at top end
# rxx_table = np.r_[0., rxx_grid, rxx_grid[-1]]
# # The factor 2 converts power per real/imag component to power/variance of complex signal
# return 2. * sxx_table, 2. * rxx_table
, which may contain function names, class names, or code. Output only the next line. | quantised_autocorr_table, true_autocorr_table = autocorr_lookup_table(levels) |
Continue the code snippet: <|code_start|># of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
def test_norm0_cdf():
scale = 2.0
x = np.array([0.0, 2.0, 4.0, 6.0])
# Generated by scipy.stats.norm.cdf(x, scale=2.0)
expected = np.array([0.5, 0.8413447460685429, 0.9772498680518208, 0.9986501019683699])
actual = norm0_cdf(x, scale)
np.testing.assert_allclose(actual, expected, rtol=0., atol=np.finfo(float).eps)
actual = norm0_cdf(-x, scale)
np.testing.assert_allclose(actual, 1.0 - expected, rtol=0., atol=np.finfo(float).eps)
actual = norm0_cdf(x[-1], scale)
np.testing.assert_allclose(actual, expected[-1], rtol=0., atol=np.finfo(float).eps)
def test_autocorr_correction():
# 15-level "4-bit" KAT-7 requantiser (contiguous ints for now)
levels = np.arange(-7., 8.)
<|code_end|>
. Use current file imports:
import numpy as np
from katdal.van_vleck import autocorr_lookup_table, norm0_cdf
and context (classes, functions, or code) from other files:
# Path: katdal/van_vleck.py
# def autocorr_lookup_table(levels, size=4000):
# """Lookup table that corrects complex autocorrelation quantisation effects.
#
# This maps the variance of a quantised complex voltage signal to the variance
# of the unquantised signal under the assumption that the signal is proper
# (circularly-symmetric) complex normally distributed.
#
# Parameters
# ----------
# levels : sequence of float
# Quantisation levels for real and imaginary components of voltage signal
# size : int, optional
# Size of lookup table
#
# Returns
# -------
# quantised_autocorr_table, true_autocorr_table : array of float, shape (`size`,)
# Lookup table associating quantised autocorrelations and unquantised
# autocorrelations (i.e. power/variance of complex signals)
# """
# # Terminology:
# # x = Proper complex normal voltage signal (zero-mean)
# # rxx = Power (variance) *per* real/imag component of unquantised / true x
# # sxx = Power (variance) *per* real/imag component of quantised x
# abs_levels = np.abs(levels)
# sxx_min_nonzero = abs_levels[abs_levels > 0].min() ** 2
# sxx_max = abs_levels.max() ** 2
# # Sweep across range of true power values, placing more table entries at tricky lower end
# rxx_grid = np.r_[np.logspace(-2.4, 0, size // 2, endpoint=False),
# np.logspace(0, np.log10(sxx_max / sxx_min_nonzero) + 8, size - 2 - size // 2)]
# # Shift the table to place inflection point at minimum non-zero sxx
# rxx_grid *= sxx_min_nonzero
# # Map true power to expected quantised power
# sxx_mean = _squared_quant_norm0_mean(levels, rxx_grid)
# # Extend quantised power values to its maximum range
# sxx_table = np.r_[0., sxx_mean, sxx_max]
# # Replace asymptotic with linear decay at bottom end, and clip unbounded growth at top end
# rxx_table = np.r_[0., rxx_grid, rxx_grid[-1]]
# # The factor 2 converts power per real/imag component to power/variance of complex signal
# return 2. * sxx_table, 2. * rxx_table
#
# @numba.vectorize(['f8(f8, f8)'], nopython=True, cache=True)
# def norm0_cdf(x, scale):
# """Fast zero-mean (loc=0) implementation of :meth:`scipy.stats.norm.cdf`."""
# return 0.5 * (math.erf(np.sqrt(0.5) * x / scale) + 1.)
. Output only the next line. | quantised_ac_table, true_ac_table = autocorr_lookup_table(levels) |
Predict the next line for this snippet: <|code_start|>################################################################################
# Copyright (c) 2020, National Research Foundation (SARAO)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
def test_norm0_cdf():
scale = 2.0
x = np.array([0.0, 2.0, 4.0, 6.0])
# Generated by scipy.stats.norm.cdf(x, scale=2.0)
expected = np.array([0.5, 0.8413447460685429, 0.9772498680518208, 0.9986501019683699])
<|code_end|>
with the help of current file imports:
import numpy as np
from katdal.van_vleck import autocorr_lookup_table, norm0_cdf
and context from other files:
# Path: katdal/van_vleck.py
# def autocorr_lookup_table(levels, size=4000):
# """Lookup table that corrects complex autocorrelation quantisation effects.
#
# This maps the variance of a quantised complex voltage signal to the variance
# of the unquantised signal under the assumption that the signal is proper
# (circularly-symmetric) complex normally distributed.
#
# Parameters
# ----------
# levels : sequence of float
# Quantisation levels for real and imaginary components of voltage signal
# size : int, optional
# Size of lookup table
#
# Returns
# -------
# quantised_autocorr_table, true_autocorr_table : array of float, shape (`size`,)
# Lookup table associating quantised autocorrelations and unquantised
# autocorrelations (i.e. power/variance of complex signals)
# """
# # Terminology:
# # x = Proper complex normal voltage signal (zero-mean)
# # rxx = Power (variance) *per* real/imag component of unquantised / true x
# # sxx = Power (variance) *per* real/imag component of quantised x
# abs_levels = np.abs(levels)
# sxx_min_nonzero = abs_levels[abs_levels > 0].min() ** 2
# sxx_max = abs_levels.max() ** 2
# # Sweep across range of true power values, placing more table entries at tricky lower end
# rxx_grid = np.r_[np.logspace(-2.4, 0, size // 2, endpoint=False),
# np.logspace(0, np.log10(sxx_max / sxx_min_nonzero) + 8, size - 2 - size // 2)]
# # Shift the table to place inflection point at minimum non-zero sxx
# rxx_grid *= sxx_min_nonzero
# # Map true power to expected quantised power
# sxx_mean = _squared_quant_norm0_mean(levels, rxx_grid)
# # Extend quantised power values to its maximum range
# sxx_table = np.r_[0., sxx_mean, sxx_max]
# # Replace asymptotic with linear decay at bottom end, and clip unbounded growth at top end
# rxx_table = np.r_[0., rxx_grid, rxx_grid[-1]]
# # The factor 2 converts power per real/imag component to power/variance of complex signal
# return 2. * sxx_table, 2. * rxx_table
#
# @numba.vectorize(['f8(f8, f8)'], nopython=True, cache=True)
# def norm0_cdf(x, scale):
# """Fast zero-mean (loc=0) implementation of :meth:`scipy.stats.norm.cdf`."""
# return 0.5 * (math.erf(np.sqrt(0.5) * x / scale) + 1.)
, which may contain function names, class names, or code. Output only the next line. | actual = norm0_cdf(x, scale) |
Predict the next line for this snippet: <|code_start|> Pattern(1)]
pat_goal = [[Pattern(0.1, ["BD", "YD"]),
Pattern(0.1, ["OK"]),
Pattern(0.1, ["BI", "YI"])],
3 * [Pattern(0.1),
Pattern(0.1, ["BI", "BD", "OK", "YI", "YD"])]]
pat_ok = [Pattern(0.3, ["OK"])]
pat_upload_feedback = 2 * [Pattern(0.1, ["OK"]), Pattern(0.1)]
pat_error = 2 * [Pattern(0.3, ["YD", "BD"]),
Pattern(0.3)]
pat_demo = [Pattern(1, ["BD"]),
Pattern(1, ["BI"]),
Pattern(1, ["YD"]),
Pattern(1, ["YI"]),
Pattern(1, ["OK"])]
if __name__ == "__main__":
def write_data(led_event):
leds = led_event.data
print("\r", end="")
for led in ["BD", "BI", "OK", "YI", "YD"]:
print("0" if led in leds else " ", end=" ")
sys.stdout.flush()
<|code_end|>
with the help of current file imports:
import time
import sys
import threading
import queue
import collections
from foos.bus import Bus
and context from other files:
# Path: foos/bus.py
# class Bus:
# def __init__(self):
# self.queue = mp.Queue()
# self.subscribers = []
# Thread(target=self.__run, daemon=True).start()
#
# def subscribe_map(self, fmap, thread=False):
# def f(ev):
# fmap[ev.name](ev.data)
#
# self.subscribe(f, thread=thread, subscribed_events=fmap.keys())
#
# def subscribe(self, f, thread=False, subscribed_events=None):
# if thread:
# f = self.__threaded_func(f, subscribed_events)
#
# def fs(ev):
# if ev.name in subscribed_events:
# f(ev)
#
# self.subscribers.append(fs if subscribed_events else f)
#
# def notify(self, ev, ev_data=None):
# self.queue.put(Event(ev, ev_data))
#
# def __threaded_func(self, f, subscribed_events=None):
# q = queue.Queue(maxsize=20)
#
# def trun():
# while True:
# ev = q.get()
# try:
# f(ev)
# except:
# logger.exception("Error delivering event")
# finally:
# q.task_done()
#
# def fthread(ev):
# try:
# if subscribed_events is None or ev.name in subscribed_events:
# q.put_nowait(ev)
#
# except queue.Full:
# logger.warning("Queue full when sending %s to %s", ev.name, f)
#
# Thread(target=trun, daemon=True).start()
# return fthread
#
# def __run(self):
# while True:
# e = self.queue.get()
# for s in self.subscribers:
# s(e)
, which may contain function names, class names, or code. Output only the next line. | bus = Bus() |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Plugin:
def __init__(self, bus):
bus.subscribe(self.process_event, thread=False, subscribed_events=['results_written'])
<|code_end|>
. Use current file imports:
import requests
import threading
import logging
import foos.config as config
import json
from plugins.league import diskbackend
and context (classes, functions, or code) from other files:
# Path: plugins/league.py
# class DiskBackend:
# class Plugin:
# def __init__(self):
# def get_games(self):
# def write_games(self, competition):
# def filter_played_games(self, competition):
# def write_results(self, match):
# def get_result_files(self):
# def _get_result_file_for(self, match):
# def mark_result_as_processed(self, name):
# def __init__(self, bus):
# def save(self):
# def load(self, state):
# def update_players(self):
# def pstring(ps):
# def clear_players(self):
# def start_competition(self, data):
# def win_game(self, data):
# def cancel_competition(self, data):
# def get_player_points_per_match(self):
# def calc_points(self):
# def get_menu_entries(self):
# def q(ev, data=None):
# def f():
. Output only the next line. | self.diskbe = diskbackend |
Continue the code snippet: <|code_start|>#!/usr/bin/python3
logger = logging.getLogger(__name__)
class Plugin:
def __init__(self, bus):
self.bus = bus
self.bus.subscribe(self.process_event, thread=True)
self.game_win_score = None
self.check_win_time = None
self.check_delay = 2
self.current_score = {}
self.party_timeout = None
self.game_end_time = None
self.timeout_close_time = None
self.sudden_death = False
self.timeout_close_secs = 15
<|code_end|>
. Use current file imports:
from threading import Thread
from foos import config
from foos.ui.ui import registerMenu
import time
import logging
and context (classes, functions, or code) from other files:
# Path: foos/config.py
#
# Path: foos/ui/ui.py
# def registerMenu(f):
# menuGenerators.append(f)
. Output only the next line. | self.modes = config.game_modes |
Next line prediction: <|code_start|>#!/usr/bin/python3
logger = logging.getLogger(__name__)
class Plugin:
def __init__(self, bus):
self.bus = bus
self.bus.subscribe(self.process_event, thread=True)
self.game_win_score = None
self.check_win_time = None
self.check_delay = 2
self.current_score = {}
self.party_timeout = None
self.game_end_time = None
self.timeout_close_time = None
self.sudden_death = False
self.timeout_close_secs = 15
self.modes = config.game_modes
# Turn off party mode after this time in sudden death
self.party_mode_auto_off = 600
<|code_end|>
. Use current file imports:
(from threading import Thread
from foos import config
from foos.ui.ui import registerMenu
import time
import logging)
and context including class names, function names, or small code snippets from other files:
# Path: foos/config.py
#
# Path: foos/ui/ui.py
# def registerMenu(f):
# menuGenerators.append(f)
. Output only the next line. | registerMenu(self.getMenuEntries) |
Here is a snippet: <|code_start|>
class Plugin:
def __init__(self, bus):
self.bus = bus
bus.subscribe_map({'replay_request': lambda d: self.replay('long', 'manual', {}),
'score_goal': lambda d: self.replay('short', 'goal', d)},
thread=True)
def replay(self, replay_type, trigger, extra={}):
extra['type'] = trigger
<|code_end|>
. Write the next line using the current file imports:
import foos.config as config
import os
import time
from foos.process import call_and_log
from foos.platform import is_pi
and context from other files:
# Path: foos/process.py
# def call_and_log(*args, **kwargs):
# """Run process, gather output and write to log"""
# p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
# stdout, stderr = p.communicate()
# if len(stdout) > 0:
# logger.info(stdout.decode("utf-8").strip())
# if len(stderr) > 0:
# logger.error(stderr.decode("utf-8").strip())
# if p.returncode != 0:
# logger.error("{} returned {}".format(p.args, p.returncode))
#
# Path: foos/platform.py
# def is_pi():
# return pi3d.PLATFORM == pi3d.PLATFORM_PI
, which may include functions, classes, or code. Output only the next line. | call_and_log(["video/generate-replay.sh", config.replay_path, |
Given snippet: <|code_start|>
class Plugin:
def __init__(self, bus):
self.bus = bus
bus.subscribe_map({'replay_request': lambda d: self.replay('long', 'manual', {}),
'score_goal': lambda d: self.replay('short', 'goal', d)},
thread=True)
def replay(self, replay_type, trigger, extra={}):
extra['type'] = trigger
call_and_log(["video/generate-replay.sh", config.replay_path,
str(config.ignore_recent_chunks),
str(config.long_chunks), str(config.short_chunks)])
self.bus.notify('replay_start', extra)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import foos.config as config
import os
import time
from foos.process import call_and_log
from foos.platform import is_pi
and context:
# Path: foos/process.py
# def call_and_log(*args, **kwargs):
# """Run process, gather output and write to log"""
# p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
# stdout, stderr = p.communicate()
# if len(stdout) > 0:
# logger.info(stdout.decode("utf-8").strip())
# if len(stderr) > 0:
# logger.error(stderr.decode("utf-8").strip())
# if p.returncode != 0:
# logger.error("{} returned {}".format(p.args, p.returncode))
#
# Path: foos/platform.py
# def is_pi():
# return pi3d.PLATFORM == pi3d.PLATFORM_PI
which might include code, classes, or functions. Output only the next line. | if is_pi(): |
Predict the next line after this snippet: <|code_start|> self.setText()
self.changed = False
self.first = False
self.select.draw()
self.bg_t.draw()
self.bg.draw()
self.title_shape.draw()
if self.offset > 0:
self.up_i.draw()
if len(self.options) > self.offset + self.n:
self.down_i.draw()
for s in self.shapes:
s.draw()
def selected(self):
idx = self.offset + self.selectpos
return (idx, self.options[idx])
def setOptions(self, options):
self.offset = 0
self.selectpos = 0
self.options = options
self.changed = True
<|code_end|>
using the current file's imports:
import pi3d
from .anim import Delegate
and any relevant context from other files:
# Path: foos/ui/anim.py
# class Delegate:
# def __init__(self, delegate):
# self.delegate = delegate
#
# def __getattr__(self, name):
# return getattr(self.delegate, name)
. Output only the next line. | class MenuTree(Delegate): |
Using the snippet: <|code_start|>#!/usr/bin/python3
State = namedtuple('State', ['yellow_goals', 'black_goals', 'last_goal'])
logger = logging.getLogger(__name__)
class Plugin:
def __init__(self, bus):
<|code_end|>
, determine the next line of code. You have imports:
from collections import namedtuple
from foos.clock import Clock
import logging
import foos.config as config
and context (class names, function names, or code) available:
# Path: foos/clock.py
# class Clock:
# def __init__(self, name):
# self.name = name
# self.time = None
#
# def set(self, ts):
# self.time = ts
#
# def get(self):
# return self.time
#
# def reset(self):
# self.time = time.time()
#
# def get_diff(self):
# if self.time:
# return time.time() - self.time
# else:
# return None
. Output only the next line. | self.last_goal_clock = Clock('last_goal_clock') |
Given the following code snippet before the placeholder: <|code_start|> def write_results(self, match):
fname = self._get_result_file_for(match)
with open(fname, 'w') as f:
json.dump(match, f, indent=2)
def get_result_files(self):
pattern = os.path.join(league_results_dir, 'result_*.json')
return glob.glob(pattern)
def _get_result_file_for(self, match):
return os.path.join(league_results_dir,
'result_%d.json' % match.get('id', random.randint(0, 10000)))
def mark_result_as_processed(self, name):
target = os.path.join(processed_dir, os.path.basename(name))
shutil.move(name, target)
diskbackend = DiskBackend()
class Plugin:
def __init__(self, bus):
self.bus = bus
self.bus.subscribe_map({"start_competition": self.start_competition,
"win_game": self.win_game,
"cancel_competition": self.cancel_competition},
thread=True)
self.current_game = 0
self.match = None
self.backend = diskbackend
<|code_end|>
, predict the next line using imports from the current file:
import time
import logging
import json
import random
import os
import glob
import shutil
import foos.config as config
from foos.ui.ui import registerMenu
and context including class names, function names, and sometimes code from other files:
# Path: foos/ui/ui.py
# def registerMenu(f):
# menuGenerators.append(f)
. Output only the next line. | registerMenu(self.get_menu_entries) |
Predict the next line after this snippet: <|code_start|>
class Plugin(IOBase):
bitmap = {
"YD": 0b00001,
"YI": 0b00010,
"BD": 0b00100,
"BI": 0b01000,
"OK": 0b10000
}
def __init__(self, bus):
self.ser = None
super().__init__(bus)
def __getArduinoValueFor(self, leds):
value = sum(map(lambda x: self.bitmap.get(x, 0), leds))
return chr(value + ord('A'))
def convert_data(self, data):
return (self.__getArduinoValueFor(data) + "\n").encode("ascii")
def reader_thread(self):
while True:
if not self.ser:
self.open_serial()
try:
line = self.ser.readline()
try:
line = line.decode('ascii').strip()
<|code_end|>
using the current file's imports:
import time
import serial
import glob
import logging
from .io_base import IOBase
from .arduino import getEventForButton
and any relevant context from other files:
# Path: plugins/io_base.py
# class IOBase:
# def __init__(self, bus):
# self.bus = bus
# self.bus.subscribe(self.process_event, thread=False)
# self.write_queue = Queue(10)
# self.reader = threading.Thread(target=self.reader_thread)
# self.reader.daemon = True
# self.reader.start()
# self.writer = threading.Thread(target=self.writer_thread)
# self.writer.daemon = True
# self.writer.start()
#
# def reader_thread(self):
# raise NotImplementedError()
#
# def writer_thread(self):
# raise NotImplementedError()
#
# def convert_data(self, data):
# return data
#
# def process_event(self, ev):
# try:
# if ev.name == "leds_enabled":
# data = self.convert_data(ev.data)
# self.write_queue.put_nowait(data)
# except queue.Full:
# #TODO alert somehow without flooding?
# pass
#
# Path: plugins/arduino.py
# def getEventForButton(line):
# if any([k in line for k in goalmap.keys()]):
# parts = line.split()
# data = {'source': 'serial', 'team': goalmap[parts[0]]}
#
# if len(parts) > 1:
# data['duration'] = int(parts[1])
#
# if len(parts) > 2:
# data['elapsed'] = int(parts[2])
#
# return 'goal_event', data
#
# if '_' in line:
# btn, state = line.split('_')
# btn = btnmap.get(btn, 'ERROR')
# state = statemap.get(state, 'ERROR')
# return 'button_event', {'source': 'serial', 'btn': btn, 'state': state}
#
# return None
. Output only the next line. | ev = getEventForButton(line) |
Predict the next line after this snippet: <|code_start|> time.sleep(sleep_seconds)
class Plugin:
def __init__(self, bus):
self.bus = bus
self.bus.subscribe(self.process_event, thread=True)
self.replay_data = {}
self.current_score = ('?', '?')
def process_event(self, ev):
if ev.name == 'score_changed':
self.current_score = ev.data['yellow'], ev.data['black']
elif ev.name == 'replay_start':
self.replay_data = ev.data
if ev.name != 'upload_request':
return
self.bus.notify('upload_start')
text = 'Replay'
if self.replay_data.get('type') == 'goal':
text = '{} goal'.format(self.replay_data.get('team', '?').capitalize())
title = "{}: {}-{}".format(text, self.current_score[0], self.current_score[1])
logger.info("Uploading video: %s", title)
try:
in_file = os.path.join(config.replay_path, 'replay_long.h264')
out_file = os.path.join(config.replay_path, 'replay_long.mp4')
<|code_end|>
using the current file's imports:
import http.client
import httplib2
import os
import random
import sys
import time
import logging
import foos.config as config
from foos.process import call_and_log
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
and any relevant context from other files:
# Path: foos/process.py
# def call_and_log(*args, **kwargs):
# """Run process, gather output and write to log"""
# p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
# stdout, stderr = p.communicate()
# if len(stdout) > 0:
# logger.info(stdout.decode("utf-8").strip())
# if len(stderr) > 0:
# logger.error(stderr.decode("utf-8").strip())
# if p.returncode != 0:
# logger.error("{} returned {}".format(p.args, p.returncode))
. Output only the next line. | call_and_log(["video/convert.sh", in_file, out_file]) |
Given snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Plugin(IOBase):
def convert_data(self, data):
return ("Leds: %s\n" % ', '.join(data))
def reader_thread(self):
fifo_file = "/tmp/foos-debug.in"
try:
os.mkfifo(fifo_file)
except:
pass
while True:
f = open(fifo_file, "r")
if not f:
logger.error("Error opening fifo file %s", fifo_file)
time.sleep(5)
continue
logger.info("Opened new debugging session")
while True:
line = f.readline()
if not line:
break
line = line.strip()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import os
import logging
from .io_base import IOBase
from .arduino import getEventForButton
and context:
# Path: plugins/io_base.py
# class IOBase:
# def __init__(self, bus):
# self.bus = bus
# self.bus.subscribe(self.process_event, thread=False)
# self.write_queue = Queue(10)
# self.reader = threading.Thread(target=self.reader_thread)
# self.reader.daemon = True
# self.reader.start()
# self.writer = threading.Thread(target=self.writer_thread)
# self.writer.daemon = True
# self.writer.start()
#
# def reader_thread(self):
# raise NotImplementedError()
#
# def writer_thread(self):
# raise NotImplementedError()
#
# def convert_data(self, data):
# return data
#
# def process_event(self, ev):
# try:
# if ev.name == "leds_enabled":
# data = self.convert_data(ev.data)
# self.write_queue.put_nowait(data)
# except queue.Full:
# #TODO alert somehow without flooding?
# pass
#
# Path: plugins/arduino.py
# def getEventForButton(line):
# if any([k in line for k in goalmap.keys()]):
# parts = line.split()
# data = {'source': 'serial', 'team': goalmap[parts[0]]}
#
# if len(parts) > 1:
# data['duration'] = int(parts[1])
#
# if len(parts) > 2:
# data['elapsed'] = int(parts[2])
#
# return 'goal_event', data
#
# if '_' in line:
# btn, state = line.split('_')
# btn = btnmap.get(btn, 'ERROR')
# state = statemap.get(state, 'ERROR')
# return 'button_event', {'source': 'serial', 'btn': btn, 'state': state}
#
# return None
which might include code, classes, or functions. Output only the next line. | ev = getEventForButton(line) |
Given the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Plugin:
def __init__(self, bus, standby_timeout=500):
self.standby_timeout = config.standby_timeout_secs
self.bus = bus
self.activation_events = ["button_event", "movement_detected", "goal_event"]
self.last_active = time.time()
self.active = True
# disable if standby_timeout is 0
if self.standby_timeout != 0:
self.bus.subscribe(self.process_event, subscribed_events=self.activation_events)
threading.Thread(daemon=True, target=self.run).start()
def run(self):
while True:
time.sleep(1)
if self.active and time.time() > (self.last_active + self.standby_timeout):
self.turn_off()
def turn_off(self):
logger.info("Turning TV off...")
self.active = False
<|code_end|>
, generate the next line using the imports in this file:
import time
import threading
import foos.config as config
import logging
from foos.process import call_and_log
and context (functions, classes, or occasionally code) from other files:
# Path: foos/process.py
# def call_and_log(*args, **kwargs):
# """Run process, gather output and write to log"""
# p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
# stdout, stderr = p.communicate()
# if len(stdout) > 0:
# logger.info(stdout.decode("utf-8").strip())
# if len(stderr) > 0:
# logger.error(stderr.decode("utf-8").strip())
# if p.returncode != 0:
# logger.error("{} returned {}".format(p.args, p.returncode))
. Output only the next line. | call_and_log("echo 'standby 0' | cec-client -s >/dev/null", shell=True) |
Predict the next line for this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class Plugin(object):
def __init__(self, bus):
self.bus = bus
self.bus.subscribe(self.process_event, thread=True)
self.players = {}
def get_players(self, team):
return self.players.get(team, [])
def get_team_name(self, team):
players = self.get_players(team)
if len(players) > 0:
p = " (" + ", ".join(players) + ")"
else:
p = ""
<|code_end|>
with the help of current file imports:
import foos.config as config
import logging
from foos import utils
and context from other files:
# Path: foos/utils.py
# def teamName(team):
, which may contain function names, class names, or code. Output only the next line. | return utils.teamName(team).capitalize() + p |
Based on the snippet: <|code_start|> self.pin = pin_number
self.team = team
if self.pin:
#GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=self.on_goal, bouncetime=10)
else:
logger.warn("Cannot init GoalDetector {0}, pin not specified".format(self.team))
def __del__(self):
if self.pin:
GPIO.remove_event_detect(self.pin)
def on_goal(self, channel):
logger.info("Goal {}!".format(self.team))
self.bus.notify('goal_event', {'source': 'rpi', 'team': self.team})
class IRBarrierPwmGenerator:
def __init__(self):
# https://sites.google.com/site/semilleroadt/raspberry-pi-tutorials/gpio:
# "According to it, configure GPIO18 (WiringPi Pin 1)..."
# Raspberry base PWM frequency: 19,200,000 Hz
# Resulted frequency: base freq / 101 / 5 = 38.019 kHz
# Signal duty cycle = 3/5 = ~60%
process.call_and_log("gpio mode 1 pwm && gpio pwm-ms && gpio pwmr 5 && gpio pwmc 101 && gpio pwm 1 2", shell=True)
def __del__(self):
process.call_and_log("gpio pwm 1 0", shell=True)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import logging
import ctypes
import time
import RPi.GPIO as GPIO
import foos.config as config
import foos.process as process
from .io_base import IOBase
and context (classes, functions, sometimes code) from other files:
# Path: plugins/io_base.py
# class IOBase:
# def __init__(self, bus):
# self.bus = bus
# self.bus.subscribe(self.process_event, thread=False)
# self.write_queue = Queue(10)
# self.reader = threading.Thread(target=self.reader_thread)
# self.reader.daemon = True
# self.reader.start()
# self.writer = threading.Thread(target=self.writer_thread)
# self.writer.daemon = True
# self.writer.start()
#
# def reader_thread(self):
# raise NotImplementedError()
#
# def writer_thread(self):
# raise NotImplementedError()
#
# def convert_data(self, data):
# return data
#
# def process_event(self, ev):
# try:
# if ev.name == "leds_enabled":
# data = self.convert_data(ev.data)
# self.write_queue.put_nowait(data)
# except queue.Full:
# #TODO alert somehow without flooding?
# pass
. Output only the next line. | class Plugin(IOBase):
|
Given the code snippet: <|code_start|>
class Plugin:
def __init__(self, bus):
Thread(target=self.runCamera, daemon=True).start()
# Run camera
def runCamera(self):
while True:
<|code_end|>
, generate the next line using the imports in this file:
from foos.process import long_running
from threading import Thread
import time
import foos.config as config
and context (functions, classes, or occasionally code) from other files:
# Path: foos/process.py
# def long_running(*args, **kwargs):
# """Run process redirecting stderr to stdout and write output to log"""
# p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, **kwargs)
# with p.stdout:
# for line in iter(p.stdout.readline, b''):
# logger.error(line.decode("utf-8").strip())
#
# p.wait()
# if p.returncode != 0:
# logger.error("{} returned {}".format(p.args, p.returncode))
. Output only the next line. | long_running(["video/run-camera.sh"]) |
Using the snippet: <|code_start|>
def test_count_tree_size():
root = astroid.builder.parse("""
def test(x, y):
return x * y if x > 5 else 0
""")
<|code_end|>
, determine the next line of code. You have imports:
import astroid
from shopify_python import ast
and context (class names, function names, or code) available:
# Path: shopify_python/ast.py
# def count_tree_size(node): # type: (astroid.NodeNG) -> int
. Output only the next line. | assert ast.count_tree_size(root) == 14 |
Given the code snippet: <|code_start|>
@pytest.fixture
def remote_repo(tmpdir):
# type: ('py.path.LocalPath') -> repo.Repo
return repo.Repo.init(str(tmpdir.join('remote')), bare=True)
@pytest.fixture
def main_repo(tmpdir, remote_repo):
# type: ('py.path.LocalPath', repo.Repo) -> repo.Repo
to_dir = str(tmpdir.join('main'))
new_repo = repo.Repo.clone_from(remote_repo.git_dir, to_dir)
file_name = os.path.join(new_repo.working_dir, 'new_file')
open(str(file_name), 'wb').close()
new_repo.index.add([str(file_name)])
new_repo.index.commit("initial commit")
new_repo.remote('origin').push('master')
return new_repo
def test_detects_changed_python_files(main_repo, python_file, python_script):
# type: (repo.Repo, str, str) -> None
main_repo.create_head('foo').checkout()
main_repo.index.add([python_file, python_script])
main_repo.index.commit("adding python files")
<|code_end|>
, generate the next line using the imports in this file:
import os
import py # pylint: disable=unused-import
import pytest
import git # pylint: disable=unused-import
from git import repo
from shopify_python import git_utils
and context (functions, classes, or occasionally code) from other files:
# Path: shopify_python/git_utils.py
# class GitUtilsException(Exception):
# class _CustomPylintReporter(text.ColorizedTextReporter):
# def _remote_origin_master(git_repo):
# def _modified_in_branch(git_repo, other_ref):
# def _file_is_python(path):
# def changed_python_files_in_tree(root_path):
# def autopep_files(files, max_line_length):
# def __init__(self):
# def handle_message(self, msg):
# def pylint_files(files, **kwargs):
. Output only the next line. | changed_files = git_utils.changed_python_files_in_tree(main_repo.working_dir) |
Next line prediction: <|code_start|>
def multiset_difference(left_op, right_op):
"""Takes two multisets and compares them.
A multiset is a dict with the cardinality of the key as the value.
:param left_op: The expected entries.
:param right_op: Actual entries.
:returns: The two multisets of missing and unexpected messages.
"""
missing = left_op.copy()
missing.subtract(right_op)
unexpected = {}
for key, value in list(six.iteritems(missing)):
if value <= 0:
missing.pop(key)
if value < 0:
unexpected[key] = -value
return missing, unexpected
class LintModuleTest(object):
maxDiff = None
def __init__(self, test_file):
test_reporter = FunctionalTestReporter()
self._linter = lint.PyLinter()
<|code_end|>
. Use current file imports:
(import csv
import collections
import io
import operator
import os
import re
import sys
import platform
import six
import pytest
from six.moves import configparser
from pylint import checkers
from pylint import interfaces
from pylint import lint
from pylint import reporters
from tests.shopify_python import google_styleguide
from tests.shopify_python import shopify_styleguide)
and context including class names, function names, or small code snippets from other files:
# Path: shopify_python/google_styleguide.py
# def register_checkers(linter): # type: (lint.PyLinter) -> None
# def __init__(self, linter):
# def visit_assign(self, node): # type: (astroid.Assign) -> None
# def visit_excepthandler(self, node): # type: (astroid.ExceptHandler) -> None
# def visit_lambda(self, node): # type: (astroid.Lambda) -> None
# def visit_listcomp(self, node): # type: (astroid.ListComp) -> None
# def visit_tryexcept(self, node): # type: (astroid.TryExcept) -> None
# def visit_tryfinally(self, node): # type: (astroid.TryFinally) -> None
# def visit_importfrom(self, node): # type: (astroid.ImportFrom) -> None
# def visit_raise(self, node): # type: (astroid.Raise) -> None
# def visit_if(self, node):
# def visit_classdef(self, node): # type: (astroid.ClassDef) -> None
# def __get_module_names(node): # type: (astroid.ImportFrom) -> typing.Generator[str, None, None]
# def __import_modules_only(self, node): # type: (astroid.ImportFrom) -> None
# def __import_full_path_only(self, node): # type: (astroid.ImportFrom) -> None
# def __limit_one_import(self, node): # type: (astroid.ImportFrom) -> None
# def __avoid_global_variables(self, node): # type: (astroid.Assign) -> None
# def check_assignment(node):
# def __dont_use_archaic_raise_syntax(self, node): # type: (astroid.Raise) -> None
# def __dont_catch_standard_error(self, node): # type: (astroid.ExceptHandler) -> None
# def __minimize_code_in_try_except(self, node): # type: (astroid.TryExcept) -> None
# def __minimize_code_in_finally(self, node): # type: (astroid.TryFinally) -> None
# def __use_simple_lambdas(self, node): # type: (astroid.Lambda) -> None
# def __use_simple_list_comp(self, node): # type: (astroid.ListComp) -> None
# def __use_cond_expr(self, node): # type: (astroid.If) -> None
# def __lambda_func(self, node): # type: (astroid.Lambda) -> None
# def __class_def_check(self, node): # type: (astroid.ClassDef) -> None
# class GoogleStyleGuideChecker(checkers.BaseChecker):
# UNARY_OPERATORS = {
# "~": "invert",
# "-": "neg",
# "not": "not_",
# "+": "pos"
# }
# BINARY_OPERATORS = {
# "+": "add",
# "in": "contains",
# "/": "truediv",
# "//": "floordiv",
# "&": "and_",
# "^": "xor",
# "|": "or_",
# "**": "pow",
# "is": "is",
# "is not": "is_not",
# "<<": "lshift",
# "%": "modulo",
# "*": "mul",
# ">>": "rshift",
# "-": "sub",
# "<": "lt",
# "<=": "le",
# "==": "eq",
# "!=": "ne",
# ">=": "ge",
# ">": "gt"
# }
#
# Path: shopify_python/shopify_styleguide.py
# def register_checkers(linter): # type: (lint.PyLinter) -> None
# def process_tokens(self, tokens):
# def __validate_comment(self, string, start):
# def __validate_name(self, string, start, line):
# def __disable_name_only(self, string, start):
# def get_name(code):
# def __sequence_str(self, string, start):
# class ShopifyStyleGuideChecker(checkers.BaseTokenChecker):
# RE_PYLINT_DISABLE = re.compile(r'^#[ \t]*pylint:[ \t]*(disable|enable)[ \t]*=(?P<messages>[a-zA-Z0-9\-_, \t]+)$')
# RE_PYLINT_MESSAGE_CODE = re.compile(r'^[A-Z]{1,2}[0-9]{4}$')
# RE_COMMENT_TYPE_ANNOTATION = re.compile(r'^# type.*:.*$')
# RE_SEQUENCE_STRING = re.compile(r'^.*Sequence\[str\].*$')
. Output only the next line. | google_styleguide.register_checkers(self._linter) |
Predict the next line for this snippet: <|code_start|>
def multiset_difference(left_op, right_op):
"""Takes two multisets and compares them.
A multiset is a dict with the cardinality of the key as the value.
:param left_op: The expected entries.
:param right_op: Actual entries.
:returns: The two multisets of missing and unexpected messages.
"""
missing = left_op.copy()
missing.subtract(right_op)
unexpected = {}
for key, value in list(six.iteritems(missing)):
if value <= 0:
missing.pop(key)
if value < 0:
unexpected[key] = -value
return missing, unexpected
class LintModuleTest(object):
maxDiff = None
def __init__(self, test_file):
test_reporter = FunctionalTestReporter()
self._linter = lint.PyLinter()
google_styleguide.register_checkers(self._linter)
<|code_end|>
with the help of current file imports:
import csv
import collections
import io
import operator
import os
import re
import sys
import platform
import six
import pytest
from six.moves import configparser
from pylint import checkers
from pylint import interfaces
from pylint import lint
from pylint import reporters
from tests.shopify_python import google_styleguide
from tests.shopify_python import shopify_styleguide
and context from other files:
# Path: shopify_python/google_styleguide.py
# def register_checkers(linter): # type: (lint.PyLinter) -> None
# def __init__(self, linter):
# def visit_assign(self, node): # type: (astroid.Assign) -> None
# def visit_excepthandler(self, node): # type: (astroid.ExceptHandler) -> None
# def visit_lambda(self, node): # type: (astroid.Lambda) -> None
# def visit_listcomp(self, node): # type: (astroid.ListComp) -> None
# def visit_tryexcept(self, node): # type: (astroid.TryExcept) -> None
# def visit_tryfinally(self, node): # type: (astroid.TryFinally) -> None
# def visit_importfrom(self, node): # type: (astroid.ImportFrom) -> None
# def visit_raise(self, node): # type: (astroid.Raise) -> None
# def visit_if(self, node):
# def visit_classdef(self, node): # type: (astroid.ClassDef) -> None
# def __get_module_names(node): # type: (astroid.ImportFrom) -> typing.Generator[str, None, None]
# def __import_modules_only(self, node): # type: (astroid.ImportFrom) -> None
# def __import_full_path_only(self, node): # type: (astroid.ImportFrom) -> None
# def __limit_one_import(self, node): # type: (astroid.ImportFrom) -> None
# def __avoid_global_variables(self, node): # type: (astroid.Assign) -> None
# def check_assignment(node):
# def __dont_use_archaic_raise_syntax(self, node): # type: (astroid.Raise) -> None
# def __dont_catch_standard_error(self, node): # type: (astroid.ExceptHandler) -> None
# def __minimize_code_in_try_except(self, node): # type: (astroid.TryExcept) -> None
# def __minimize_code_in_finally(self, node): # type: (astroid.TryFinally) -> None
# def __use_simple_lambdas(self, node): # type: (astroid.Lambda) -> None
# def __use_simple_list_comp(self, node): # type: (astroid.ListComp) -> None
# def __use_cond_expr(self, node): # type: (astroid.If) -> None
# def __lambda_func(self, node): # type: (astroid.Lambda) -> None
# def __class_def_check(self, node): # type: (astroid.ClassDef) -> None
# class GoogleStyleGuideChecker(checkers.BaseChecker):
# UNARY_OPERATORS = {
# "~": "invert",
# "-": "neg",
# "not": "not_",
# "+": "pos"
# }
# BINARY_OPERATORS = {
# "+": "add",
# "in": "contains",
# "/": "truediv",
# "//": "floordiv",
# "&": "and_",
# "^": "xor",
# "|": "or_",
# "**": "pow",
# "is": "is",
# "is not": "is_not",
# "<<": "lshift",
# "%": "modulo",
# "*": "mul",
# ">>": "rshift",
# "-": "sub",
# "<": "lt",
# "<=": "le",
# "==": "eq",
# "!=": "ne",
# ">=": "ge",
# ">": "gt"
# }
#
# Path: shopify_python/shopify_styleguide.py
# def register_checkers(linter): # type: (lint.PyLinter) -> None
# def process_tokens(self, tokens):
# def __validate_comment(self, string, start):
# def __validate_name(self, string, start, line):
# def __disable_name_only(self, string, start):
# def get_name(code):
# def __sequence_str(self, string, start):
# class ShopifyStyleGuideChecker(checkers.BaseTokenChecker):
# RE_PYLINT_DISABLE = re.compile(r'^#[ \t]*pylint:[ \t]*(disable|enable)[ \t]*=(?P<messages>[a-zA-Z0-9\-_, \t]+)$')
# RE_PYLINT_MESSAGE_CODE = re.compile(r'^[A-Z]{1,2}[0-9]{4}$')
# RE_COMMENT_TYPE_ANNOTATION = re.compile(r'^# type.*:.*$')
# RE_SEQUENCE_STRING = re.compile(r'^.*Sequence\[str\].*$')
, which may contain function names, class names, or code. Output only the next line. | shopify_styleguide.register_checkers(self._linter) |
Given snippet: <|code_start|># for local debugging
if os.path.exists("../provisioning") is True:
sys.path.insert(0, "../../")
class TestBaseImport(unittest.TestCase):
def setUp(self):
super(TestBaseImport, self).setUp()
self.base_vm_path = None
self.base_hashvalue = None
self.temp_dir = mkdtemp(prefix="cloudlet-test-basevm-")
self.base_vm_cirros_filepath = os.path.join(
self.temp_dir, os.path.basename(Const.base_vm_cirros_url))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import os
import sys
import shutil
from tempfile import mkdtemp
from elijah.test.util import Const as Const
from elijah.test.util import VMUtility
from elijah.provisioning.package import PackagingUtil
and context:
# Path: elijah/test/util.py
# class Const(object):
#
# base_vm_cirros_url =\
# "https://storage.cmusatyalab.org/cloudlet-vm/cirros-0.3.4-x86_64-base.zip"
# overlay_url_cirros =\
# "https://storage.cmusatyalab.org/cloudlet-vm/cirros-overlay.zip"
#
# Path: elijah/test/util.py
# class VMUtility(object):
#
# @staticmethod
# def get_VM_status(machine):
# machine_id = machine.ID()
# conn = libvirt.open("qemu:///session")
# for each_id in conn.listDomainsID():
# if each_id == machine_id:
# each_machine = conn.lookupByID(machine_id)
# vm_state, reason = each_machine.state(0)
# return vm_state
# return None
#
# @staticmethod
# def download_baseVM(url, download_file):
# req = urllib2.urlopen(url)
# CHUNK_SIZE = 1024*1024
# with open(download_file, 'wb') as fd:
# while True:
# chunk = req.read(CHUNK_SIZE)
# if not chunk:
# break
# fd.write(chunk)
#
# @staticmethod
# def delete_basevm(base_path, base_hashvalue):
# if base_path is not None and base_hashvalue is not None:
# disk_path=base_path
# hash_value=base_hashvalue
# dbconn, matching_basevm = PackagingUtil._get_matching_basevm(disk_path)
# if matching_basevm:
# dbconn.del_item(matching_basevm)
# if matching_basevm:
# base_dir = os.path.dirname(base_path)
# shutil.rmtree(base_dir)
which might include code, classes, or functions. Output only the next line. | VMUtility.download_baseVM(Const.base_vm_cirros_url, |
Continue the code snippet: <|code_start|>class _HttpRequestManager:
"""
This class is responsible for
making Http request calls
"""
def __init__(self, auth: AuthBase):
self.auth = auth
self._logger = logging.getLogger(__name__)
self.request_session = requests.Session()
def post(self, url, data=None, json=None, **kwargs):
return self._raise_for_status(self.request_session.post(url, auth=self.auth, data=data, json=json, **kwargs))
def get(self, url, **kwargs):
return self._raise_for_status(self.request_session.get(url, auth=self.auth, **kwargs))
def put(self, url, data=None, **kwargs):
return self._raise_for_status(self.request_session.put(url, auth=self.auth, data=data, **kwargs))
def delete(self, url, **kwargs):
return self._raise_for_status(self.request_session.delete(url, auth=self.auth, **kwargs))
def get_raw(self, url):
return self.get(url, stream=True).raw
def _raise_for_status(self, response):
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == HTTPStatus.CONFLICT:
<|code_end|>
. Use current file imports:
from bs4 import BeautifulSoup
from http import HTTPStatus
from requests.auth import AuthBase
from .exceptions import ReloginRequiredException
import logging
import requests
and context (classes, functions, or code) from other files:
# Path: domino/exceptions.py
# class ReloginRequiredException(DominoException):
# """Re-login required Exception"""
# pass
. Output only the next line. | raise ReloginRequiredException("Temporary credentials expired") |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for package in orm['folivora.Package'].objects.all():
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from ..utils.pypi import normalize_name
and context (classes, functions, sometimes code) from other files:
# Path: folivora/utils/pypi.py
# def normalize_name(name):
# return pkg_resources.safe_name(name).lower()
. Output only the next line. | package.normalized_name = normalize_name(package.name) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
PROVIDES = ('pypi',)
class Package(models.Model):
PYPI = 'pypi'
PROVIDER_CHOICES = (
(PYPI, 'PyPi'),
)
name = models.CharField(_('name'), max_length=255, unique=True)
normalized_name = models.CharField(_('Normalized Name'), max_length=255,
unique=True)
url = models.URLField(_('url'))
provider = models.CharField(_('provider'), max_length=255,
choices=PROVIDER_CHOICES, default=PYPI)
initial_sync_done = models.BooleanField(default=False)
@classmethod
def create_with_provider_url(cls, name, provider='pypi', url=None):
if url is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import urlparse
import datetime
import pytz
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import make_aware, now
from django.contrib.auth.models import User
from django_orm.postgresql import hstore
from .utils.pypi import DEFAULT_SERVER, CheeseShop, normalize_name
from .tasks import sync_project
and context (classes, functions, sometimes code) from other files:
# Path: folivora/utils/pypi.py
# DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
#
# class CheeseShop(object):
#
# def __init__(self, server=DEFAULT_SERVER):
# self.xmlrpc = xmlrpclib.Server(server)
#
# def get_package_versions(self, package_name):
# """Fetch list of available versions for a package.
#
# :param package_name: Name of the package to query.
# """
# return self.xmlrpc.package_releases(package_name)
#
# def get_package_list(self):
# """Fetch the master list of package names."""
# return self.xmlrpc.list_packages()
#
# def search(self, spec, operator):
# """Query using search spec."""
# return self.xmlrpc.search(spec, operator.lower())
#
# def get_changelog(self, hours, force_seconds=False):
# """Query the changelog.
#
# :param hours: Hours from now to specify the changelog size.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.changelog(seconds)
#
# def get_updated_releases(self, hours, force_seconds):
# """Query all updated releases within `hours`.
#
# :param hours: Specify the number of hours to find updated releases.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.updated_releases(seconds)
#
# def get_release_urls(self, package_name, version):
# """Query for all available release urls of `package_name`.
#
# :param package_name: Name of the package.
# :param version: Version of the package.
# """
# return self.xmlrpc.release_urls(package_name, version)
#
# def get_release_data(self, package_name, version=None):
# """Query for specific release data.
#
# :param package_name: Name of the package.
# :param version: Version to query the data. If `None`, it's latest
# version will be used.
# """
# if version is None:
# versions = self.get_package_versions(package_name)
# if not versions:
# return {}
# version = versions[-1]
# return self.xmlrpc.release_data(package_name, version)
#
# def normalize_name(name):
# return pkg_resources.safe_name(name).lower()
. Output only the next line. | url = urlparse.urljoin(DEFAULT_SERVER, name) |
Based on the snippet: <|code_start|>
PROVIDES = ('pypi',)
class Package(models.Model):
PYPI = 'pypi'
PROVIDER_CHOICES = (
(PYPI, 'PyPi'),
)
name = models.CharField(_('name'), max_length=255, unique=True)
normalized_name = models.CharField(_('Normalized Name'), max_length=255,
unique=True)
url = models.URLField(_('url'))
provider = models.CharField(_('provider'), max_length=255,
choices=PROVIDER_CHOICES, default=PYPI)
initial_sync_done = models.BooleanField(default=False)
@classmethod
def create_with_provider_url(cls, name, provider='pypi', url=None):
if url is None:
url = urlparse.urljoin(DEFAULT_SERVER, name)
pkg = cls(name=name, url=url, provider=provider)
pkg.save()
return pkg
def sync_versions(self):
if self.initial_sync_done:
return
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import urlparse
import datetime
import pytz
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import make_aware, now
from django.contrib.auth.models import User
from django_orm.postgresql import hstore
from .utils.pypi import DEFAULT_SERVER, CheeseShop, normalize_name
from .tasks import sync_project
and context (classes, functions, sometimes code) from other files:
# Path: folivora/utils/pypi.py
# DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
#
# class CheeseShop(object):
#
# def __init__(self, server=DEFAULT_SERVER):
# self.xmlrpc = xmlrpclib.Server(server)
#
# def get_package_versions(self, package_name):
# """Fetch list of available versions for a package.
#
# :param package_name: Name of the package to query.
# """
# return self.xmlrpc.package_releases(package_name)
#
# def get_package_list(self):
# """Fetch the master list of package names."""
# return self.xmlrpc.list_packages()
#
# def search(self, spec, operator):
# """Query using search spec."""
# return self.xmlrpc.search(spec, operator.lower())
#
# def get_changelog(self, hours, force_seconds=False):
# """Query the changelog.
#
# :param hours: Hours from now to specify the changelog size.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.changelog(seconds)
#
# def get_updated_releases(self, hours, force_seconds):
# """Query all updated releases within `hours`.
#
# :param hours: Specify the number of hours to find updated releases.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.updated_releases(seconds)
#
# def get_release_urls(self, package_name, version):
# """Query for all available release urls of `package_name`.
#
# :param package_name: Name of the package.
# :param version: Version of the package.
# """
# return self.xmlrpc.release_urls(package_name, version)
#
# def get_release_data(self, package_name, version=None):
# """Query for specific release data.
#
# :param package_name: Name of the package.
# :param version: Version to query the data. If `None`, it's latest
# version will be used.
# """
# if version is None:
# versions = self.get_package_versions(package_name)
# if not versions:
# return {}
# version = versions[-1]
# return self.xmlrpc.release_data(package_name, version)
#
# def normalize_name(name):
# return pkg_resources.safe_name(name).lower()
. Output only the next line. | client = CheeseShop() |
Using the snippet: <|code_start|> @classmethod
def create_with_provider_url(cls, name, provider='pypi', url=None):
if url is None:
url = urlparse.urljoin(DEFAULT_SERVER, name)
pkg = cls(name=name, url=url, provider=provider)
pkg.save()
return pkg
def sync_versions(self):
if self.initial_sync_done:
return
client = CheeseShop()
versions = client.get_package_versions(self.name)
for version in versions:
urls = client.get_release_urls(self.name, version)
if urls:
url = urls[0]
utime = time.mktime(url['upload_time'].timetuple())
release_date = make_aware(
datetime.datetime.fromtimestamp(utime),
pytz.UTC)
PackageVersion.objects.get_or_create(
package=self,
version=version,
release_date=release_date)
self.initial_sync_done = True
self.save()
def save(self, *args, **kwargs):
if not self.normalized_name:
<|code_end|>
, determine the next line of code. You have imports:
import time
import urlparse
import datetime
import pytz
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import make_aware, now
from django.contrib.auth.models import User
from django_orm.postgresql import hstore
from .utils.pypi import DEFAULT_SERVER, CheeseShop, normalize_name
from .tasks import sync_project
and context (class names, function names, or code) available:
# Path: folivora/utils/pypi.py
# DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
#
# class CheeseShop(object):
#
# def __init__(self, server=DEFAULT_SERVER):
# self.xmlrpc = xmlrpclib.Server(server)
#
# def get_package_versions(self, package_name):
# """Fetch list of available versions for a package.
#
# :param package_name: Name of the package to query.
# """
# return self.xmlrpc.package_releases(package_name)
#
# def get_package_list(self):
# """Fetch the master list of package names."""
# return self.xmlrpc.list_packages()
#
# def search(self, spec, operator):
# """Query using search spec."""
# return self.xmlrpc.search(spec, operator.lower())
#
# def get_changelog(self, hours, force_seconds=False):
# """Query the changelog.
#
# :param hours: Hours from now to specify the changelog size.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.changelog(seconds)
#
# def get_updated_releases(self, hours, force_seconds):
# """Query all updated releases within `hours`.
#
# :param hours: Specify the number of hours to find updated releases.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.updated_releases(seconds)
#
# def get_release_urls(self, package_name, version):
# """Query for all available release urls of `package_name`.
#
# :param package_name: Name of the package.
# :param version: Version of the package.
# """
# return self.xmlrpc.release_urls(package_name, version)
#
# def get_release_data(self, package_name, version=None):
# """Query for specific release data.
#
# :param package_name: Name of the package.
# :param version: Version to query the data. If `None`, it's latest
# version will be used.
# """
# if version is None:
# versions = self.get_package_versions(package_name)
# if not versions:
# return {}
# version = versions[-1]
# return self.xmlrpc.release_data(package_name, version)
#
# def normalize_name(name):
# return pkg_resources.safe_name(name).lower()
. Output only the next line. | self.normalized_name = normalize_name(self.name) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
#-*- coding: utf-8 -*-
SERVER = CheeseShop(DEFAULT_SERVER)
def sync():
if ('delete_all' in sys.argv and
raw_input('sure (this resets everything)? [y/n]: ') == 'y'):
<|code_end|>
, predict the next line using imports from the current file:
import sys
import urlparse
import datetime
import logging
import time
import pytz
from django.utils import timezone
from folivora.models import Package, SyncState
from folivora.utils.pypi import CheeseShop, DEFAULT_SERVER
and context including class names, function names, and sometimes code from other files:
# Path: folivora/models.py
# class Package(models.Model):
# PYPI = 'pypi'
# PROVIDER_CHOICES = (
# (PYPI, 'PyPi'),
# )
#
# name = models.CharField(_('name'), max_length=255, unique=True)
# normalized_name = models.CharField(_('Normalized Name'), max_length=255,
# unique=True)
# url = models.URLField(_('url'))
# provider = models.CharField(_('provider'), max_length=255,
# choices=PROVIDER_CHOICES, default=PYPI)
# initial_sync_done = models.BooleanField(default=False)
#
# @classmethod
# def create_with_provider_url(cls, name, provider='pypi', url=None):
# if url is None:
# url = urlparse.urljoin(DEFAULT_SERVER, name)
# pkg = cls(name=name, url=url, provider=provider)
# pkg.save()
# return pkg
#
# def sync_versions(self):
# if self.initial_sync_done:
# return
# client = CheeseShop()
# versions = client.get_package_versions(self.name)
# for version in versions:
# urls = client.get_release_urls(self.name, version)
# if urls:
# url = urls[0]
# utime = time.mktime(url['upload_time'].timetuple())
# release_date = make_aware(
# datetime.datetime.fromtimestamp(utime),
# pytz.UTC)
# PackageVersion.objects.get_or_create(
# package=self,
# version=version,
# release_date=release_date)
# self.initial_sync_done = True
# self.save()
#
# def save(self, *args, **kwargs):
# if not self.normalized_name:
# self.normalized_name = normalize_name(self.name)
# super(Package, self).save(*args, **kwargs)
#
# class Meta:
# verbose_name = _('package')
# verbose_name_plural = _('packages')
# unique_together = ('name', 'provider')
#
# def __unicode__(self):
# return self.name
#
# def __repr__(self):
# return '<%s: %s>' % (self.__class__.__name__, self.name)
#
# class SyncState(models.Model):
# """Generic model to store syncronization states."""
# CHANGELOG = 'changelog'
#
# TYPE_CHOICES = (
# (_('Changelog'), CHANGELOG),
# )
#
# STATE_DOWN = 'down'
# STATE_RUNNING = 'running'
#
# STATE_CHOICES = (
# (_('Down'), STATE_DOWN),
# (_('Running'), STATE_RUNNING),
# )
#
# type = models.CharField(max_length=255, choices=TYPE_CHOICES, unique=True)
# state = models.CharField(max_length=255, choices=STATE_CHOICES,
# default=STATE_RUNNING)
# last_sync = models.DateTimeField(_('Last Sync'), default=now)
#
# Path: folivora/utils/pypi.py
# class CheeseShop(object):
#
# def __init__(self, server=DEFAULT_SERVER):
# self.xmlrpc = xmlrpclib.Server(server)
#
# def get_package_versions(self, package_name):
# """Fetch list of available versions for a package.
#
# :param package_name: Name of the package to query.
# """
# return self.xmlrpc.package_releases(package_name)
#
# def get_package_list(self):
# """Fetch the master list of package names."""
# return self.xmlrpc.list_packages()
#
# def search(self, spec, operator):
# """Query using search spec."""
# return self.xmlrpc.search(spec, operator.lower())
#
# def get_changelog(self, hours, force_seconds=False):
# """Query the changelog.
#
# :param hours: Hours from now to specify the changelog size.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.changelog(seconds)
#
# def get_updated_releases(self, hours, force_seconds):
# """Query all updated releases within `hours`.
#
# :param hours: Specify the number of hours to find updated releases.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.updated_releases(seconds)
#
# def get_release_urls(self, package_name, version):
# """Query for all available release urls of `package_name`.
#
# :param package_name: Name of the package.
# :param version: Version of the package.
# """
# return self.xmlrpc.release_urls(package_name, version)
#
# def get_release_data(self, package_name, version=None):
# """Query for specific release data.
#
# :param package_name: Name of the package.
# :param version: Version to query the data. If `None`, it's latest
# version will be used.
# """
# if version is None:
# versions = self.get_package_versions(package_name)
# if not versions:
# return {}
# version = versions[-1]
# return self.xmlrpc.release_data(package_name, version)
#
# DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
. Output only the next line. | Package.objects.all().delete() |
Here is a snippet: <|code_start|>#!/usr/bin/env python
#-*- coding: utf-8 -*-
SERVER = CheeseShop(DEFAULT_SERVER)
def sync():
if ('delete_all' in sys.argv and
raw_input('sure (this resets everything)? [y/n]: ') == 'y'):
Package.objects.all().delete()
<|code_end|>
. Write the next line using the current file imports:
import sys
import urlparse
import datetime
import logging
import time
import pytz
from django.utils import timezone
from folivora.models import Package, SyncState
from folivora.utils.pypi import CheeseShop, DEFAULT_SERVER
and context from other files:
# Path: folivora/models.py
# class Package(models.Model):
# PYPI = 'pypi'
# PROVIDER_CHOICES = (
# (PYPI, 'PyPi'),
# )
#
# name = models.CharField(_('name'), max_length=255, unique=True)
# normalized_name = models.CharField(_('Normalized Name'), max_length=255,
# unique=True)
# url = models.URLField(_('url'))
# provider = models.CharField(_('provider'), max_length=255,
# choices=PROVIDER_CHOICES, default=PYPI)
# initial_sync_done = models.BooleanField(default=False)
#
# @classmethod
# def create_with_provider_url(cls, name, provider='pypi', url=None):
# if url is None:
# url = urlparse.urljoin(DEFAULT_SERVER, name)
# pkg = cls(name=name, url=url, provider=provider)
# pkg.save()
# return pkg
#
# def sync_versions(self):
# if self.initial_sync_done:
# return
# client = CheeseShop()
# versions = client.get_package_versions(self.name)
# for version in versions:
# urls = client.get_release_urls(self.name, version)
# if urls:
# url = urls[0]
# utime = time.mktime(url['upload_time'].timetuple())
# release_date = make_aware(
# datetime.datetime.fromtimestamp(utime),
# pytz.UTC)
# PackageVersion.objects.get_or_create(
# package=self,
# version=version,
# release_date=release_date)
# self.initial_sync_done = True
# self.save()
#
# def save(self, *args, **kwargs):
# if not self.normalized_name:
# self.normalized_name = normalize_name(self.name)
# super(Package, self).save(*args, **kwargs)
#
# class Meta:
# verbose_name = _('package')
# verbose_name_plural = _('packages')
# unique_together = ('name', 'provider')
#
# def __unicode__(self):
# return self.name
#
# def __repr__(self):
# return '<%s: %s>' % (self.__class__.__name__, self.name)
#
# class SyncState(models.Model):
# """Generic model to store syncronization states."""
# CHANGELOG = 'changelog'
#
# TYPE_CHOICES = (
# (_('Changelog'), CHANGELOG),
# )
#
# STATE_DOWN = 'down'
# STATE_RUNNING = 'running'
#
# STATE_CHOICES = (
# (_('Down'), STATE_DOWN),
# (_('Running'), STATE_RUNNING),
# )
#
# type = models.CharField(max_length=255, choices=TYPE_CHOICES, unique=True)
# state = models.CharField(max_length=255, choices=STATE_CHOICES,
# default=STATE_RUNNING)
# last_sync = models.DateTimeField(_('Last Sync'), default=now)
#
# Path: folivora/utils/pypi.py
# class CheeseShop(object):
#
# def __init__(self, server=DEFAULT_SERVER):
# self.xmlrpc = xmlrpclib.Server(server)
#
# def get_package_versions(self, package_name):
# """Fetch list of available versions for a package.
#
# :param package_name: Name of the package to query.
# """
# return self.xmlrpc.package_releases(package_name)
#
# def get_package_list(self):
# """Fetch the master list of package names."""
# return self.xmlrpc.list_packages()
#
# def search(self, spec, operator):
# """Query using search spec."""
# return self.xmlrpc.search(spec, operator.lower())
#
# def get_changelog(self, hours, force_seconds=False):
# """Query the changelog.
#
# :param hours: Hours from now to specify the changelog size.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.changelog(seconds)
#
# def get_updated_releases(self, hours, force_seconds):
# """Query all updated releases within `hours`.
#
# :param hours: Specify the number of hours to find updated releases.
# :param force_seconds: Force that `hours` are the seconds to use.
# """
# seconds = get_seconds(hours) if not force_seconds else hours
# return self.xmlrpc.updated_releases(seconds)
#
# def get_release_urls(self, package_name, version):
# """Query for all available release urls of `package_name`.
#
# :param package_name: Name of the package.
# :param version: Version of the package.
# """
# return self.xmlrpc.release_urls(package_name, version)
#
# def get_release_data(self, package_name, version=None):
# """Query for specific release data.
#
# :param package_name: Name of the package.
# :param version: Version to query the data. If `None`, it's latest
# version will be used.
# """
# if version is None:
# versions = self.get_package_versions(package_name)
# if not versions:
# return {}
# version = versions[-1]
# return self.xmlrpc.release_data(package_name, version)
#
# DEFAULT_SERVER = 'http://pypi.python.org/pypi/'
, which may include functions, classes, or code. Output only the next line. | SyncState.objects.all().delete() |
Here is a snippet: <|code_start|> if sort and sort.strip('-') in self.sort_fields:
self.sort_field = sort
qs = qs.order_by(sort)
else:
qs = qs.order_by(*self.default_order)
self.sort_field = self.default_order[0]
self.sort_order = 'desc' if self.sort_field[0] == '-' else 'asc'
self.sort_field = self.sort_field.strip('-')
return qs
class ProjectMixin(object):
"""Mixin which checks if the user has access to the project in question.
It is written for this project and won't work anywhere else ;)
Access is granted by checking if the user is a member of a project, the
project is taken from the slug in the URL.
Additionally it checks if the user is authenticated.
Set allow_only_owner True, to grant access only to owners
Also polulates self.project and context['project']
"""
allow_only_owner = False
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
slug = kwargs['slug']
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from ..models import Project, ProjectMember
and context from other files:
# Path: folivora/models.py
# class Project(models.Model):
# name = models.CharField(_('name'), max_length=255)
# slug = models.SlugField(_('slug'), unique=True)
# members = models.ManyToManyField(User, through=ProjectMember,
# verbose_name=_('members'))
#
# class Meta:
# verbose_name = _('project')
# verbose_name_plural = _('projects')
#
# @models.permalink
# def get_absolute_url(self):
# return 'folivora_project_detail', (), {'slug': self.slug}
#
# def create_logentry(self, type, action, user=None, **kwargs):
# Log.objects.create(project=self, type=type,
# action=action, data=kwargs, user=user)
#
# @property
# def requirements(self):
# query = ProjectDependency.objects.filter(project=self) \
# .select_related('package') \
# .order_by('package__name')
# return "\n".join([d.dependency_string for d in query])
#
# @property
# def requirement_dict(self):
# query = ProjectDependency.objects.filter(project=self) \
# .select_related('package')
# return dict((d.package.name, d.version) for d in query)
#
# def process_changes(self, user, remove=None, change=None, add=None):
# log_entries = []
#
# remove = remove if remove else []
# change = change if change else []
# add = add if add else []
#
# for package_id, version in add:
# log_entries.append(Log(type='project_dependency', action='add',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': version}))
# for package_id, version in remove:
# log_entries.append(Log(type='project_dependency', action='remove',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': version}))
# for package_id, old_version, new_version in change:
# log_entries.append(Log(type='project_dependency', action='update',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': new_version,
# 'old_version': old_version}))
#
# Log.objects.bulk_create(log_entries)
# from .tasks import sync_project
# # give the request time to finish before syncing
# sync_project.apply_async(args=[self.pk], countdown=1)
#
# @property
# def owners(self):
# return self.members.filter(projectmember__state=ProjectMember.OWNER)
#
# class ProjectMember(models.Model):
# OWNER = 0
# MEMBER = 1
# STATE_CHOICES = (
# (OWNER, _('Owner')),
# (MEMBER, _('Member'))
# )
#
# project = models.ForeignKey('Project', verbose_name=_('project'))
# user = models.ForeignKey(User, verbose_name=_('user'))
# state = models.IntegerField(_('state'), choices=STATE_CHOICES)
# mail = models.EmailField(_('Email'), max_length=255, blank=True)
# jabber = models.CharField(_('Jabber'), max_length=255, blank=True)
#
# class Meta:
# verbose_name = _('project member')
# verbose_name_plural = _('project members')
# unique_together = ('project', 'user')
, which may include functions, classes, or code. Output only the next line. | self.project = Project.objects.get(slug=slug) |
Predict the next line after this snippet: <|code_start|> self.sort_field = sort
qs = qs.order_by(sort)
else:
qs = qs.order_by(*self.default_order)
self.sort_field = self.default_order[0]
self.sort_order = 'desc' if self.sort_field[0] == '-' else 'asc'
self.sort_field = self.sort_field.strip('-')
return qs
class ProjectMixin(object):
"""Mixin which checks if the user has access to the project in question.
It is written for this project and won't work anywhere else ;)
Access is granted by checking if the user is a member of a project, the
project is taken from the slug in the URL.
Additionally it checks if the user is authenticated.
Set allow_only_owner True, to grant access only to owners
Also polulates self.project and context['project']
"""
allow_only_owner = False
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
slug = kwargs['slug']
self.project = Project.objects.get(slug=slug)
<|code_end|>
using the current file's imports:
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from ..models import Project, ProjectMember
and any relevant context from other files:
# Path: folivora/models.py
# class Project(models.Model):
# name = models.CharField(_('name'), max_length=255)
# slug = models.SlugField(_('slug'), unique=True)
# members = models.ManyToManyField(User, through=ProjectMember,
# verbose_name=_('members'))
#
# class Meta:
# verbose_name = _('project')
# verbose_name_plural = _('projects')
#
# @models.permalink
# def get_absolute_url(self):
# return 'folivora_project_detail', (), {'slug': self.slug}
#
# def create_logentry(self, type, action, user=None, **kwargs):
# Log.objects.create(project=self, type=type,
# action=action, data=kwargs, user=user)
#
# @property
# def requirements(self):
# query = ProjectDependency.objects.filter(project=self) \
# .select_related('package') \
# .order_by('package__name')
# return "\n".join([d.dependency_string for d in query])
#
# @property
# def requirement_dict(self):
# query = ProjectDependency.objects.filter(project=self) \
# .select_related('package')
# return dict((d.package.name, d.version) for d in query)
#
# def process_changes(self, user, remove=None, change=None, add=None):
# log_entries = []
#
# remove = remove if remove else []
# change = change if change else []
# add = add if add else []
#
# for package_id, version in add:
# log_entries.append(Log(type='project_dependency', action='add',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': version}))
# for package_id, version in remove:
# log_entries.append(Log(type='project_dependency', action='remove',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': version}))
# for package_id, old_version, new_version in change:
# log_entries.append(Log(type='project_dependency', action='update',
# project_id=self.pk, package_id=package_id,
# user=user, data={'version': new_version,
# 'old_version': old_version}))
#
# Log.objects.bulk_create(log_entries)
# from .tasks import sync_project
# # give the request time to finish before syncing
# sync_project.apply_async(args=[self.pk], countdown=1)
#
# @property
# def owners(self):
# return self.members.filter(projectmember__state=ProjectMember.OWNER)
#
# class ProjectMember(models.Model):
# OWNER = 0
# MEMBER = 1
# STATE_CHOICES = (
# (OWNER, _('Owner')),
# (MEMBER, _('Member'))
# )
#
# project = models.ForeignKey('Project', verbose_name=_('project'))
# user = models.ForeignKey(User, verbose_name=_('user'))
# state = models.IntegerField(_('state'), choices=STATE_CHOICES)
# mail = models.EmailField(_('Email'), max_length=255, blank=True)
# jabber = models.CharField(_('Jabber'), max_length=255, blank=True)
#
# class Meta:
# verbose_name = _('project member')
# verbose_name_plural = _('project members')
# unique_together = ('project', 'user')
. Output only the next line. | query = ProjectMember.objects.filter( |
Based on the snippet: <|code_start|> """
def __new__(cls, name, bases, attrs):
if BaseModelForm not in bases and 'Meta' in attrs:
meta = attrs['Meta']
model = meta.model
widgets = getattr(meta, 'widgets', None)
if not widgets:
widgets = meta.widgets = {}
for field in model._meta.fields:
if isinstance(field, models.AutoField):
continue
if field.choices:
widgets[field.name] = widget_map[models.ForeignKey]
elif type(field) in widget_map and field.name not in widgets:
widgets[field.name] = widget_map[type(field)]
return super(FloppyFormsModelMetaclass, cls).__new__(cls, name,
bases, attrs)
class ModelForm(forms.LayoutRenderer, BaseModelForm):
"""Model form which does incorporate floppyforms layout renderer"""
__metaclass__ = FloppyFormsModelMetaclass
class JabberField(fields.CharField):
def clean(self, value):
value = value.strip()
if not value and not self.required:
return value
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from django.utils.translation import ugettext as _
from django.forms import ValidationError, fields
from django.forms.models import ModelFormMetaclass, ModelForm as BaseModelForm
from floppyforms import widgets, forms
from .jabber import is_valid_jid
and context (classes, functions, sometimes code) from other files:
# Path: folivora/utils/jabber.py
# def is_valid_jid(jabber):
# return _jabber_re.match(jabber) is not None
. Output only the next line. | if not is_valid_jid(value): |
Predict the next line for this snippet: <|code_start|>
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
<|code_end|>
with the help of current file imports:
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in
from .models import UserProfile
and context from other files:
# Path: folivora/models.py
# class UserProfile(models.Model):
# user = models.OneToOneField(User)
# language = models.CharField(_('Language'), max_length=255,
# choices=settings.LANGUAGES, blank=True)
# timezone = models.CharField(_('Timezone'), max_length=255, default='UTC')
# jabber = models.CharField(_('JID'), max_length=255, blank=True)
#
# def get_absolute_url(self):
# return reverse('folivora_profile_edit')
, which may contain function names, class names, or code. Output only the next line. | UserProfile.objects.create(user=instance) |
Predict the next line for this snippet: <|code_start|>
def get(github_id):
return User.query.filter_by(github_id=github_id).first()
def get_by_username(username):
return User.query.filter_by(username=username).first()
def create(data):
pw = generate_password_hash(str(random()))
<|code_end|>
with the help of current file imports:
from config import site
from random import random
from app.models.user import User
from werkzeug.security import generate_password_hash
and context from other files:
# Path: config/site.py
#
# Path: app/models/user.py
# class User(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# type = db.Column(db.String(32), nullable=False, default='User')
# username = db.Column(db.String(80), unique=True)
# email = db.Column(db.String(120), unique=True)
# name = db.Column(db.String(80))
# bio = db.Column(db.String(180))
# points = db.Column(db.Integer, default=0)
# site_admin = db.Column(db.Boolean, default=False)
# avatar_url = db.Column(db.String(256))
# owner = db.Column(db.String(32), nullable=False, default='user')
# github_id = db.Column(db.Integer, unique=True)
# github_username = db.Column(db.String(64), unique=True)
# github_token = db.Column(db.String(300), unique=True)
# password = db.Column(db.String(300))
# location = db.Column(db.String(255))
# followers_count = db.Column(db.Integer, default=0)
# public_repos_count = db.Column(db.Integer, default=0)
# created_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_active_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_login_reward_at = db.Column(db.DateTime, default=datetime.utcnow)
# following_topics = db.relationship('Topic', secondary=topics,
# backref=db.backref('user', lazy='dynamic'))
#
# def __init__(self, username, email, password, name=None):
# self.email = email
# self.username = username
# self.password = password
# if name is None:
# self.name = username
# else:
# self.name = name
#
# is_authenticated = True
# is_anonymous = False
# is_active = True
#
# def get_id(self):
# return unicode(self.id)
#
# def __repr__(self):
# return '<User %r>' % self.username
, which may contain function names, class names, or code. Output only the next line. | email = 'github_%s@%s' % (data['login'], site.config['domain']) |
Next line prediction: <|code_start|>
def autoheader(content):
lines = content.split('\n')
if len(lines) > 1:
header = lines[0].strip()
if len(header) < 78 and ',.!?~+-'.find(header[-1]) < 0:
lines[0] = '<div class="header">{}</div>'.format(header)
return '\n'.join(lines)
return content
def init_app(app):
app.add_template_filter(autoheader, 'autoheader')
<|code_end|>
. Use current file imports:
(from lib import highlight, markdown)
and context including class names, function names, or small code snippets from other files:
# Path: lib/highlight.py
# def render(code, lang, linenostart):
#
# Path: lib/markdown.py
# class Renderer(misaka.HtmlRenderer):
# def block_code(self, text, lang):
. Output only the next line. | app.add_template_filter(highlight.render, 'highlight') |
Predict the next line after this snippet: <|code_start|>
def autoheader(content):
lines = content.split('\n')
if len(lines) > 1:
header = lines[0].strip()
if len(header) < 78 and ',.!?~+-'.find(header[-1]) < 0:
lines[0] = '<div class="header">{}</div>'.format(header)
return '\n'.join(lines)
return content
def init_app(app):
app.add_template_filter(autoheader, 'autoheader')
app.add_template_filter(highlight.render, 'highlight')
<|code_end|>
using the current file's imports:
from lib import highlight, markdown
and any relevant context from other files:
# Path: lib/highlight.py
# def render(code, lang, linenostart):
#
# Path: lib/markdown.py
# class Renderer(misaka.HtmlRenderer):
# def block_code(self, text, lang):
. Output only the next line. | app.add_template_filter(markdown.render, 'markdown') |
Given snippet: <|code_start|>
def auth_required(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth:
return abort(401)
login = auth.username
if login[1:-1].find('@') >= 0:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import wraps
from flask import request
from flask_restful import abort
from app.models.user import User
from werkzeug.security import check_password_hash
and context:
# Path: app/models/user.py
# class User(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# type = db.Column(db.String(32), nullable=False, default='User')
# username = db.Column(db.String(80), unique=True)
# email = db.Column(db.String(120), unique=True)
# name = db.Column(db.String(80))
# bio = db.Column(db.String(180))
# points = db.Column(db.Integer, default=0)
# site_admin = db.Column(db.Boolean, default=False)
# avatar_url = db.Column(db.String(256))
# owner = db.Column(db.String(32), nullable=False, default='user')
# github_id = db.Column(db.Integer, unique=True)
# github_username = db.Column(db.String(64), unique=True)
# github_token = db.Column(db.String(300), unique=True)
# password = db.Column(db.String(300))
# location = db.Column(db.String(255))
# followers_count = db.Column(db.Integer, default=0)
# public_repos_count = db.Column(db.Integer, default=0)
# created_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_active_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_login_reward_at = db.Column(db.DateTime, default=datetime.utcnow)
# following_topics = db.relationship('Topic', secondary=topics,
# backref=db.backref('user', lazy='dynamic'))
#
# def __init__(self, username, email, password, name=None):
# self.email = email
# self.username = username
# self.password = password
# if name is None:
# self.name = username
# else:
# self.name = name
#
# is_authenticated = True
# is_anonymous = False
# is_active = True
#
# def get_id(self):
# return unicode(self.id)
#
# def __repr__(self):
# return '<User %r>' % self.username
which might include code, classes, or functions. Output only the next line. | user = User.query.filter_by(email=login).first() |
Predict the next line after this snippet: <|code_start|>
def get(username, name):
user = User.query.filter_by(username=username).first()
if user is None:
return None
<|code_end|>
using the current file's imports:
from app.models.user import User
from app.models.repository import Repository
and any relevant context from other files:
# Path: app/models/user.py
# class User(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# type = db.Column(db.String(32), nullable=False, default='User')
# username = db.Column(db.String(80), unique=True)
# email = db.Column(db.String(120), unique=True)
# name = db.Column(db.String(80))
# bio = db.Column(db.String(180))
# points = db.Column(db.Integer, default=0)
# site_admin = db.Column(db.Boolean, default=False)
# avatar_url = db.Column(db.String(256))
# owner = db.Column(db.String(32), nullable=False, default='user')
# github_id = db.Column(db.Integer, unique=True)
# github_username = db.Column(db.String(64), unique=True)
# github_token = db.Column(db.String(300), unique=True)
# password = db.Column(db.String(300))
# location = db.Column(db.String(255))
# followers_count = db.Column(db.Integer, default=0)
# public_repos_count = db.Column(db.Integer, default=0)
# created_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_active_at = db.Column(db.DateTime, default=datetime.utcnow)
# last_login_reward_at = db.Column(db.DateTime, default=datetime.utcnow)
# following_topics = db.relationship('Topic', secondary=topics,
# backref=db.backref('user', lazy='dynamic'))
#
# def __init__(self, username, email, password, name=None):
# self.email = email
# self.username = username
# self.password = password
# if name is None:
# self.name = username
# else:
# self.name = name
#
# is_authenticated = True
# is_anonymous = False
# is_active = True
#
# def get_id(self):
# return unicode(self.id)
#
# def __repr__(self):
# return '<User %r>' % self.username
#
# Path: app/models/repository.py
# class Repository(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# origin_id = db.Column(db.Integer, nullable=False)
# name = db.Column(db.String(128), nullable=False)
# description = db.Column(db.String(1024))
# logo_url = db.Column(db.String(256))
# html_url = db.Column(db.String(256))
# homepage = db.Column(db.String(256))
# language = db.Column(db.String(32))
# last_snippet_number = db.Column(db.Integer, nullable=False, default=0)
# pushed_at = db.Column(db.DateTime)
# created_at = db.Column(db.DateTime)
# updated_at = db.Column(db.DateTime)
# imported_at = db.Column(db.DateTime, default=datetime.utcnow)
# imported_from = db.Column(db.String(16))
# owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
# owner = db.relationship('User', uselist=False)
# topics = db.relationship('Topic', secondary=topics,
# backref=db.backref('repository', lazy='dynamic'))
#
# def __init__(self, owner, data):
# self.name = data['name']
# self.origin_id = data['id']
# self.homepage = data['homepage']
# self.language = data['language']
# self.html_url = data['html_url']
# self.description = data['description']
# self.created_at = datetime_from_utc(data['created_at'])
# self.updated_at = datetime_from_utc(data['updated_at'])
# self.pushed_at = datetime_from_utc(data['pushed_at'])
# self.owner_id = owner.id
# self.owner = owner
# language = data['language']
# has_language_topic = False
# for name in data['topics']:
# topic = Topic.query.filter_by(name=name).first()
# if topic is None:
# topic = Topic(name)
# if language and name == language:
# topic.group = 'language'
# has_language_topic = True
# topic.repositories_count = 1
# self.topics.append(topic)
# if language and not has_language_topic:
# topic = Topic.query.filter_by(name=language).first()
# if topic is None:
# topic = Topic(language, 'language')
# topic.repositories_count = 1
# self.topics.append(topic)
#
# def __repr__(self):
# return '<Repository %r>' % self.name
. Output only the next line. | repo = Repository.query.filter_by(owner_id=user.id, name=name).first() |
Given the code snippet: <|code_start|>
class FileInline(admin.StackedInline):
model = File
extra = 1
class CommandAdmin(admin.ModelAdmin):
inlines = [
FileInline,
]
# Register your models here.
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from .models import Bot, Command, File
and context (functions, classes, or occasionally code) from other files:
# Path: aura-server/convey/models.py
# class Bot(models.Model):
# version = models.CharField(max_length=15, null=True, blank=True)
# hash_type = models.CharField(max_length=15)
# hash_sum = models.CharField(max_length=200)
# group = models.IntegerField(default=0)
# operating_sys = models.CharField(max_length=50)
# user = models.CharField(max_length=20)
# ip_addr = models.CharField(max_length=16)
# last_contact = models.DateTimeField(default=timezone.now)
# completed_cmds = models.ManyToManyField(
# Command,
# through='Bot_Command',
# )
#
# def __str__(self):
# return '{}@{}({})'.format(self.user, self.hash_sum[:6], self.operating_sys)
#
# def is_active(self):
# now = timezone.now()
# return self.last_contact >= now - datetime.timedelta(days=20)
#
# class Command(models.Model):
# SHELL_CHOICES = (
# ('default','Default'),
# ('bash','Bash'),
# ('powershell','PowerShell'),
# )
# shell = models.CharField(
# max_length=30,
# blank=False,
# choices=SHELL_CHOICES,
# default="default"
# )
# cmd_txt = models.TextField(default='')
# start_time = models.DateTimeField('start_time', default=timezone.now)
# end_time = models.DateTimeField('end_time', default=timezone.now)
# group_assigned = models.IntegerField(default=-2, null=True, blank=True)
# hash_assigned = models.CharField(max_length=200, null=True, blank=True)
# oneshot = models.BooleanField(default=True)
#
# def __str__(self):
# if self.group_assigned == -1:
# return "All: {}".format(self.cmd_txt)
# if self.group_assigned == -2:
# return "Default: {}".format(self.cmd_txt)
# return "Group {}: {}".format(self.group_assigned, self.cmd_txt)
#
# class File(models.Model):
# command = models.ForeignKey(Command, on_delete=models.CASCADE)
# name = models.CharField(max_length=256)
# file_type = models.CharField(
# max_length=25,
# choices=(
# ('local', 'Local'),
# ('network', 'Network'),
# )
# )
# path = models.CharField(max_length=1000)
#
# def __str__(self):
# return "{}: {}".format(self.file_type.title(), self.name)
. Output only the next line. | admin.site.register(Bot) |
Given the following code snippet before the placeholder: <|code_start|>
class FileInline(admin.StackedInline):
model = File
extra = 1
class CommandAdmin(admin.ModelAdmin):
inlines = [
FileInline,
]
# Register your models here.
admin.site.register(Bot)
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from .models import Bot, Command, File
and context including class names, function names, and sometimes code from other files:
# Path: aura-server/convey/models.py
# class Bot(models.Model):
# version = models.CharField(max_length=15, null=True, blank=True)
# hash_type = models.CharField(max_length=15)
# hash_sum = models.CharField(max_length=200)
# group = models.IntegerField(default=0)
# operating_sys = models.CharField(max_length=50)
# user = models.CharField(max_length=20)
# ip_addr = models.CharField(max_length=16)
# last_contact = models.DateTimeField(default=timezone.now)
# completed_cmds = models.ManyToManyField(
# Command,
# through='Bot_Command',
# )
#
# def __str__(self):
# return '{}@{}({})'.format(self.user, self.hash_sum[:6], self.operating_sys)
#
# def is_active(self):
# now = timezone.now()
# return self.last_contact >= now - datetime.timedelta(days=20)
#
# class Command(models.Model):
# SHELL_CHOICES = (
# ('default','Default'),
# ('bash','Bash'),
# ('powershell','PowerShell'),
# )
# shell = models.CharField(
# max_length=30,
# blank=False,
# choices=SHELL_CHOICES,
# default="default"
# )
# cmd_txt = models.TextField(default='')
# start_time = models.DateTimeField('start_time', default=timezone.now)
# end_time = models.DateTimeField('end_time', default=timezone.now)
# group_assigned = models.IntegerField(default=-2, null=True, blank=True)
# hash_assigned = models.CharField(max_length=200, null=True, blank=True)
# oneshot = models.BooleanField(default=True)
#
# def __str__(self):
# if self.group_assigned == -1:
# return "All: {}".format(self.cmd_txt)
# if self.group_assigned == -2:
# return "Default: {}".format(self.cmd_txt)
# return "Group {}: {}".format(self.group_assigned, self.cmd_txt)
#
# class File(models.Model):
# command = models.ForeignKey(Command, on_delete=models.CASCADE)
# name = models.CharField(max_length=256)
# file_type = models.CharField(
# max_length=25,
# choices=(
# ('local', 'Local'),
# ('network', 'Network'),
# )
# )
# path = models.CharField(max_length=1000)
#
# def __str__(self):
# return "{}: {}".format(self.file_type.title(), self.name)
. Output only the next line. | admin.site.register(Command, CommandAdmin) |
Given snippet: <|code_start|> def __unicode__(self):
"""
Convert the element into an XML unicode string.
"""
result = '<%s' % self.tagname
if self.xmlns:
result += ' xmlns="%s"' % self.xmlns
for key, value in self._attr.items():
if value is None:
continue
value = py3_str(value)
result += ' %s=%s' % (key, xml.sax.saxutils.quoteattr(value))
if not self._children and not self._content:
return result + '/>'
result += '>'
for child in self._children:
if not isinstance(child, Element):
child = child.__xml__()
result += py3_str(child)
return result + xml.sax.saxutils.escape(self._content.strip()) + '</%s>' % self.tagname
def __str__(self):
"""
Convert the element into an XML string using the current
string encoding.
"""
if sys.hexversion >= 0x03000000:
return self.__unicode__()
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import codecs
import xml.sax
import xml.sax.saxutils
from io import StringIO
from StringIO import StringIO
from .strutils import py3_b, py3_str
and context:
# Path: src/strutils.py
# def py3_b(value, encoding=None, desperate=True, coerce=False, fs=False):
# """
# Convert (if necessary) the given value to a "string of bytes", agnostic to
# any character encoding.
#
# :param value: the value to be converted to a string of bytes
# :param encoding: the character set to first try to encode to; if None, will
# use the system default (from the locale).
# :type encoding: str
# :param desperate: if True and encoding to the given (or default) charset
# fails, will also try utf-8 and latin-1 (in that order),
# and if those fail, will encode to the preferred charset,
# replacing unknown characters with \\\\uFFFD.
# :type desperate: bool
# :param coerce: if True, will coerce numeric types to a bytes object; if
# False, such values will be returned untouched.
# :type coerce: bool
# :param fs: indicates value is a file name or other environment string; if True,
# the encoding (if not explicitly specified) will be the encoding
# given by ``sys.getfilesystemencoding()`` and the error handler
# used will be ``surrogateescape`` if supported.
# :type fs: bool
# :returns: the value as a string of bytes, or the original value if coerce is
# False and the value was not a bytes or string.
#
# .. note:: The notion of "bytes" was introduced in Python 3 (and included
# in Python 2.6 as an alias to str), hence the ``py3_`` prefix. On Python
# 2, the returned value is a *str* object while on Python 3, the returned
# value is a *bytes* object.
# """
# if isinstance(value, BYTES_TYPE):
# # Nothing to do.
# return value
# elif isinstance(value, (int, long, float)):
# return bl(str(value)) if coerce else value
# elif not isinstance(value, UNICODE_TYPE):
# # Need to coerce to a unicode before converting to bytes. We can't just
# # feed it to bytes() in case the default character set can't encode it.
# value = py3_str(value, coerce=coerce)
#
# errors = 'strict'
# if fs:
# if not encoding:
# encoding = sys.getfilesystemencoding()
# errors = FS_ERRORS
#
# for c in (encoding or ENCODING, 'utf-8', 'latin-1'):
# try:
# return value.encode(c, errors)
# except UnicodeError:
# pass
# if not desperate:
# raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)")
#
# return value.encode(encoding or ENCODING, 'replace')
#
# def py3_str(value, encoding=None, desperate=True, coerce=False, fs=False):
# """
# Convert (if necessary) the given value to a (unicode) string.
#
# :param value: the value to be converted to a unicode string
# :param encoding: the character set to first try to decode as; if None, will
# use the system default (from the locale).
# :type encoding: str
# :param desperate: if True and decoding to the given (or default) charset
# fails, will also try utf-8 and latin-1 (in that order),
# and if those fail, will decode as the preferred charset,
# replacing unknown characters with \\\\uFFFD.
# :type desperate: bool
# :param coerce: if True, will coerce numeric types to a unicode string; if
# False, such values will be returned untouched.
# :type coerce: bool
# :param fs: indicates value is a file name or other environment string; if True,
# the encoding (if not explicitly specified) will be the encoding
# given by ``sys.getfilesystemencoding()`` and the error handler
# used will be ``surrogateescape`` if supported.
# :type fs: bool
# :returns: the value as a (unicode) string, or the original value if coerce is
# False and the value was not a bytes or string.
#
# .. note:: The naming of ``str`` is relative Python 3's notion of a *str* object,
# hence the ``py3_`` prefix. On Python 2, the returned value is a *unicode*
# object while on Python 3, the returned value is a *str* object.
# """
# if isinstance(value, UNICODE_TYPE):
# # Nothing to do.
# return value
# elif isinstance(value, (int, long, float)):
# return UNICODE_TYPE(value) if coerce else value
# elif not isinstance(value, BYTES_TYPE):
# # Need to coerce this value. Try the direct approach.
# try:
# return UNICODE_TYPE(value)
# except UnicodeError:
# # Could be that value.__repr__ returned a non-unicode and
# # non-8bit-clean string. Be a bit more brute force about it.
# return py3_str(repr(value), desperate=desperate)
#
# errors = 'strict'
# if fs:
# if not encoding:
# encoding = sys.getfilesystemencoding()
# errors = FS_ERRORS
#
# # We now have a bytes object to decode.
# for c in (encoding or ENCODING, 'utf-8', 'latin-1'):
# try:
# return value.decode(c, errors)
# except UnicodeError:
# pass
# if not desperate:
# raise UnicodeError("Couldn't decode value to unicode (and not desperate enough to keep trying)")
#
# return value.decode(encoding or ENCODING, 'replace')
which might include code, classes, or functions. Output only the next line. | return py3_b(self.__unicode__()) |
Based on the snippet: <|code_start|> result = self._attr.get(attr)
if result is not None:
return result
result = self.get_child(attr)
if result is not None:
return result
if '_' in attr:
return getattr(self, attr.replace('_', '-'))
def __cmp__(self, other):
if isinstance(other, (str, unicode)):
return cmp(self.tagname, other)
return object.__cmp__(self, other)
def __repr__(self):
"""
Python representation string
"""
return '<Element %s>' % self.tagname
def __unicode__(self):
"""
Convert the element into an XML unicode string.
"""
result = '<%s' % self.tagname
if self.xmlns:
result += ' xmlns="%s"' % self.xmlns
for key, value in self._attr.items():
if value is None:
continue
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import os
import codecs
import xml.sax
import xml.sax.saxutils
from io import StringIO
from StringIO import StringIO
from .strutils import py3_b, py3_str
and context (classes, functions, sometimes code) from other files:
# Path: src/strutils.py
# def py3_b(value, encoding=None, desperate=True, coerce=False, fs=False):
# """
# Convert (if necessary) the given value to a "string of bytes", agnostic to
# any character encoding.
#
# :param value: the value to be converted to a string of bytes
# :param encoding: the character set to first try to encode to; if None, will
# use the system default (from the locale).
# :type encoding: str
# :param desperate: if True and encoding to the given (or default) charset
# fails, will also try utf-8 and latin-1 (in that order),
# and if those fail, will encode to the preferred charset,
# replacing unknown characters with \\\\uFFFD.
# :type desperate: bool
# :param coerce: if True, will coerce numeric types to a bytes object; if
# False, such values will be returned untouched.
# :type coerce: bool
# :param fs: indicates value is a file name or other environment string; if True,
# the encoding (if not explicitly specified) will be the encoding
# given by ``sys.getfilesystemencoding()`` and the error handler
# used will be ``surrogateescape`` if supported.
# :type fs: bool
# :returns: the value as a string of bytes, or the original value if coerce is
# False and the value was not a bytes or string.
#
# .. note:: The notion of "bytes" was introduced in Python 3 (and included
# in Python 2.6 as an alias to str), hence the ``py3_`` prefix. On Python
# 2, the returned value is a *str* object while on Python 3, the returned
# value is a *bytes* object.
# """
# if isinstance(value, BYTES_TYPE):
# # Nothing to do.
# return value
# elif isinstance(value, (int, long, float)):
# return bl(str(value)) if coerce else value
# elif not isinstance(value, UNICODE_TYPE):
# # Need to coerce to a unicode before converting to bytes. We can't just
# # feed it to bytes() in case the default character set can't encode it.
# value = py3_str(value, coerce=coerce)
#
# errors = 'strict'
# if fs:
# if not encoding:
# encoding = sys.getfilesystemencoding()
# errors = FS_ERRORS
#
# for c in (encoding or ENCODING, 'utf-8', 'latin-1'):
# try:
# return value.encode(c, errors)
# except UnicodeError:
# pass
# if not desperate:
# raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)")
#
# return value.encode(encoding or ENCODING, 'replace')
#
# def py3_str(value, encoding=None, desperate=True, coerce=False, fs=False):
# """
# Convert (if necessary) the given value to a (unicode) string.
#
# :param value: the value to be converted to a unicode string
# :param encoding: the character set to first try to decode as; if None, will
# use the system default (from the locale).
# :type encoding: str
# :param desperate: if True and decoding to the given (or default) charset
# fails, will also try utf-8 and latin-1 (in that order),
# and if those fail, will decode as the preferred charset,
# replacing unknown characters with \\\\uFFFD.
# :type desperate: bool
# :param coerce: if True, will coerce numeric types to a unicode string; if
# False, such values will be returned untouched.
# :type coerce: bool
# :param fs: indicates value is a file name or other environment string; if True,
# the encoding (if not explicitly specified) will be the encoding
# given by ``sys.getfilesystemencoding()`` and the error handler
# used will be ``surrogateescape`` if supported.
# :type fs: bool
# :returns: the value as a (unicode) string, or the original value if coerce is
# False and the value was not a bytes or string.
#
# .. note:: The naming of ``str`` is relative Python 3's notion of a *str* object,
# hence the ``py3_`` prefix. On Python 2, the returned value is a *unicode*
# object while on Python 3, the returned value is a *str* object.
# """
# if isinstance(value, UNICODE_TYPE):
# # Nothing to do.
# return value
# elif isinstance(value, (int, long, float)):
# return UNICODE_TYPE(value) if coerce else value
# elif not isinstance(value, BYTES_TYPE):
# # Need to coerce this value. Try the direct approach.
# try:
# return UNICODE_TYPE(value)
# except UnicodeError:
# # Could be that value.__repr__ returned a non-unicode and
# # non-8bit-clean string. Be a bit more brute force about it.
# return py3_str(repr(value), desperate=desperate)
#
# errors = 'strict'
# if fs:
# if not encoding:
# encoding = sys.getfilesystemencoding()
# errors = FS_ERRORS
#
# # We now have a bytes object to decode.
# for c in (encoding or ENCODING, 'utf-8', 'latin-1'):
# try:
# return value.decode(c, errors)
# except UnicodeError:
# pass
# if not desperate:
# raise UnicodeError("Couldn't decode value to unicode (and not desperate enough to keep trying)")
#
# return value.decode(encoding or ENCODING, 'replace')
. Output only the next line. | value = py3_str(value) |
Given snippet: <|code_start|> def __init__(self, bio, ssl):
# Hold reference to SSL object to ensure _BIOWrapper.__del__ gets
# called before _SSLWrapper.__del__. Otherwise, if the SSL obj
# gets freed before the BIO object, we will segfault.
self.obj = bio
self.ssl = ssl
def __del__(self):
if self.obj is not None:
self.m2_bio_free_all(self.obj)
class M2TLSSocket(TLSSocketBase):
"""
TLSSocket implementation that uses M2Crypto. This class uses OpenSSL's BIO
pairs for guaranteed async IO; all socket communication is handled by us
(via the IOChannel). See:
http://www.openssl.org/docs/crypto/BIO_new_bio_pair.html
Inspired heavily by TwistedProtocolWrapper.py from M2Crypto.
"""
# list of suuported TLS authentication mechanisms
supported_methods = [ 'X.509' ]
def __init__(self):
super(M2TLSSocket, self).__init__()
self._reset()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
import M2Crypto
import kaa
from M2Crypto import m2, X509
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase
and context:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
which might include code, classes, or functions. Output only the next line. | def _m2_check_err(self, r=None, cls=TLSError): |
Continue the code snippet: <|code_start|> Returns True if we're interested in read events.
"""
# While doing initial handshake from ClientHello, we are interested
# in read events internally, even if we have no listeners.
should_read = m2.bio_should_read(self._bio_ssl.obj) if self._bio_ssl else False
return should_read or self._handshake or super(M2TLSSocket, self)._is_read_connected()
# Useful for debug.
#def _write(self, data):
# print 'm2: write len=%d data=%r...' % (len(data), data[:20])
# return super(M2TLSSocket, self)._write(data)
def write(self, data):
# A write can require us to read from the socket, even when there are
# no callbacks attached to 'read' or 'readline', such as in the
# case when a handshake is still pending. If this is the case,
# _encrypt() called below will cause _rmon to get registered while
# the TLS layer needs data from the peer.
if not self._tls_started:
return super(M2TLSSocket, self).write(data)
self._buf_plaintext.append(data)
try:
ip = super(M2TLSSocket, self).write(self._encrypt())
# FIXME: this IP might not reflect the given data for this write()
# if we're currently doing a handshake.
return ip
except M2Crypto.BIO.BIOError, e:
<|code_end|>
. Use current file imports:
import logging
import os
import M2Crypto
import kaa
from M2Crypto import m2, X509
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase
and context (classes, functions, or code) from other files:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
. Output only the next line. | raise TLSProtocolError(e.args[0]) |
Using the snippet: <|code_start|>
def write(self, data):
# A write can require us to read from the socket, even when there are
# no callbacks attached to 'read' or 'readline', such as in the
# case when a handshake is still pending. If this is the case,
# _encrypt() called below will cause _rmon to get registered while
# the TLS layer needs data from the peer.
if not self._tls_started:
return super(M2TLSSocket, self).write(data)
self._buf_plaintext.append(data)
try:
ip = super(M2TLSSocket, self).write(self._encrypt())
# FIXME: this IP might not reflect the given data for this write()
# if we're currently doing a handshake.
return ip
except M2Crypto.BIO.BIOError, e:
raise TLSProtocolError(e.args[0])
def _check(self):
if self._validated or not m2.ssl_is_init_finished(self._ssl.obj):
return
kwargs = self._starttls_kwargs
if kwargs.get('verify'):
# See http://www.openssl.org/docs/apps/verify.html#DIAGNOSTICS
# for the error codes returned by SSL_get_verify_result.
if m2.ssl_get_verify_result(self._ssl.obj) != m2.X509_V_OK:
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import M2Crypto
import kaa
from M2Crypto import m2, X509
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase
and context (class names, function names, or code) available:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
. Output only the next line. | raise TLSVerificationError('Peer certificate is not signed by a known CA') |
Here is a snippet: <|code_start|>
def __init__(self, ssl):
self.obj = ssl
def __del__(self):
if self.obj is not None:
self.m2_ssl_free(self.obj)
class _BIOWrapper:
"""
Wrapper for a BIO object, which calls the low-level bio_free_all() on the
BIO during destruction. Also by pushing __del__ into here, it allows
M2TLSSocket to be garbage collected.
"""
m2_bio_free_all = m2.bio_free_all
def __init__(self, bio, ssl):
# Hold reference to SSL object to ensure _BIOWrapper.__del__ gets
# called before _SSLWrapper.__del__. Otherwise, if the SSL obj
# gets freed before the BIO object, we will segfault.
self.obj = bio
self.ssl = ssl
def __del__(self):
if self.obj is not None:
self.m2_bio_free_all(self.obj)
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import M2Crypto
import kaa
from M2Crypto import m2, X509
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase
and context from other files:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
, which may include functions, classes, or code. Output only the next line. | class M2TLSSocket(TLSSocketBase): |
Given snippet: <|code_start|> return init_args, init_kwargs
else:
# Fast paths.
if not args and not kwargs:
return init_args, init_kwargs
elif not init_args and not init_kwargs:
return args, kwargs
# Slower paths, where we must copy kwargs in order to merge user
# kwargs and invocation-time kwargs.
if self._init_args_first:
cb_args, cb_kwargs = init_args + args, kwargs.copy()
cb_kwargs.update(init_kwargs)
else:
cb_args, cb_kwargs = args + init_args, init_kwargs.copy()
cb_kwargs.update(kwargs)
return cb_args, cb_kwargs
def __call__(self, *args, **kwargs):
"""
Invoke the callable.
The arguments passed here take precedence over constructor arguments
if the :attr:`~kaa.Callable.init_args_first` property is False (default).
The wrapped callable's return value is returned.
"""
cb = self._get_func()
if cb is None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import _weakref
import types
import logging
import atexit
from .errors import CallableError
and context:
# Path: src/errors.py
# class CallableError(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | raise CallableError('attempting to invoke an invalid callable') |
Given snippet: <|code_start|>#
# gnutls_srp_allocate_client_credentials = c_gnutls.gnutls_srp_allocate_client_credentials
# gnutls_srp_allocate_client_credentials.restype = ctypes.c_int
# gnutls_srp_allocate_client_credentials.argtypes = [ctypes.POINTER(gnutls_srp_credentials_t)]
# gnutls_srp_set_client_credentials = c_gnutls.gnutls_srp_set_client_credentials
# gnutls_srp_set_client_credentials.restype = ctypes.c_int
# gnutls_srp_set_client_credentials.argtypes = [gnutls_srp_credentials_t]
# gnutls_srp_free_client_credentials = c_gnutls.gnutls_srp_free_client_credentials
# gnutls_srp_free_client_credentials.restype = None
# gnutls_srp_free_client_credentials.argtypes = [gnutls_srp_credentials_t]
#
# class SRPCredentials(object):
#
# def __new__(cls, *args, **kwargs):
# c_object = gnutls_srp_credentials_t()
# gnutls_srp_allocate_client_credentials(ctypes.byref(c_object))
# instance = object.__new__(cls)
# instance._c_object = c_object
# return instance
#
# def __init__(self, username, password):
# self._type = ctypes.c_int(3)
# self.username = username
# self.password = password
# gnutls_srp_set_client_credentials(self._c_object, username, password);
#
# def __del__(self):
# gnutls_srp_free_client_credentials(self._c_object)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import socket
import logging
import kaa
import gnutls.connection
from .common import TLSSocketBase
from gnutls.connection import X509Certificate, X509PrivateKey, X509Certificate, X509CRL, X509Credentials
and context:
# Path: src/net/tls/common.py
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
which might include code, classes, or functions. Output only the next line. | class GNUTLSSocket(TLSSocketBase): |
Next line prediction: <|code_start|>
self._rmon.unregister()
def _handle_write(self):
if self._handshake:
# Before starting the TLS handshake we created a new write
# queue. The data send before TLS was started
# (_pre_handshake_write_queue) must be send, after that we
# give control over the socket to the TLS layer. Data
# written while doing the handshake is send after it.
if not self._pre_handshake_write_queue:
# No data to send before the handshake
return
try:
# Switch queues and send pre handshake data
queue = self._write_queue
self._write_queue = self._pre_handshake_write_queue
super(TLSSocketBase, self)._handle_write()
finally:
self._write_queue = queue
else:
# normal operation
super(TLSSocketBase, self)._handle_write()
@kaa.coroutine()
def _starttls(self, mode, *args, **kwargs):
# TODO: accept 'verify' and 'check' kwargs like the m2 backend
if not self.connected:
<|code_end|>
. Use current file imports:
(import logging
import os
import tlslite.api as tlsapi
import gdata.tlslite.api as tlsapi
import kaa
from tlslite.errors import TLSAuthenticationError
from gdata.tlslite.errors import TLSAuthenticationError
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase)
and context including class names, function names, or small code snippets from other files:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
. Output only the next line. | raise TLSError('Socket not connected') |
Predict the next line after this snippet: <|code_start|> settings=None, checker=None):
"""
Start a server handshake operation on the TLS connection.
"""
handshake = tlsapi.TLSConnection.handshakeServerAsync(
self, sharedKeyDB, verifierDB, certChain, privateKey, reqCert,
sessionCache, settings, checker)
return self._iterate_handshake(handshake)
def fileno(self):
"""
Return socket descriptor. This makes this class feel like a normal
socket to the IOMonitor.
"""
return self.sock.fileno()
def close(self):
"""
Close the socket.
"""
if not self.closed:
# force socket close or this will block
# on kaa shutdown.
self.sock.close()
return tlsapi.TLSConnection.close(self)
<|code_end|>
using the current file's imports:
import logging
import os
import tlslite.api as tlsapi
import gdata.tlslite.api as tlsapi
import kaa
from tlslite.errors import TLSAuthenticationError
from gdata.tlslite.errors import TLSAuthenticationError
from .common import TLSError, TLSProtocolError, TLSVerificationError, TLSSocketBase
and any relevant context from other files:
# Path: src/net/tls/common.py
# class TLSError(Exception):
# """
# Base class for all TLS/SSL exceptions.
#
# Exception args is a message string.
# """
# pass
#
# class TLSProtocolError(TLSError):
# """
# Raised when a protocol-related problem occurs, such as the remote end does
# not speak TLS, or when no shared cipher could be established.
# """
# pass
#
# class TLSVerificationError(TLSError):
# """
# Raised when the remote end's certificate did not verify correctly.
# """
# pass
#
# class TLSSocketBase(kaa.Socket):
# # list of suuported TLS authentication mechanisms (subclass must override)
# supported_methods = []
#
# # Cached system-wide CA cert file (as detected), or None if none was found.
# _cafile = False
#
# __kaasignals__ = {
# 'tls':
# '''
# Emitted when a TLS handshake has been successfully completed.
# '''
# }
#
# def __init__(self, cafile=None):
# super(TLSSocketBase, self).__init__()
# self._handshake = False
# self._pre_handshake_write_queue = []
#
# if cafile:
# self._cafile = cafile
# elif TLSSocketBase._cafile is False:
# self._cafile = None
# for path in CA_SEARCH_PATH:
# if os.path.exists(path):
# cafile = path
# break
# else:
# # Maybe locate(1) can help.
# # XXX: assumes this is fast. Maybe this should be done async.
# path = os.popen('locate -l 1 ca-certificates.crt ca-bundle.crt 2>/dev/null').readline().strip()
# if os.path.exists(path):
# cafile = path
#
# TLSSocketBase._cafile = self._cafile = cafile
. Output only the next line. | class TLSLiteSocket(TLSSocketBase): |
Given snippet: <|code_start|> message = "ok"
if os.path.exists(dsm) is False:
message = "no dsm"
if message == "ok":
tiles.append(t)
return tiles
def produce_lidarviewer(s2poutdir, output):
"""
Produce a single multiscale point cloud for the whole processed region.
Args:
tiles: list of tiles dictionaries
"""
tiles_file = os.path.join(s2poutdir, 'tiles.txt')
# Read the tiles file
tiles = s2p.read_tiles(tiles_file)
print(str(len(tiles))+' tiles found')
# collect all plys
plys = [os.path.join(os.path.abspath(os.path.dirname(t)), 'cloud.ply') for t in tiles]
nthreads = 4
plys = ' '.join(plys)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import json
import argparse
import s2p
import tempfile
from s2p import common
and context:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
which might include code, classes, or functions. Output only the next line. | common.run("LidarPreprocessor -to %s.LidarO -tp %s.LidarP -nt %d %s -o %s" % (output, |
Using the snippet: <|code_start|> apply_async, it has to take one argument.
"""
show_progress.counter += 1
status = "done {:{fill}{width}} / {} tiles".format(show_progress.counter,
show_progress.total,
fill='',
width=len(str(show_progress.total)))
if show_progress.counter < show_progress.total:
status += chr(8) * len(status)
else:
status += '\n'
sys.stdout.write(status)
sys.stdout.flush()
def tilewise_wrapper(fun, *args, **kwargs):
"""
"""
if not cfg['debug']: # redirect stdout and stderr to log file
f = open(kwargs['stdout'], 'a')
sys.stdout = f
sys.stderr = f
try:
out = fun(*args)
except Exception:
print("Exception in %s" % fun.__name__)
traceback.print_exc()
raise
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import traceback
import multiprocessing
from s2p import common
from s2p.config import cfg
and context (class names, function names, or code) available:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | common.garbage_cleanup() |
Given snippet: <|code_start|>
def test_affine_transformation():
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
# list of transformations to be tested
T = np.eye(3)
I = np.eye(3)
S = np.eye(3)
A = np.eye(3)
translations = []
isometries = []
similarities = []
affinities = []
for i in range(100):
translations.append(T)
isometries.append(I)
similarities.append(S)
affinities.append(A)
T[0:2, 2] = np.random.random(2)
I = rotation_matrix(2*np.pi * np.random.random_sample())
I[0:2, 2] = np.random.random(2)
S = similarity_matrix(2*np.pi * np.random.random_sample(),
np.random.random_sample())
S[0:2, 2] = 100 * np.random.random(2)
A[0:2, :] = np.random.random((2, 3))
for B in translations + isometries + similarities + affinities:
xx = common.points_apply_homography(B, x)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from numpy.testing import assert_array_almost_equal
from s2p import estimation
from s2p import common
and context:
# Path: s2p/estimation.py
# def fundamental_matrix_cameras(P1, P2):
# def get_angle_from_cos_and_sin(c, s):
# def rectifying_similarities_from_affine_fundamental_matrix(F, debug=False):
# def affine_fundamental_matrix(matches):
# def affine_transformation(x, xx):
# def translation(x, xx):
# X0 = P1[[1, 2], :]
# X1 = P1[[2, 0], :]
# X2 = P1[[0, 1], :]
# Y0 = P2[[1, 2], :]
# Y1 = P2[[2, 0], :]
# Y2 = P2[[0, 1], :]
# F = np.zeros((3, 3))
# F[0, 0] = np.linalg.det(np.vstack([X0, Y0]))
# F[0, 1] = np.linalg.det(np.vstack([X1, Y0]))
# F[0, 2] = np.linalg.det(np.vstack([X2, Y0]))
# F[1, 0] = np.linalg.det(np.vstack([X0, Y1]))
# F[1, 1] = np.linalg.det(np.vstack([X1, Y1]))
# F[1, 2] = np.linalg.det(np.vstack([X2, Y1]))
# F[2, 0] = np.linalg.det(np.vstack([X0, Y2]))
# F[2, 1] = np.linalg.det(np.vstack([X1, Y2]))
# F[2, 2] = np.linalg.det(np.vstack([X2, Y2]))
# R1 = (1.0 / r) * np.array([[b, -a], [a, b]])
# R2 = (1.0 / s) * np.array([[-d, c], [-c, -d]])
# S1 = np.zeros((3, 3))
# S1[0:2, 0:2] = z * R1
# S1[1, 2] = t
# S1[2, 2] = 1
# S2 = np.zeros((3, 3))
# S2[0:2, 0:2] = (1.0 / z) * R2
# S2[1, 2] = -t
# S2[2, 2] = 1
# X = matches[:, [2, 3, 0, 1]]
# N = len(X)
# XX = np.sum(X, axis=0) / N
# A = X - np.tile(XX, (N, 1))
# U, S, V = np.linalg.svd(A)
# N = V[-1, :]
# F = np.zeros((3, 3))
# F[0, 2] = N[0]
# F[1, 2] = N[1]
# F[2, 0] = N[2]
# F[2, 1] = N[3]
# F[2, 2] = -np.dot(N, XX)
# A = np.hstack((x, xx))
# U, S, V = np.linalg.svd(A)
# B = tmp[0:2, :]
# C = tmp[2:4, :]
# H = np.dot(C, np.linalg.inv(B))
# A = np.eye(3)
# A[0:2, 0:2] = H
# A[0:2, 2] = np.dot(H, t) - tt
# A = np.eye(3)
# A[0, 2] = t[0]
# A[1, 2] = t[1]
#
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
which might include code, classes, or functions. Output only the next line. | E = estimation.affine_transformation(x, xx) |
Next line prediction: <|code_start|> return R
def test_affine_transformation():
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
# list of transformations to be tested
T = np.eye(3)
I = np.eye(3)
S = np.eye(3)
A = np.eye(3)
translations = []
isometries = []
similarities = []
affinities = []
for i in range(100):
translations.append(T)
isometries.append(I)
similarities.append(S)
affinities.append(A)
T[0:2, 2] = np.random.random(2)
I = rotation_matrix(2*np.pi * np.random.random_sample())
I[0:2, 2] = np.random.random(2)
S = similarity_matrix(2*np.pi * np.random.random_sample(),
np.random.random_sample())
S[0:2, 2] = 100 * np.random.random(2)
A[0:2, :] = np.random.random((2, 3))
for B in translations + isometries + similarities + affinities:
<|code_end|>
. Use current file imports:
(import numpy as np
from numpy.testing import assert_array_almost_equal
from s2p import estimation
from s2p import common)
and context including class names, function names, or small code snippets from other files:
# Path: s2p/estimation.py
# def fundamental_matrix_cameras(P1, P2):
# def get_angle_from_cos_and_sin(c, s):
# def rectifying_similarities_from_affine_fundamental_matrix(F, debug=False):
# def affine_fundamental_matrix(matches):
# def affine_transformation(x, xx):
# def translation(x, xx):
# X0 = P1[[1, 2], :]
# X1 = P1[[2, 0], :]
# X2 = P1[[0, 1], :]
# Y0 = P2[[1, 2], :]
# Y1 = P2[[2, 0], :]
# Y2 = P2[[0, 1], :]
# F = np.zeros((3, 3))
# F[0, 0] = np.linalg.det(np.vstack([X0, Y0]))
# F[0, 1] = np.linalg.det(np.vstack([X1, Y0]))
# F[0, 2] = np.linalg.det(np.vstack([X2, Y0]))
# F[1, 0] = np.linalg.det(np.vstack([X0, Y1]))
# F[1, 1] = np.linalg.det(np.vstack([X1, Y1]))
# F[1, 2] = np.linalg.det(np.vstack([X2, Y1]))
# F[2, 0] = np.linalg.det(np.vstack([X0, Y2]))
# F[2, 1] = np.linalg.det(np.vstack([X1, Y2]))
# F[2, 2] = np.linalg.det(np.vstack([X2, Y2]))
# R1 = (1.0 / r) * np.array([[b, -a], [a, b]])
# R2 = (1.0 / s) * np.array([[-d, c], [-c, -d]])
# S1 = np.zeros((3, 3))
# S1[0:2, 0:2] = z * R1
# S1[1, 2] = t
# S1[2, 2] = 1
# S2 = np.zeros((3, 3))
# S2[0:2, 0:2] = (1.0 / z) * R2
# S2[1, 2] = -t
# S2[2, 2] = 1
# X = matches[:, [2, 3, 0, 1]]
# N = len(X)
# XX = np.sum(X, axis=0) / N
# A = X - np.tile(XX, (N, 1))
# U, S, V = np.linalg.svd(A)
# N = V[-1, :]
# F = np.zeros((3, 3))
# F[0, 2] = N[0]
# F[1, 2] = N[1]
# F[2, 0] = N[2]
# F[2, 1] = N[3]
# F[2, 2] = -np.dot(N, XX)
# A = np.hstack((x, xx))
# U, S, V = np.linalg.svd(A)
# B = tmp[0:2, :]
# C = tmp[2:4, :]
# H = np.dot(C, np.linalg.inv(B))
# A = np.eye(3)
# A[0:2, 0:2] = H
# A[0:2, 2] = np.dot(H, t) - tt
# A = np.eye(3)
# A[0, 2] = t[0]
# A[1, 2] = t[1]
#
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | xx = common.points_apply_homography(B, x) |
Based on the snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
def write_svg_tilemap(filename, cfg, tiles):
'''
draw tiles boundaries with names in an svg file
'''
with open(filename,'w') as f:
f.write('<?xml version="1.0" standalone="no"?>\
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" \
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">')
f.write('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" \
xmlns:xlink="http://www.w3.org/1999/xlink" \
width="1000px" height="1000px" viewBox="%d %d %d %d">'%(
cfg['roi']['x'], cfg['roi']['y'], cfg['roi']['w'], cfg['roi']['h']))
for t in tiles:
x, y ,w ,h = t['coordinates']
dir = os.path.abspath(t['dir']).split(os.path.abspath(cfg['out_dir']))[-1]
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import os.path
import json
import argparse
import numpy as np
import datetime
import s2p
from s2p.config import cfg
from s2p import common
from s2p import initialization
and context (classes, functions, sometimes code) from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/initialization.py
# def workaround_json_int64(o):
# def dict_has_keys(d, l):
# def check_parameters(d):
# def build_cfg(user_cfg):
# def make_dirs():
# def adjust_tile_size():
# def compute_tiles_coordinates(rx, ry, rw, rh, tw, th):
# def get_tile_dir(x, y, w, h):
# def create_tile(coords, neighborhood_coords_dict):
# def tiles_full_info(tw, th, tiles_txt, create_masks=False):
. Output only the next line. | common.image_qauto("%s/dsm.tif"%t['dir'], "%s/dsm.tif.png"%t['dir']) |
Next line prediction: <|code_start|> except common.RunFailure:
pass
f.write('<polygon style="fill:white;stroke:black;stroke-width:2" \
points="%d %d, %d %d, %d %d, %d %d" />'%(
x,y, x+w,y, x+w,y+h, x,y+h))
f.write('<image xlink:href="./%s/dsm.tif.png" \
x="%d" y="%d" width="%d" height="%d"/>'%(
dir, x,y, w, h))
f.write('<a xlink:href="./%s/" target="_blank">'%dir)
f.write('<g transform="translate(%d,%d)">\
<text x="%d" y="%d" text-anchor="middle" \
style="fill: #00FF00; stroke: #00FF00; stroke-width: 0.5; font-size: 12px;" \
alignment-baseline="central">%s</text></g>'%(
x,y,w/2,h/2,dir))
f.write('</a>')
f.write('</svg>')
f.close()
def main(user_cfg):
"""
Recompute the s2p tile geometry for the config file
and produce an svg representing the tiles
Args:
user_cfg: user config dictionary
"""
common.print_elapsed_time.t0 = datetime.datetime.now()
<|code_end|>
. Use current file imports:
(import os.path
import json
import argparse
import numpy as np
import datetime
import s2p
from s2p.config import cfg
from s2p import common
from s2p import initialization)
and context including class names, function names, or small code snippets from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/initialization.py
# def workaround_json_int64(o):
# def dict_has_keys(d, l):
# def check_parameters(d):
# def build_cfg(user_cfg):
# def make_dirs():
# def adjust_tile_size():
# def compute_tiles_coordinates(rx, ry, rw, rh, tw, th):
# def get_tile_dir(x, y, w, h):
# def create_tile(coords, neighborhood_coords_dict):
# def tiles_full_info(tw, th, tiles_txt, create_masks=False):
. Output only the next line. | initialization.build_cfg(user_cfg) |
Continue the code snippet: <|code_start|>
if output_format == 'tif':
vrt_basename = vrt_basename[:-3]+'vrt'
elif output_format !='vrt':
print('Error: only vrt or tif extension is allowed for output image.')
return
vrt_name = os.path.join(outfile_dirname,vrt_basename)
# Read the tiles file
tiles = s2p.read_tiles(tiles_file)
print(str(len(tiles))+' tiles found')
# Compute the global extent of the output image
(min_x,max_x,min_y,max_y) = global_extent(tiles)
print('Global extent: [%i,%i]x[%i,%i]'%(min_x,max_x,min_y,max_y))
# Now, write all row vrts
print("Writing row vrt files "+vrt_basename)
vrt_row = write_row_vrts(tiles,sub_img,vrt_basename,min_x,max_x)
# Finally, write main vrt
print('Writing '+vrt_name)
write_main_vrt(vrt_row,vrt_name,min_x,max_x,min_y,max_y)
# If Output format is tif, convert vrt file to tif
if output_format == 'tif':
print('Converting vrt to tif ...')
<|code_end|>
. Use current file imports:
import os
import json
import argparse
import s2p
from s2p import common
and context (classes, functions, or code) from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | common.run(('gdal_translate -ot Float32 -co TILED=YES -co' |
Given snippet: <|code_start|> else:
return np.nanmedian(x)
def merge_n(output, inputs, offsets, averaging='average_if_close', threshold=1):
"""
Merge n images of equal sizes by taking the median/mean/min/max pixelwise.
Args:
inputs: list of paths to the input images
output: path to the output image
averaging: string containing the name of a function that accepts
1D arrays. It is applied to 1D slices of the stack of images along
the last axis. Possible values are, for instance np.min, np.max,
np.mean, np.median and their nanproof counterparts, ie np.nanmin,
np.nanmax, np.nanmean, np.nanmedian
"""
assert(len(inputs) == len(offsets))
# get input images size
if inputs:
with rasterio.open(inputs[0], 'r') as f:
h, w = f.shape
# read input images and apply offsets
x = np.empty((h, w, len(inputs)))
for i, img in enumerate(inputs):
with rasterio.open(img, 'r') as f:
x[:, :, i] = f.read(1) - offsets[i]
if cfg['debug']:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import shutil
import numpy as np
import rasterio
from s2p.config import cfg
from s2p import common
and context:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
which might include code, classes, or functions. Output only the next line. | common.rasterio_write('{}_registered.tif'.format(os.path.splitext(img)[0]), |
Using the snippet: <|code_start|> if algo in ['tvl1_2d']:
return True
else:
return False
def compute_disparity_map(im1, im2, disp, mask, algo, disp_min=None,
disp_max=None, extra_params=''):
"""
Runs a block-matching binary on a pair of stereo-rectified images.
Args:
im1, im2: rectified stereo pair
disp: path to the output diparity map
mask: path to the output rejection mask
algo: string used to indicate the desired binary. Currently it can be
one among 'hirschmuller02', 'hirschmuller08',
'hirschmuller08_laplacian', 'hirschmuller08_cauchy', 'sgbm',
'msmw', 'tvl1', 'mgm', 'mgm_multi' and 'micmac'
disp_min : smallest disparity to consider
disp_max : biggest disparity to consider
extra_params: optional string with algorithm-dependent parameters
"""
if rectify_secondary_tile_only(algo) is False:
disp_min = [disp_min]
disp_max = [disp_max]
# limit disparity bounds
np.alltrue(len(disp_min) == len(disp_max))
for dim in range(len(disp_min)):
if disp_min[dim] is not None and disp_max[dim] is not None:
<|code_end|>
, determine the next line of code. You have imports:
import os
import numpy as np
from s2p import common
from s2p.config import cfg
and context (class names, function names, or code) available:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | image_size = common.image_size_gdal(im1) |
Using the snippet: <|code_start|># Copyright (C) 2015, Carlo de Franchis <carlo.de-franchis@cmla.ens-cachan.fr>
# Copyright (C) 2015, Gabriele Facciolo <facciolo@cmla.ens-cachan.fr>
# Copyright (C) 2015, Enric Meinhardt <enric.meinhardt@cmla.ens-cachan.fr>
def height_map_rectified(rpc1, rpc2, H1, H2, disp, mask, height, rpc_err, A=None):
"""
Computes a height map from a disparity map, using rpc.
Args:
rpc1, rpc2: paths to the xml files
H1, H2: path to txt files containing two 3x3 numpy arrays defining
the rectifying homographies
disp, mask: paths to the diparity and mask maps
height: path to the output height map
rpc_err: path to the output rpc_error of triangulation
A (optional): path to txt file containing the pointing correction matrix
for im2
"""
if A is not None:
<|code_end|>
, determine the next line of code. You have imports:
import os
import numpy as np
from s2p import common
from s2p.config import cfg
and context (class names, function names, or code) available:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | HH2 = common.tmpfile('.txt') |
Given the following code snippet before the placeholder: <|code_start|>def dict_has_keys(d, l):
"""
Return True if the dict d contains all the keys of the input list l.
"""
return all(k in d for k in l)
def check_parameters(d):
"""
Check that the provided dictionary defines all mandatory s2p arguments.
Args:
d: python dictionary
"""
# verify that input files paths are defined
if 'images' not in d or len(d['images']) < 2:
print('ERROR: missing paths to input images')
sys.exit(1)
for i in range(len(d['images'])):
img = d['images'][i]
if not dict_has_keys(img, ['img']):
print('ERROR: missing img paths for image', img)
sys.exit(1)
if not dict_has_keys(img, ['rpc']) or img['rpc'] == '':
img['rpc'] = tempfile.mktemp('.rpc')
rpc_utils.rpc_from_geotiff(img['img'], img['rpc'])
print('INFO: trying reading rpc from image', img)
# verify that roi or path to preview file are defined
if 'full_img' in d and d['full_img']:
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import utm
import json
import copy
import shutil
import warnings
import numpy as np
import tempfile # TODO: fix for common.tmpfile failure
from s2p import common
from s2p import rpc_utils
from s2p import masking
from s2p import parallel
from s2p.config import cfg
and context including class names, function names, and sometimes code from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/rpc_utils.py
# def find_corresponding_point(model_a, model_b, x, y, z):
# def compute_height(model_a, model_b, x1, y1, x2, y2):
# def geodesic_bounding_box(rpc, x, y, w, h):
# def altitude_range_coarse(rpc, scale_factor=1):
# def min_max_heights_from_bbx(im, lon_m, lon_M, lat_m, lat_M, rpc):
# def altitude_range(rpc, x, y, w, h, margin_top=0, margin_bottom=0):
# def utm_zone(rpc, x, y, w, h):
# def utm_roi_to_img_roi(rpc, roi):
# def kml_roi_process(rpc, kml):
# def generate_point_mesh(col_range, row_range, alt_range):
# def ground_control_points(rpc, x, y, w, h, m, M, n):
# def corresponding_roi(rpc1, rpc2, x, y, w, h):
# def matches_from_rpc(rpc1, rpc2, x, y, w, h, n):
# def alt_to_disp(rpc1, rpc2, x, y, alt, H1, H2, A=None):
# def exogenous_disp_range_estimation(rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def altitude_range_to_disp_range(m, M, rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def rpc_from_geotiff(geotiff_path, outrpcfile='.rpc'):
# HSTEP = 1
# M = rpc.altOff + rpc.altScale
# M = rpc.altOff + scale_factor * rpc.altScale
#
# Path: s2p/masking.py
# def cloud_water_image_domain(x, y, w, h, rpc, roi_gml=None, cld_gml=None,
# wat_msk=None):
# def erosion(out, msk, radius):
# H = common.matrix_translation(-x, -y)
#
# Path: s2p/parallel.py
# def show_progress(a):
# def tilewise_wrapper(fun, *args, **kwargs):
# def launch_calls(fun, list_of_args, nb_workers, *extra_args):
# def launch_calls_simple(fun, list_of_args, nb_workers, *extra_args):
. Output only the next line. | sz = common.image_size_gdal(d['images'][0]['img']) |
Continue the code snippet: <|code_start|># https://bugs.python.org/issue24313
def workaround_json_int64(o):
if isinstance(o,np.integer) : return int(o)
raise TypeError
def dict_has_keys(d, l):
"""
Return True if the dict d contains all the keys of the input list l.
"""
return all(k in d for k in l)
def check_parameters(d):
"""
Check that the provided dictionary defines all mandatory s2p arguments.
Args:
d: python dictionary
"""
# verify that input files paths are defined
if 'images' not in d or len(d['images']) < 2:
print('ERROR: missing paths to input images')
sys.exit(1)
for i in range(len(d['images'])):
img = d['images'][i]
if not dict_has_keys(img, ['img']):
print('ERROR: missing img paths for image', img)
sys.exit(1)
if not dict_has_keys(img, ['rpc']) or img['rpc'] == '':
img['rpc'] = tempfile.mktemp('.rpc')
<|code_end|>
. Use current file imports:
import os
import sys
import utm
import json
import copy
import shutil
import warnings
import numpy as np
import tempfile # TODO: fix for common.tmpfile failure
from s2p import common
from s2p import rpc_utils
from s2p import masking
from s2p import parallel
from s2p.config import cfg
and context (classes, functions, or code) from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/rpc_utils.py
# def find_corresponding_point(model_a, model_b, x, y, z):
# def compute_height(model_a, model_b, x1, y1, x2, y2):
# def geodesic_bounding_box(rpc, x, y, w, h):
# def altitude_range_coarse(rpc, scale_factor=1):
# def min_max_heights_from_bbx(im, lon_m, lon_M, lat_m, lat_M, rpc):
# def altitude_range(rpc, x, y, w, h, margin_top=0, margin_bottom=0):
# def utm_zone(rpc, x, y, w, h):
# def utm_roi_to_img_roi(rpc, roi):
# def kml_roi_process(rpc, kml):
# def generate_point_mesh(col_range, row_range, alt_range):
# def ground_control_points(rpc, x, y, w, h, m, M, n):
# def corresponding_roi(rpc1, rpc2, x, y, w, h):
# def matches_from_rpc(rpc1, rpc2, x, y, w, h, n):
# def alt_to_disp(rpc1, rpc2, x, y, alt, H1, H2, A=None):
# def exogenous_disp_range_estimation(rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def altitude_range_to_disp_range(m, M, rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def rpc_from_geotiff(geotiff_path, outrpcfile='.rpc'):
# HSTEP = 1
# M = rpc.altOff + rpc.altScale
# M = rpc.altOff + scale_factor * rpc.altScale
#
# Path: s2p/masking.py
# def cloud_water_image_domain(x, y, w, h, rpc, roi_gml=None, cld_gml=None,
# wat_msk=None):
# def erosion(out, msk, radius):
# H = common.matrix_translation(-x, -y)
#
# Path: s2p/parallel.py
# def show_progress(a):
# def tilewise_wrapper(fun, *args, **kwargs):
# def launch_calls(fun, list_of_args, nb_workers, *extra_args):
# def launch_calls_simple(fun, list_of_args, nb_workers, *extra_args):
. Output only the next line. | rpc_utils.rpc_from_geotiff(img['img'], img['rpc']) |
Given snippet: <|code_start|> return tile
def tiles_full_info(tw, th, tiles_txt, create_masks=False):
"""
List the tiles to process and prepare their output directories structures.
Most of the time is spent discarding tiles that are masked by water
(according to exogenous dem).
Returns:
a list of dictionaries. Each dictionary contains the image coordinates
and the output directory path of a tile.
"""
rpc = cfg['images'][0]['rpc']
roi_msk = cfg['images'][0]['roi']
cld_msk = cfg['images'][0]['cld']
wat_msk = cfg['images'][0]['wat']
rx = cfg['roi']['x']
ry = cfg['roi']['y']
rw = cfg['roi']['w']
rh = cfg['roi']['h']
# build a tile dictionary for all non-masked tiles and store them in a list
tiles = []
# list tiles coordinates
tiles_coords, neighborhood_coords_dict = compute_tiles_coordinates(rx, ry, rw, rh, tw, th)
if os.path.exists(tiles_txt) is False or create_masks is True:
print('\ndiscarding masked tiles...')
# compute all masks in parallel as numpy arrays
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import utm
import json
import copy
import shutil
import warnings
import numpy as np
import tempfile # TODO: fix for common.tmpfile failure
from s2p import common
from s2p import rpc_utils
from s2p import masking
from s2p import parallel
from s2p.config import cfg
and context:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/rpc_utils.py
# def find_corresponding_point(model_a, model_b, x, y, z):
# def compute_height(model_a, model_b, x1, y1, x2, y2):
# def geodesic_bounding_box(rpc, x, y, w, h):
# def altitude_range_coarse(rpc, scale_factor=1):
# def min_max_heights_from_bbx(im, lon_m, lon_M, lat_m, lat_M, rpc):
# def altitude_range(rpc, x, y, w, h, margin_top=0, margin_bottom=0):
# def utm_zone(rpc, x, y, w, h):
# def utm_roi_to_img_roi(rpc, roi):
# def kml_roi_process(rpc, kml):
# def generate_point_mesh(col_range, row_range, alt_range):
# def ground_control_points(rpc, x, y, w, h, m, M, n):
# def corresponding_roi(rpc1, rpc2, x, y, w, h):
# def matches_from_rpc(rpc1, rpc2, x, y, w, h, n):
# def alt_to_disp(rpc1, rpc2, x, y, alt, H1, H2, A=None):
# def exogenous_disp_range_estimation(rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def altitude_range_to_disp_range(m, M, rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def rpc_from_geotiff(geotiff_path, outrpcfile='.rpc'):
# HSTEP = 1
# M = rpc.altOff + rpc.altScale
# M = rpc.altOff + scale_factor * rpc.altScale
#
# Path: s2p/masking.py
# def cloud_water_image_domain(x, y, w, h, rpc, roi_gml=None, cld_gml=None,
# wat_msk=None):
# def erosion(out, msk, radius):
# H = common.matrix_translation(-x, -y)
#
# Path: s2p/parallel.py
# def show_progress(a):
# def tilewise_wrapper(fun, *args, **kwargs):
# def launch_calls(fun, list_of_args, nb_workers, *extra_args):
# def launch_calls_simple(fun, list_of_args, nb_workers, *extra_args):
which might include code, classes, or functions. Output only the next line. | tiles_masks = parallel.launch_calls_simple(masking.cloud_water_image_domain, |
Predict the next line for this snippet: <|code_start|> return tile
def tiles_full_info(tw, th, tiles_txt, create_masks=False):
"""
List the tiles to process and prepare their output directories structures.
Most of the time is spent discarding tiles that are masked by water
(according to exogenous dem).
Returns:
a list of dictionaries. Each dictionary contains the image coordinates
and the output directory path of a tile.
"""
rpc = cfg['images'][0]['rpc']
roi_msk = cfg['images'][0]['roi']
cld_msk = cfg['images'][0]['cld']
wat_msk = cfg['images'][0]['wat']
rx = cfg['roi']['x']
ry = cfg['roi']['y']
rw = cfg['roi']['w']
rh = cfg['roi']['h']
# build a tile dictionary for all non-masked tiles and store them in a list
tiles = []
# list tiles coordinates
tiles_coords, neighborhood_coords_dict = compute_tiles_coordinates(rx, ry, rw, rh, tw, th)
if os.path.exists(tiles_txt) is False or create_masks is True:
print('\ndiscarding masked tiles...')
# compute all masks in parallel as numpy arrays
<|code_end|>
with the help of current file imports:
import os
import sys
import utm
import json
import copy
import shutil
import warnings
import numpy as np
import tempfile # TODO: fix for common.tmpfile failure
from s2p import common
from s2p import rpc_utils
from s2p import masking
from s2p import parallel
from s2p.config import cfg
and context from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
#
# Path: s2p/rpc_utils.py
# def find_corresponding_point(model_a, model_b, x, y, z):
# def compute_height(model_a, model_b, x1, y1, x2, y2):
# def geodesic_bounding_box(rpc, x, y, w, h):
# def altitude_range_coarse(rpc, scale_factor=1):
# def min_max_heights_from_bbx(im, lon_m, lon_M, lat_m, lat_M, rpc):
# def altitude_range(rpc, x, y, w, h, margin_top=0, margin_bottom=0):
# def utm_zone(rpc, x, y, w, h):
# def utm_roi_to_img_roi(rpc, roi):
# def kml_roi_process(rpc, kml):
# def generate_point_mesh(col_range, row_range, alt_range):
# def ground_control_points(rpc, x, y, w, h, m, M, n):
# def corresponding_roi(rpc1, rpc2, x, y, w, h):
# def matches_from_rpc(rpc1, rpc2, x, y, w, h, n):
# def alt_to_disp(rpc1, rpc2, x, y, alt, H1, H2, A=None):
# def exogenous_disp_range_estimation(rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def altitude_range_to_disp_range(m, M, rpc1, rpc2, x, y, w, h, H1, H2, A=None,
# margin_top=0, margin_bottom=0):
# def rpc_from_geotiff(geotiff_path, outrpcfile='.rpc'):
# HSTEP = 1
# M = rpc.altOff + rpc.altScale
# M = rpc.altOff + scale_factor * rpc.altScale
#
# Path: s2p/masking.py
# def cloud_water_image_domain(x, y, w, h, rpc, roi_gml=None, cld_gml=None,
# wat_msk=None):
# def erosion(out, msk, radius):
# H = common.matrix_translation(-x, -y)
#
# Path: s2p/parallel.py
# def show_progress(a):
# def tilewise_wrapper(fun, *args, **kwargs):
# def launch_calls(fun, list_of_args, nb_workers, *extra_args):
# def launch_calls_simple(fun, list_of_args, nb_workers, *extra_args):
, which may contain function names, class names, or code. Output only the next line. | tiles_masks = parallel.launch_calls_simple(masking.cloud_water_image_domain, |
Using the snippet: <|code_start|> percentile = np.nanpercentile(np.abs(diff), 99)
print('99th percentile abs difference',percentile,'(tolerance='+str(percentile_tol)+')')
assert(percentile <= percentile_tol)
def end2end(config,ref_dsm,absmean_tol=0.025,percentile_tol=1.):
print('Configuration file: ',config)
print('Reference DSM:',ref_dsm,os.linesep)
test_cfg = s2p.read_config_file(config)
s2p.main(test_cfg)
outdir = test_cfg['out_dir']
computed = s2p.common.gdal_read_as_array_with_nans(os.path.join(outdir,'dsm.tif'))
expected = s2p.common.gdal_read_as_array_with_nans(ref_dsm)
end2end_compare_dsm(computed,expected,absmean_tol,percentile_tol)
def end2end_mosaic(config,ref_height_map,absmean_tol=0.025,percentile_tol=1.):
test_cfg = s2p.read_config_file(config)
outdir = test_cfg['out_dir']
s2p.main(test_cfg)
tiles_file = os.path.join(outdir,'tiles.txt')
global_height_map = os.path.join(outdir,'height_map.tif')
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import argparse
import os
import sys
import json
import shutil
import multiprocessing
import collections
import subprocess
import glob
import s2p
import rasterio
from utils import s2p_mosaic
and context (class names, function names, or code) available:
# Path: utils/s2p_mosaic.py
# def vrt_body_source(fname,band,src_x,src_y,src_w,src_h,dst_x,dst_y,dst_w,dst_h):
# def vrt_header(w,h,dataType='Float32'):
# def vrt_footer():
# def global_extent(tiles):
# def write_row_vrts(tiles,sub_img,vrt_basename,min_x,max_x):
# def write_main_vrt(vrt_row,vrt_name,min_x,max_x,min_y,max_y):
# def main(tiles_file,outfile,sub_img):
. Output only the next line. | s2p_mosaic.main(tiles_file,global_height_map,'pair_1/height_map.tif') |
Continue the code snippet: <|code_start|>
The output file can be viewed with a web browser. This is useful for
huge point clouds. The input is a list of ply files.
If PotreeConverter is not available it doesn't fail.
Args:
output: path to the output folder
input_plys: list of paths to ply files
"""
ply2ascii = os.path.join(bin_dir, 'plytool/ply2ascii')
txt2las = os.path.join(bin_dir, 'PotreeConverter/LAStools/bin/txt2las')
PotreeConverter = os.path.join(bin_dir, 'PotreeConverter/build/PotreeConverter/PotreeConverter')
#if (not os.path.exists(ply2ascii)) or (not os.path.exists(txt2las)) or (not os.path.exists(PotreeConverter)) :
# return
outdir = os.path.dirname(output)
plys = ' '.join(input_plys)
las = []
trash = []
for p in input_plys:
# make ascii ply if needed
ap = tmpfile('.ply', outdir)
lp = tmpfile('.las', outdir)
las.append(lp)
<|code_end|>
. Use current file imports:
import os
import json
import argparse
import s2p
import tempfile
import os.path
import os.path
from codecs import open
from s2p import common
and context (classes, functions, or code) from other files:
# Path: s2p/common.py
# def remove(target):
# def garbage_cleanup():
# def tmpfile(ext=''):
# def run(cmd, env=os.environ):
# def mkdir_p(path):
# def shellquote(s):
# def matrix_translation(x, y):
# def image_size_gdal(im):
# def gdal_read_as_array_with_nans(im):
# def image_zoom_out_morpho(im, f):
# def rasterio_write(path, array, profile={}, tags={}):
# def image_apply_homography(out, im, H, w, h):
# def image_qauto(im, out=None):
# def points_apply_homography(H, pts):
# def bounding_box2D(pts):
# def image_crop_gdal(im, x, y, w, h, out=None):
# def run_binary_on_list_of_points(points, binary, option=None, env_var=None):
# def get_rectangle_coordinates(im):
# def get_roi_coordinates(img, preview):
# def cargarse_basura(inputf, outputf):
# def print_elapsed_time(since_first_call=False):
# class RunFailure(Exception):
. Output only the next line. | common.run("%s < %s > %s" % (ply2ascii, p, ap)) |
Given snippet: <|code_start|># coding=utf-8
from __future__ import absolute_import, division, print_function
__metaclass__ = type
def test_spectral_get_color_values():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from astwro.phot import stype
import numpy as np
and context:
# Path: astwro/phot/stype.py
# class SpectralType(object):
# def stype_name(cls, sptype):
# def stype_number(cls, sptypename):
# def __init__(self, reddening=None):
# def __call__ (self, color, value):
# def get_reddening(self, color):
# def get_color_values(self, color, sptypes):
# def get_color_value(self, color, sptype):
# def generate_plot_aids(self, color):
# def plot_twiny_spectral_types(self, ax, color, facecolor='gray', alpha=0.2):
which might include code, classes, or functions. Output only the next line. | zz = stype.SpectralType({'B-V': 1.5}) |
Predict the next line for this snippet: <|code_start|>
def test_real():
d, e, f = prepare_testset_real()
o, s, l, oe, se, le = dphot_filters(d, e, f)
pass
def test_masked_object():
d, e, c = prepare_testset_masked()
s, l, o, se, le, oe = dphot(d, e, c)
dp = DiffPhot(d, e, c)
assert np.allclose(dp.mag, s)
assert np.allclose(dp.lc, l)
assert np.allclose(dp.obs_deltas, o)
e = dp.err
e2= e**2
d = dp.obs_deltas_stddev
d2 = d**2
x = (dp.mag, dp.mag_v2, dp.lc_e)
# assert np.allclose(dp.mag_e, se)
def test_write_lc():
#TODO: Limit numer of stars in some_stars_data.pkl
with TmpDir() as td:
d, e, f = prepare_testset_real()
hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
<|code_end|>
with the help of current file imports:
from astwro.phot import *
from os.path import join
from astwro.phot.lc_io import write_lc, write_lc_filters
from astwro.utils import TmpDir
import numpy as np
import sys
import os
import pickle
and context from other files:
# Path: astwro/phot/lc_io.py
# def write_lc(hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if ids is None:
# ids = range(lc.shape[0])
# masked = isinstance(lc, np.ma.MaskedArray)
# if masked:
# smask = lc.count(axis=1) >= min_obs
# else:
# smask = np.ones(lc.shape[0], dtype=bool)
# logging.info('Number of stars to save: {}'.format(np.count_nonzero(smask)))
# for i in smask.nonzero()[0]:
# fname = '{:s}{:05d}{:s}'.format(prefix, ids[i], suffix)
# logging.info('Processing star id: ',i)
# d = lc[i]
# if masked:
# m = ~d.mask
# t = hjd[m]
# e = lc_e[i][m] if lc_e is not None else None
# d = d.compressed()
# else:
# t = hjd
# e = lc_e[i] if lc_e is not None else None
# if lc_e is None:
# out = np.array([t, d]).T
# else:
# out = np.array([t, d, e]).T
# np.savetxt(fname, out, fmt='%15f')
#
# def write_lc_filters(filters_masks, filternames, hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if isinstance(filters_masks, dict):
# filters_masks = [filters_masks[f] for f in filternames]
# filters_masks = np.array(filters_masks, dtype=bool)
#
# for i, mask in enumerate(filters_masks):
# logging.info('Writing lc for Filter: {}'.format(filternames[i]))
# s = '_' + filternames[i] + suffix
# mhjd = hjd[mask]
# mlc = lc[:, mask]
# if lc_e is not None:
# mlc_e = lc_e[:, mask]
# else:
# mlc_e = None
# write_lc(mhjd, mlc, mlc_e, ids, min_obs, prefix, s)
#
# Path: astwro/utils/TmpDir.py
# class TmpDir(PathLike):
# """
# instances of TmpDir keeps track and lifetime of temporary directory
# """
# path = None
# dir_is_tmp = True
# _prefix = ''
# _base = None
#
# def __init__(self, use_existing=None, prefix='astwro_tmp_', base_dir=None):
# """
# :param str use_existing: If provided, instance will point to that directory and not delete it on destruct
# :param str prefix: Prefix for temporary dir
# :param str base_dir: Where to crate tem dir, in None system default is used
# """
# self._prefix = prefix
# self._base = base_dir
# if use_existing is None:
# self.path = mkdtemp(prefix=prefix, dir=base_dir)
# self.dir_is_tmp = True
# else:
# self.path = use_existing
# self.dir_is_tmp = False
#
# def clone(self):
# return deepcopy(self)
#
# def __del__(self):
# self._rm_dir()
#
# def __enter__(self):
# return self
#
# def __exit__(self, type_, value, traceback):
# self._rm_dir()
#
# def __repr__(self):
# return ('Tmp dir:' if self.dir_is_tmp else 'Ext dir:') + (self.path if self.path else 'none')
#
# def __str__(self):
# return self.path
#
# def __deepcopy__(self, memo):
# cls = self.__class__
# new = cls.__new__(cls)
# memo[id(self)] = new
# if self.dir_is_tmp:
# new.__init__(prefix=self._prefix, base_dir=self._base)
# shutil.rmtree(new.path)
# shutil.copytree(self.path, new.path, symlinks=True)
# else:
# new.__init__(use_existing=self.path)
# return new
#
# def __fspath__(self):
# """Implements ``os.PathLike interface``"""
# return str(self)
#
# def _rm_dir(self):
# """Deletes working dir with all content."""
# if self.dir_is_tmp:
# try:
# shutil.rmtree(self.path)
# except OSError:
# pass
, which may contain function names, class names, or code. Output only the next line. | write_lc(hjd, d, e, prefix=join(td.path, 'lc_')) |
Given the following code snippet before the placeholder: <|code_start|> dp = DiffPhot(d, e, c)
assert np.allclose(dp.mag, s)
assert np.allclose(dp.lc, l)
assert np.allclose(dp.obs_deltas, o)
e = dp.err
e2= e**2
d = dp.obs_deltas_stddev
d2 = d**2
x = (dp.mag, dp.mag_v2, dp.lc_e)
# assert np.allclose(dp.mag_e, se)
def test_write_lc():
#TODO: Limit numer of stars in some_stars_data.pkl
with TmpDir() as td:
d, e, f = prepare_testset_real()
hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
write_lc(hjd, d, e, prefix=join(td.path, 'lc_'))
def test_write_lc_filter():
d, e, f = prepare_testset_real()
hjd = np.linspace(989.34316, 1002.63264, d.shape[1])
fn = ['B', 'Han']
r = np.random.uniform(size=d.shape[1])
fm = np.array([r<0.5, r>=0.5], dtype=bool)
with TmpDir() as td:
<|code_end|>
, predict the next line using imports from the current file:
from astwro.phot import *
from os.path import join
from astwro.phot.lc_io import write_lc, write_lc_filters
from astwro.utils import TmpDir
import numpy as np
import sys
import os
import pickle
and context including class names, function names, and sometimes code from other files:
# Path: astwro/phot/lc_io.py
# def write_lc(hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if ids is None:
# ids = range(lc.shape[0])
# masked = isinstance(lc, np.ma.MaskedArray)
# if masked:
# smask = lc.count(axis=1) >= min_obs
# else:
# smask = np.ones(lc.shape[0], dtype=bool)
# logging.info('Number of stars to save: {}'.format(np.count_nonzero(smask)))
# for i in smask.nonzero()[0]:
# fname = '{:s}{:05d}{:s}'.format(prefix, ids[i], suffix)
# logging.info('Processing star id: ',i)
# d = lc[i]
# if masked:
# m = ~d.mask
# t = hjd[m]
# e = lc_e[i][m] if lc_e is not None else None
# d = d.compressed()
# else:
# t = hjd
# e = lc_e[i] if lc_e is not None else None
# if lc_e is None:
# out = np.array([t, d]).T
# else:
# out = np.array([t, d, e]).T
# np.savetxt(fname, out, fmt='%15f')
#
# def write_lc_filters(filters_masks, filternames, hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if isinstance(filters_masks, dict):
# filters_masks = [filters_masks[f] for f in filternames]
# filters_masks = np.array(filters_masks, dtype=bool)
#
# for i, mask in enumerate(filters_masks):
# logging.info('Writing lc for Filter: {}'.format(filternames[i]))
# s = '_' + filternames[i] + suffix
# mhjd = hjd[mask]
# mlc = lc[:, mask]
# if lc_e is not None:
# mlc_e = lc_e[:, mask]
# else:
# mlc_e = None
# write_lc(mhjd, mlc, mlc_e, ids, min_obs, prefix, s)
#
# Path: astwro/utils/TmpDir.py
# class TmpDir(PathLike):
# """
# instances of TmpDir keeps track and lifetime of temporary directory
# """
# path = None
# dir_is_tmp = True
# _prefix = ''
# _base = None
#
# def __init__(self, use_existing=None, prefix='astwro_tmp_', base_dir=None):
# """
# :param str use_existing: If provided, instance will point to that directory and not delete it on destruct
# :param str prefix: Prefix for temporary dir
# :param str base_dir: Where to crate tem dir, in None system default is used
# """
# self._prefix = prefix
# self._base = base_dir
# if use_existing is None:
# self.path = mkdtemp(prefix=prefix, dir=base_dir)
# self.dir_is_tmp = True
# else:
# self.path = use_existing
# self.dir_is_tmp = False
#
# def clone(self):
# return deepcopy(self)
#
# def __del__(self):
# self._rm_dir()
#
# def __enter__(self):
# return self
#
# def __exit__(self, type_, value, traceback):
# self._rm_dir()
#
# def __repr__(self):
# return ('Tmp dir:' if self.dir_is_tmp else 'Ext dir:') + (self.path if self.path else 'none')
#
# def __str__(self):
# return self.path
#
# def __deepcopy__(self, memo):
# cls = self.__class__
# new = cls.__new__(cls)
# memo[id(self)] = new
# if self.dir_is_tmp:
# new.__init__(prefix=self._prefix, base_dir=self._base)
# shutil.rmtree(new.path)
# shutil.copytree(self.path, new.path, symlinks=True)
# else:
# new.__init__(use_existing=self.path)
# return new
#
# def __fspath__(self):
# """Implements ``os.PathLike interface``"""
# return str(self)
#
# def _rm_dir(self):
# """Deletes working dir with all content."""
# if self.dir_is_tmp:
# try:
# shutil.rmtree(self.path)
# except OSError:
# pass
. Output only the next line. | write_lc_filters(fm, fn, hjd, d, e, prefix=join(td.path, 'lc_')) |
Predict the next line for this snippet: <|code_start|> o, s, l, oe, se, le = dphot(d, e, c)
pass
def test_real():
d, e, f = prepare_testset_real()
o, s, l, oe, se, le = dphot_filters(d, e, f)
pass
def test_masked_object():
d, e, c = prepare_testset_masked()
s, l, o, se, le, oe = dphot(d, e, c)
dp = DiffPhot(d, e, c)
assert np.allclose(dp.mag, s)
assert np.allclose(dp.lc, l)
assert np.allclose(dp.obs_deltas, o)
e = dp.err
e2= e**2
d = dp.obs_deltas_stddev
d2 = d**2
x = (dp.mag, dp.mag_v2, dp.lc_e)
# assert np.allclose(dp.mag_e, se)
def test_write_lc():
#TODO: Limit numer of stars in some_stars_data.pkl
<|code_end|>
with the help of current file imports:
from astwro.phot import *
from os.path import join
from astwro.phot.lc_io import write_lc, write_lc_filters
from astwro.utils import TmpDir
import numpy as np
import sys
import os
import pickle
and context from other files:
# Path: astwro/phot/lc_io.py
# def write_lc(hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if ids is None:
# ids = range(lc.shape[0])
# masked = isinstance(lc, np.ma.MaskedArray)
# if masked:
# smask = lc.count(axis=1) >= min_obs
# else:
# smask = np.ones(lc.shape[0], dtype=bool)
# logging.info('Number of stars to save: {}'.format(np.count_nonzero(smask)))
# for i in smask.nonzero()[0]:
# fname = '{:s}{:05d}{:s}'.format(prefix, ids[i], suffix)
# logging.info('Processing star id: ',i)
# d = lc[i]
# if masked:
# m = ~d.mask
# t = hjd[m]
# e = lc_e[i][m] if lc_e is not None else None
# d = d.compressed()
# else:
# t = hjd
# e = lc_e[i] if lc_e is not None else None
# if lc_e is None:
# out = np.array([t, d]).T
# else:
# out = np.array([t, d, e]).T
# np.savetxt(fname, out, fmt='%15f')
#
# def write_lc_filters(filters_masks, filternames, hjd, lc, lc_e=None, ids=None, min_obs=1, prefix='lc_', suffix='.obs'):
# if isinstance(filters_masks, dict):
# filters_masks = [filters_masks[f] for f in filternames]
# filters_masks = np.array(filters_masks, dtype=bool)
#
# for i, mask in enumerate(filters_masks):
# logging.info('Writing lc for Filter: {}'.format(filternames[i]))
# s = '_' + filternames[i] + suffix
# mhjd = hjd[mask]
# mlc = lc[:, mask]
# if lc_e is not None:
# mlc_e = lc_e[:, mask]
# else:
# mlc_e = None
# write_lc(mhjd, mlc, mlc_e, ids, min_obs, prefix, s)
#
# Path: astwro/utils/TmpDir.py
# class TmpDir(PathLike):
# """
# instances of TmpDir keeps track and lifetime of temporary directory
# """
# path = None
# dir_is_tmp = True
# _prefix = ''
# _base = None
#
# def __init__(self, use_existing=None, prefix='astwro_tmp_', base_dir=None):
# """
# :param str use_existing: If provided, instance will point to that directory and not delete it on destruct
# :param str prefix: Prefix for temporary dir
# :param str base_dir: Where to crate tem dir, in None system default is used
# """
# self._prefix = prefix
# self._base = base_dir
# if use_existing is None:
# self.path = mkdtemp(prefix=prefix, dir=base_dir)
# self.dir_is_tmp = True
# else:
# self.path = use_existing
# self.dir_is_tmp = False
#
# def clone(self):
# return deepcopy(self)
#
# def __del__(self):
# self._rm_dir()
#
# def __enter__(self):
# return self
#
# def __exit__(self, type_, value, traceback):
# self._rm_dir()
#
# def __repr__(self):
# return ('Tmp dir:' if self.dir_is_tmp else 'Ext dir:') + (self.path if self.path else 'none')
#
# def __str__(self):
# return self.path
#
# def __deepcopy__(self, memo):
# cls = self.__class__
# new = cls.__new__(cls)
# memo[id(self)] = new
# if self.dir_is_tmp:
# new.__init__(prefix=self._prefix, base_dir=self._base)
# shutil.rmtree(new.path)
# shutil.copytree(self.path, new.path, symlinks=True)
# else:
# new.__init__(use_existing=self.path)
# return new
#
# def __fspath__(self):
# """Implements ``os.PathLike interface``"""
# return str(self)
#
# def _rm_dir(self):
# """Deletes working dir with all content."""
# if self.dir_is_tmp:
# try:
# shutil.rmtree(self.path)
# except OSError:
# pass
, which may contain function names, class names, or code. Output only the next line. | with TmpDir() as td: |
Using the snippet: <|code_start|># coding=utf-8
from __future__ import absolute_import, division, print_function
__metaclass__ = type
def plot_coords(fig=None, ax=None, fits_file=astwro.sampledata.fits_image(), gal=True, img_alpha=1.0, cmap=None,
grid_c='gray', grid_alpha=0.5, grid_ls='solid', keep_scale=True, img=True,
):
if ax is None or isinstance(ax, int):
if fig is None:
fig = plt.figure(figsize=(6, 6))
fig.tight_layout()
if ax is None: ax = 111
hdu = fits.open(fits_file)[0]
<|code_end|>
, determine the next line of code. You have imports:
import astropy.io.fits as fits
import astropy.visualization as vis
import matplotlib.pyplot as plt
import astwro.sampledata
from astropy.wcs import WCS
from .coord_tools import fix_scamp_wcs
and context (class names, function names, or code) available:
# Path: astwro/coord/coord_tools.py
# def fix_scamp_wcs(hdu):
# """Make FITS image scamp WCS headers WCSLib compatible
#
# Warning
# -------
# Current implementation just removes distortion parameters,
# astrometry is not accurate anymore!
# """
# for i in range(11):
# for pv in ['PV1_{:d}', 'PV2_{:d}']:
# hdu.header.remove(pv.format(i), ignore_missing=True, remove_all=True)
. Output only the next line. | fix_scamp_wcs(hdu) |
Here is a snippet: <|code_start|>
def parse_config(files=None, parse_default_locations=True):
"""Parses astwro config from files and sets config singleton
:rtype:ConfigParser
"""
__SinglethonConfig.config = parse_config_files(files=files,
parse_default_locations=parse_default_locations,
default_filename='astwro.cfg')
__std_config_dirs = [
get_package_config_path(),
'/etc/astwro/',
'~/.config/astwro/',
'./'
]
def parse_config_files(files=None, parse_default_locations=True, default_filename='config.cfg'):
"""Parses set of config files"""
if files is None:
files = []
if parse_default_locations:
files += [os.path.join(os.path.expanduser(d), default_filename) for d in __std_config_dirs]
config = ConfigParser()
read = config.read(files)
read.reverse()
if read:
<|code_end|>
. Write the next line using the current file imports:
from ConfigParser import ConfigParser, NoOptionError, NoSectionError # python 2
from configparser import ConfigParser, NoOptionError, NoSectionError # python3
from .logger import logger
import os, shutil, multiprocessing, logging
and context from other files:
# Path: astwro/config/logger.py
, which may include functions, classes, or code. Output only the next line. | logger.info('Using astwro conf files (in priority order):\n\t{}'.format( |
Based on the snippet: <|code_start|>
@staff_member_required
def preview(request, content_type_id, object_id):
"""
This is an override for django.views.default.shortcut.
It assumes that get_absolute_url returns an absolute url, so
it does not do any of the very elaborate link checking that shortcut does.
This version adds the language code to the url. (/en/blaat/).
"""
try:
content_type = ContentType.objects.get(pk=content_type_id)
obj = content_type.get_object_for_this_type(pk=object_id)
except ObjectDoesNotExist:
raise http.Http404("Content type %s object %s doesn't exist" % (content_type_id, object_id))
try:
absolute_url = obj.get_absolute_url()
except AttributeError:
raise http.Http404("%s objects don't have get_absolute_url() methods" % content_type.name)
if absolute_url.startswith('http://') or absolute_url.startswith('https://'):
http.HttpResponseRedirect(absolute_url)
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from django import http
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from easymode.utils.languagecode import fix_language_code
and context (classes, functions, sometimes code) from other files:
# Path: easymode/utils/languagecode.py
# def fix_language_code(url, current_language):
# """
# Fixes the language code as follows:
#
# If there is only one language used in the site, it strips the language code.
# If there are more languages used, it will make sure that the url has the current
# language as a prefix.
#
# >>> # multiple languages defined
# >>> settings.LANGUAGES = (('en-us','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> settings.USE_SHORT_LANGUAGE_CODES = False
# >>> activate('en-us')
# >>> fix_language_code('/de/example.html', 'en-us')
# '/en-us/example.html'
# >>> settings.USE_SHORT_LANGUAGE_CODES = True
# >>> fix_language_code('/de/example.html', 'en-us')
# '/en/example.html'
# >>> fix_language_code('/en/example.html', 'en-us')
# '/example.html'
# >>> # only one language defined
# >>> settings.LANGUAGES = (('en-us', 'English'), )
# >>> fix_language_code('/en-us/example.html', 'en-us')
# '/example.html'
#
# :param url: The (absolute) url to be fixed eg. '/hi/how/is/it'.
# :param current_language: A language code defined in ``settings.LANGUAGES``.
# :rtype: The fixed url.
# """
# stripped_url = strip_language_code(url)
# if not getattr(settings, 'MASTER_SITE', False) and len(settings.LANGUAGES) == 1:
# # no MASTER_SITE and only one language, do not add language code to url
# return stripped_url
#
# # add the language code to the url
# return u"/%s%s" % (get_shorthand_from_language_code(current_language), stripped_url)
. Output only the next line. | absolute_url = fix_language_code(absolute_url, request.LANGUAGE_CODE) |
Here is a snippet: <|code_start|>
__all__ = ('TestSafeFields',)
@initdb
class TestSafeFields(TestCase):
"Test for fields that strip cariage returns."
fixtures = ['auth-user', 'tests-testl10nmodel']
def test_safe_fields_strip_cariage_returns(self):
"Safe fields should strip cariage returns from the input"
h = {
'title': "Ik ben de groot moeftie van oeral",
'description': "Ik weet\r weinig tot niks van brei \rcursussen",
'body':"Het zou kunnen dat\r linksaf\r slaan hier een goede keuze is.",
'price':34.0,
}
if self.client.login(username='admin', password='admin'):
add_view_url = reverse("admin:tests_testl10nmodel_add")
response = self.client.post(add_view_url, h)
<|code_end|>
. Write the next line using the current file imports:
from django.core.urlresolvers import reverse
from django.test import TestCase
from easymode.tests.models import TestL10nModel
from easymode.tests.testcases import initdb
and context from other files:
# Path: easymode/tests/models.py
# class TestL10nModel(models.Model):
# """
# Used in easymode.tests.testcases.testi18n.Testi18n and
# easymode.tests.testcases.testsafefields.TestSafeFields.
# """
# title = models.CharField(max_length=200)
# description = SafeTextField()
# body = SafeHTMLField(default='hi i am an error')
# price = models.FloatField()
#
# def __unicode__(self):
# return u"%s%s" % (self.__class__.__name__, self.pk)
, which may include functions, classes, or code. Output only the next line. | i = TestL10nModel.objects.get(pk=3) |
Here is a snippet: <|code_start|>
__all__ = ('LinkInline', 'LinkedItemAdmin')
class LinkInline(admin.StackedInline):
"""
A base class for an admin inline that will render as links to the change_view.
This means you have to also register the model you are inlining with a non-inline
ModelAdmin::
class BottomAdmin(InvisibleModelAdmin):
parent_link = 'top'
class BottomLinkInline(LinkInline):
fields = ('top',)
model = BottomModel
.. attribute:: fields
It is mandatory to set the fields or fieldsets attribute of a class extending
``LinkInline``. If you don't, all the fields will be show, instead of only
the change or add button. Ofcourse it can't hurt to add some ``read_only_fields``
to add some context.
"""
formset = RecursiveInlineFormSet
template = 'tree/admin/edit_inline/link_inline.html'
extra = 1
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.http import HttpResponseRedirect
from easymode.tree.admin.forms import RecursiveInlineFormSet
from easymode.tree.admin.relation import _CanFindParentLink
and context from other files:
# Path: easymode/tree/admin/relation.py
# class _CanFindParentLink(object):
# """Adds function to find a link to a parent model"""
#
# def _get_parent_link(self, object_id):
# parent_link_data = {}
# if hasattr(self, 'parent_link'):
# parent_link = getattr(self.model, self.parent_link)
# instance = self.model.objects.get(pk=object_id)
#
# parent = parent_link.__get__(instance)
# parent_type_name = parent._meta.object_name.lower()
# parent_name = parent
# parent_id = str(parent_link.field.value_from_object(instance))
#
# info = (self.admin_site.name, parent._meta.app_label, parent_type_name)
#
# parent_link_data['parent_model'] = strip_language_code(urlresolvers.reverse("%s:%s_%s_change" % info, args=[parent_id]))
# parent_link_data['parent_name'] = "%s %s" % (force_unicode(parent._meta.verbose_name), parent_name)
#
# return parent_link_data
, which may include functions, classes, or code. Output only the next line. | class LinkedItemAdmin(admin.ModelAdmin, _CanFindParentLink): |
Predict the next line after this snippet: <|code_start|>
register = template.Library()
@register.filter
@stringfilter
def strip_locale(url):
"""Strip the language code from the beginning of a string"""
<|code_end|>
using the current file's imports:
from django.template.defaultfilters import stringfilter
from django import template
from easymode.utils import languagecode
and any relevant context from other files:
# Path: easymode/utils/languagecode.py
# USE_SHORT_LANGUAGE_CODES = getattr(settings, 'USE_SHORT_LANGUAGE_CODES', False)
# STRIP_LANGUAGE_CODE_REGEX = re.compile(ur'/(?:%s)/' % "|".join(get_short_language_codes()))
# STRIP_LANGUAGE_CODE_REGEX = re.compile(ur'/(?:%s)/' % "|".join(get_language_codes()))
# def get_language_codes():
# def get_short_language_codes():
# def get_all_language_codes():
# def get_shorthand_from_language_code(locale):
# def get_language_code_from_shorthand(short_locale):
# def strip_language_code(url):
# def fix_language_code(url, current_language):
# def get_real_fieldname(field, lang):
# def localize_fieldnames(fields, internationalized_fields):
# def get_language_codes_as_disjunction():
. Output only the next line. | return languagecode.strip_language_code(url) |
Here is a snippet: <|code_start|>
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
if 'Content-Language' not in response:
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
class LocaliseUrlsMiddleware(object):
"""
This middleware replaces all anchor tags with localised versions, ugly
but it works.
Don't put any vary header for the Accept-Language because the language does
not depend on the vary header, the language is in the url.
"""
def process_response(self, request, response):
translation.deactivate()
path = unicode(request.path)
if not path.startswith(settings.MEDIA_URL) and \
not path.startswith(settings.ADMIN_MEDIA_PREFIX) and \
response.status_code == 200 and \
response._headers['content-type'][1].split(';')[0] == "text/html":
response.content = HREF_REGEX.sub(
<|code_end|>
. Write the next line using the current file imports:
import re
import time
from django.conf import settings
from django.contrib.sessions.middleware import SessionMiddleware
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
from django.utils.http import cookie_date
from easymode.utils.languagecode import get_short_language_codes,\
get_language_code_from_shorthand,\
get_shorthand_from_language_code as language_as_slug
and context from other files:
# Path: easymode/utils/languagecode.py
# def get_short_language_codes():
# """
# Retrieves the short versions of the language codes defined in settings.LANGUAGES.
#
# >>> from django.conf import settings
# >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> sorted( get_short_language_codes() )
# ['de', 'en', 'fr', 'nl']
#
# :rtype: A :class:`list` of short versions of the language codes.
# """
# languages = set([lang[:2] for lang in get_language_codes()])
# return list(languages)
#
# def get_language_code_from_shorthand(short_locale):
# """
# Returns the real language_code based on the shorthand.
#
# >>> settings.LANGUAGES = (('en-us','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> get_language_code_from_shorthand('en')
# 'en-us'
#
# :param short_locale: The short version of a language code.
# :rtype: The long version of the language code.
# """
# for locale in get_language_codes():
# if locale[:2] == short_locale:
# return locale
# return settings.LANGUAGE_CODE
#
# def get_shorthand_from_language_code(locale):
# """
# Returns the shorthand, based on the language code.
#
# If USE_SHORT_LANGUAGE_CODES is true it will return a
# ahorthand, if it is False, it will not modify the code
# at all.
#
# >>> USE_SHORT_LANGUAGE_CODES = True
# >>> get_shorthand_from_language_code('en-us')
# 'en'
# >>> USE_SHORT_LANGUAGE_CODES = False
# >>> get_shorthand_from_language_code('en-us')
# 'en-us'
#
# :param locale: The language code as a :class:`unicode` string.
# :rtype: The short version of the language code (when appropriate).
# """
# if USE_SHORT_LANGUAGE_CODES:
# return locale[:2]
#
# return locale
, which may include functions, classes, or code. Output only the next line. | ur'<a\1href="/%s/\3"\4>' % language_as_slug(request.LANGUAGE_CODE), |
Predict the next line after this snippet: <|code_start|> 5. accepts tinymce configuration options.
usage::
html = SafeHTMLField(_('some rich text'), max_length=200, width=300, height=100, buttons="link,unlink,code")
:param max_length: The maximum length of the text, after stripping markup and
converting html entities to normal characters.
:param width: The width of the html editor in the admin
:param height: The height of the html editor in the admin
:param buttons: Configuration for the
`theme_advanced_buttons1 <http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/theme_advanced_buttons_1_n>`_.
The default is "bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat".
"""
_south_introspects = True
def __init__(self, *args, **kwargs):
mce_config = DEFAULT_MCE_CONFIG or \
"bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat"
self.mce_width = kwargs.pop('width', 340)
self.mce_height = kwargs.pop('height', 160)
self.buttons = kwargs.pop('buttons', mce_config)
super(SafeHTMLField, self).__init__(*args, **kwargs)
def __serialize__(self, obj, xml):
richtext = self.value_to_string(obj)
value = u"<richtext>%s</richtext>" % richtext
<|code_end|>
using the current file's imports:
import logging
import os
import re
import warnings
import tinymce
from StringIO import StringIO
from time import time
from urllib import urlopen
from xml import sax
from django.conf import settings
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget
from django.db import connection, models
from django.db.models import CharField, TextField
from django.forms import fields
from django.utils.datastructures import DictWrapper
from django.utils.translation import ugettext_lazy as _
from tinymce.widgets import TinyMCE
from easymode.admin.forms import fields as form_fields
from easymode.utils import xmlutils
and any relevant context from other files:
# Path: easymode/utils/xmlutils.py
# def _unicode_for_entity_with_name(name):
# def unescape_all(string):
# def escape_single(matchobj):
# def is_valid(xml_string):
# def __init__(self, *args, **kwargs):
# def resolveEntity(self, publicId, systemId):
# def reset(self):
# def skippedEntity(self, name):
# def create_parser(*args, **kwargs):
# class XmlScanner(ExpatParser):
# class _NiftyEntityResolver(EntityResolver):
# class XmlPrinter(SimplerXMLGenerator):
. Output only the next line. | if xmlutils.is_valid(value): |
Using the snippet: <|code_start|>
__all__ = ('TestLocaliseUrlsMiddleware', 'TestLocaleFromUrlMiddleWare')
@decorator_from_middleware(middleware.LocaliseUrlsMiddleware)
def localise_urls_middleware_view(request):
return HttpResponse("""
<a href="/example/modifyme.html">hhh</a>
<a href="/en/example/staysthesame.html">hhh</a>
<a href="/xx/notareallangugaecode.html"/>
<a href="/de/reallanguagecode.html"/>
""")
@initdb
class TestLocaliseUrlsMiddleware(TestCase):
"""Test the middlewares that come with easymode"""
def tearDown(self):
self.settingsManager.revert()
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from django.utils.decorators import decorator_from_middleware
from easymode import middleware
from easymode.tests.testcases import initdb
from easymode.utils import languagecode
and context (class names, function names, or code) available:
# Path: easymode/middleware.py
# USE_SHORT_LANGUAGE_CODES = getattr(settings, 'USE_SHORT_LANGUAGE_CODES', False)
# MATCH_LANGUAGE_CODE = re.compile(
# r"^/(%s)/.*" % "|".join(map(lambda l: l[0], settings.LANGUAGES)))
# MATCH_SHORT_LANGUAGE_CODE = re.compile(
# r"^/(%s)/.*" % "|".join(get_short_language_codes()))
# HREF_REGEX = re.compile(
# ur'<a([^>]+)href="/(?!(%s|%s|%s))([^"]*)"([^>]*)>' % (
# "|".join(map(lambda l: l + "/" , get_short_language_codes())),
# settings.MEDIA_URL[1:],
# settings.ADMIN_MEDIA_PREFIX[1:]
# )
# )
# FORM_REGEX = re.compile(
# ur'<form([^>]+)action="/(?!(%s|%s|%s))([^"]*)"([^>]*)>' % (
# "|".join(map(lambda l: l + "/" , get_short_language_codes())),
# settings.MEDIA_URL[1:],
# settings.ADMIN_MEDIA_PREFIX[1:]
# )
# )
# HREF_REGEX = re.compile(
# ur'<a([^>]+)href="/(?!(%s|%s|%s))([^"]*)"([^>]*)>' % (
# "|".join(map(lambda l: l[0] + "/" , settings.LANGUAGES)),
# settings.MEDIA_URL[1:],
# settings.ADMIN_MEDIA_PREFIX[1:]
# )
# )
# FORM_REGEX = re.compile(
# ur'<form([^>]+)action="/(?!(%s|%s|%s))([^"]*)"([^>]*)>' % (
# "|".join(map(lambda l: l[0] + "/" , settings.LANGUAGES)),
# settings.MEDIA_URL[1:],
# settings.ADMIN_MEDIA_PREFIX[1:]
# )
# )
# def has_lang_prefix(path):
# def process_response(self, request, response):
# def process_request(self, request):
# def process_response(self, request, response):
# def process_response(self, request, response):
# def process_request(self, request):
# def process_response(self, request, response):
# class NoVaryOnCookieSessionMiddleWare(SessionMiddleware):
# class LocaleFromUrlMiddleWare(LocaleMiddleware):
# class LocaliseUrlsMiddleware(object):
# class ShortLocaleFromUrlMiddleWare(LocaleFromUrlMiddleWare):
# class ShortLocaleLocaliseUrlsMiddleware(LocaliseUrlsMiddleware):
#
# Path: easymode/utils/languagecode.py
# USE_SHORT_LANGUAGE_CODES = getattr(settings, 'USE_SHORT_LANGUAGE_CODES', False)
# STRIP_LANGUAGE_CODE_REGEX = re.compile(ur'/(?:%s)/' % "|".join(get_short_language_codes()))
# STRIP_LANGUAGE_CODE_REGEX = re.compile(ur'/(?:%s)/' % "|".join(get_language_codes()))
# def get_language_codes():
# def get_short_language_codes():
# def get_all_language_codes():
# def get_shorthand_from_language_code(locale):
# def get_language_code_from_shorthand(short_locale):
# def strip_language_code(url):
# def fix_language_code(url, current_language):
# def get_real_fieldname(field, lang):
# def localize_fieldnames(fields, internationalized_fields):
# def get_language_codes_as_disjunction():
. Output only the next line. | reload(languagecode) |
Continue the code snippet: <|code_start|> "adding a bottom model should make it appear in inlines"
if self.client.login(username='admin', password='admin'):
top_url = reverse('admin:tests_topmodel_change', args=[1])
response = self.client.get(top_url)
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'Chicken is good')
bottom_url = reverse('admin:tests_bottommodel_add')
data = {
'top':1,
'comment':'Chicken is good',
}
response = self.client.post(bottom_url, data)
self.assertEqual(response.status_code, 302)
response = self.client.get(top_url)
self.assertContains(response, 'Chicken is good')
else:
self.fail('Can not log in with admin:admin')
def test_the_plus_button_goes_to_the_correct_add_view(self):
"There should be a plus button for the inline group that goes to the correct add view"
if self.client.login(username='admin', password='admin'):
top_url = reverse('admin:tests_topmodel_change', args=[1])
response = self.client.get(top_url)
self.assertEqual(response.status_code, 200)
#/en/admin/tests/bottommodel/add/?top=1
add_url = "%s?top=1" % reverse('admin:tests_bottommodel_add')
<|code_end|>
. Use current file imports:
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils.translation import get_language, activate
from easymode.tests.testcases import initdb
from easymode.utils.languagecode import fix_language_code
and context (classes, functions, or code) from other files:
# Path: easymode/utils/languagecode.py
# def fix_language_code(url, current_language):
# """
# Fixes the language code as follows:
#
# If there is only one language used in the site, it strips the language code.
# If there are more languages used, it will make sure that the url has the current
# language as a prefix.
#
# >>> # multiple languages defined
# >>> settings.LANGUAGES = (('en-us','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> settings.USE_SHORT_LANGUAGE_CODES = False
# >>> activate('en-us')
# >>> fix_language_code('/de/example.html', 'en-us')
# '/en-us/example.html'
# >>> settings.USE_SHORT_LANGUAGE_CODES = True
# >>> fix_language_code('/de/example.html', 'en-us')
# '/en/example.html'
# >>> fix_language_code('/en/example.html', 'en-us')
# '/example.html'
# >>> # only one language defined
# >>> settings.LANGUAGES = (('en-us', 'English'), )
# >>> fix_language_code('/en-us/example.html', 'en-us')
# '/example.html'
#
# :param url: The (absolute) url to be fixed eg. '/hi/how/is/it'.
# :param current_language: A language code defined in ``settings.LANGUAGES``.
# :rtype: The fixed url.
# """
# stripped_url = strip_language_code(url)
# if not getattr(settings, 'MASTER_SITE', False) and len(settings.LANGUAGES) == 1:
# # no MASTER_SITE and only one language, do not add language code to url
# return stripped_url
#
# # add the language code to the url
# return u"/%s%s" % (get_shorthand_from_language_code(current_language), stripped_url)
. Output only the next line. | localized_add_url = fix_language_code(add_url, get_language()) |
Given the code snippet: <|code_start|> will copy the en fields into the de locale for myapp.mymodel
"""
class Command(BaseCommand):
help = __doc__
def handle(self, source, target, app=None, **options):
""" command execution """
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
models = get_models()
for model in models:
if hasattr(model, 'localized_fields'):
model_full_name = '%s.%s' % (model._meta.app_label, model._meta.module_name)
update_instances = set()
messages = []
for instance in model.objects.all():
for field in model.localized_fields:
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import get_models, get_app, get_model
from django.utils import translation
from django.utils.encoding import force_unicode
from easymode.utils.languagecode import get_real_fieldname
and context (functions, classes, or occasionally code) from other files:
# Path: easymode/utils/languagecode.py
# def get_real_fieldname(field, lang):
# """
# Depending on the language a field can have a different name.
#
# If you want to do a query, using a localized field, you have
# to use the name this function returns, not the default name.
#
# >>> get_real_fieldname('name', 'en-us')
# 'name_en_us'
#
# Usage::
#
# def index(request):
# published_in_language = get_real_fieldname('published', request.LANGUAGE_CODE)
# qs = SomeModel.objects.filter(**{published_in_language:True})
# return render_to_response('index.html', {'queryset':qs})
#
#
# :param field: The name of a field in an internationalised model.
# :param lang: The language for which you want to know the real name.
# :rtype: The actual name of the ``field`` in the ``lang``.
# """
# return str('%s_%s' % (field, to_locale(lang).lower()))
. Output only the next line. | source_field = get_real_fieldname(field, source) |
Next line prediction: <|code_start|>
if 'en-us' not in get_language_codes():
raise Exception('the language "en-us" must be in your LANGUAGES to run the test suite')
__all__ = ('XsltTest',)
@initdb
class XsltTest(TestCase):
"""
Test the functionality related to xslt
"""
def setUp(self):
<|code_end|>
. Use current file imports:
(from django.http import HttpResponse
from django.template.loader import find_template_source
from django.test import TestCase
from easymode.tree import xml as tree
from easymode.tests.models import TestModel
from easymode.tests.testcases import initdb
from easymode.utils.languagecode import get_language_codes
from easymode.xslt import response)
and context including class names, function names, or small code snippets from other files:
# Path: easymode/tests/models.py
# class TestModel(models.Model):
# "Used in lots of test"
#
# charfield = models.CharField(max_length=255, unique=True)
# tags = models.ManyToManyField('TagModel', related_name='testmodels')
#
# def __unicode__(self):
# return u"%s%s - %s" % (self.__class__.__name__, self.pk, self.charfield)
#
# def natural_key(self):
# return (self.charfield,)
#
# Path: easymode/utils/languagecode.py
# def get_language_codes():
# """
# Retrieves all the language codes defined in ``settings.LANGUAGES``.
#
# >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> sorted( get_language_codes() )
# ['de', 'en', 'fr-be', 'nl-be']
#
# :rtype: A :class:`list` of language codes.
# """
# return dict(settings.LANGUAGES).keys()
. Output only the next line. | t = TestModel(charfield='Hoi Ik ben de root node') |
Based on the snippet: <|code_start|>
class TestSubSubModel(models.Model):
"Used in lots of test"
testsubmodel = models.ForeignKey(TestSubModel, related_name="subsubmodels")
subsubcharfield = models.CharField(max_length=255)
def __unicode__(self):
return self.subsubcharfield
@I18n('value')
class TagModel(models.Model):
"Used in test_generic_relations_also_work (easymode.tests.testcases.testtoxml.RecursiveSerializerTest)"
value = models.CharField(max_length=23)
def __serialize__(self, stream):
stream.startElement('taggy', {})
stream.characters(self.value)
stream.endElement('taggy')
@toxml
@I18n('title', 'description')
class TestL10nModel(models.Model):
"""
Used in easymode.tests.testcases.testi18n.Testi18n and
easymode.tests.testcases.testsafefields.TestSafeFields.
"""
title = models.CharField(max_length=200)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from easymode.admin.models.fields import SafeTextField, SafeHTMLField
from easymode.i18n.decorators import I18n
from easymode.tree.xml.decorators import toxml
and context (classes, functions, sometimes code) from other files:
# Path: easymode/admin/models/fields.py
# class SafeTextField(models.TextField):
# """
# Removes all cariage returns from the input.
#
# This class should be used instead of :class:`django.db.models.TextField`, if you
# want to use easymode's gettext facilities. It will strip all cariage returns from
# the input. Cariage returns are an error when included in gettext message id's. It
# also allows you to specify the number of rows and columns of the textarea.
#
# :param rows: The number of rows of the textarea.
# :param cols: The number of columns of the textarea.
# """
#
# _south_introspects = True
#
# def __init__(self, *args, **kwargs):
# self.rows = kwargs.pop('rows', 5)
# self.cols = kwargs.pop('cols', 40)
#
# super(SafeTextField, self).__init__(*args, **kwargs)
#
# def formfield(self, **kwargs):
# defaults = {
# 'widget': AdminTextareaWidget(attrs={'rows':self.rows, 'cols':self.cols}),
# 'form_class': form_fields.PoSafeTextField
# }
# defaults.update(kwargs)
# return super(SafeTextField, self).formfield(**defaults)
#
# class SafeHTMLField(TextField):
# """
# A html field with the following properties:
#
# 1. Escapes cariage returns
# 2. Will render as html, without escaping < and >
# 3. Validates that html and will log errors when invalid html
# is discovered, instead of crash.
# 4. Allows the max_length attribute, the max_length is then computed,
# without counting markup. Also html entities are converted to normal
# characters before measuring the length as well.
# 5. accepts tinymce configuration options.
#
# usage::
#
# html = SafeHTMLField(_('some rich text'), max_length=200, width=300, height=100, buttons="link,unlink,code")
#
# :param max_length: The maximum length of the text, after stripping markup and
# converting html entities to normal characters.
# :param width: The width of the html editor in the admin
# :param height: The height of the html editor in the admin
# :param buttons: Configuration for the
# `theme_advanced_buttons1 <http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/theme_advanced_buttons_1_n>`_.
# The default is "bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat".
# """
# _south_introspects = True
#
# def __init__(self, *args, **kwargs):
# mce_config = DEFAULT_MCE_CONFIG or \
# "bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat"
#
# self.mce_width = kwargs.pop('width', 340)
# self.mce_height = kwargs.pop('height', 160)
# self.buttons = kwargs.pop('buttons', mce_config)
#
# super(SafeHTMLField, self).__init__(*args, **kwargs)
#
# def __serialize__(self, obj, xml):
# richtext = self.value_to_string(obj)
# value = u"<richtext>%s</richtext>" % richtext
#
# if xmlutils.is_valid(value):
# parser = sax.make_parser(["easymode.utils.xmlutils"])
# parser.setContentHandler(xml)
# parser.parse(StringIO(value.encode('utf-8')))
# else:
# logging.error('Invalid xml in %s: %s' % (obj, value))
#
# def formfield(self, **kwargs):
# mce_default_attrs = {
# 'theme_advanced_buttons1' : self.buttons,
# 'theme_advanced_resizing' : True,
# 'width': self.mce_width,
# 'height': self. mce_height,
# }
#
# defaults = {
# 'form_class': form_fields.PoSafeTextField,
# }
#
# # if this thing has a max_length then use a
# # special form field
# if hasattr(self, 'max_length'):
# defaults['form_class'] = form_fields.HtmlEntityField
# defaults['max_length'] = self.max_length
#
# defaults.update(kwargs)
# defaults['widget'] = TinyMCE(mce_attrs=mce_default_attrs)
#
# return super(SafeHTMLField, self).formfield(**defaults)
. Output only the next line. | description = SafeTextField() |
Predict the next line after this snippet: <|code_start|>
class TestSubSubModel(models.Model):
"Used in lots of test"
testsubmodel = models.ForeignKey(TestSubModel, related_name="subsubmodels")
subsubcharfield = models.CharField(max_length=255)
def __unicode__(self):
return self.subsubcharfield
@I18n('value')
class TagModel(models.Model):
"Used in test_generic_relations_also_work (easymode.tests.testcases.testtoxml.RecursiveSerializerTest)"
value = models.CharField(max_length=23)
def __serialize__(self, stream):
stream.startElement('taggy', {})
stream.characters(self.value)
stream.endElement('taggy')
@toxml
@I18n('title', 'description')
class TestL10nModel(models.Model):
"""
Used in easymode.tests.testcases.testi18n.Testi18n and
easymode.tests.testcases.testsafefields.TestSafeFields.
"""
title = models.CharField(max_length=200)
description = SafeTextField()
<|code_end|>
using the current file's imports:
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from easymode.admin.models.fields import SafeTextField, SafeHTMLField
from easymode.i18n.decorators import I18n
from easymode.tree.xml.decorators import toxml
and any relevant context from other files:
# Path: easymode/admin/models/fields.py
# class SafeTextField(models.TextField):
# """
# Removes all cariage returns from the input.
#
# This class should be used instead of :class:`django.db.models.TextField`, if you
# want to use easymode's gettext facilities. It will strip all cariage returns from
# the input. Cariage returns are an error when included in gettext message id's. It
# also allows you to specify the number of rows and columns of the textarea.
#
# :param rows: The number of rows of the textarea.
# :param cols: The number of columns of the textarea.
# """
#
# _south_introspects = True
#
# def __init__(self, *args, **kwargs):
# self.rows = kwargs.pop('rows', 5)
# self.cols = kwargs.pop('cols', 40)
#
# super(SafeTextField, self).__init__(*args, **kwargs)
#
# def formfield(self, **kwargs):
# defaults = {
# 'widget': AdminTextareaWidget(attrs={'rows':self.rows, 'cols':self.cols}),
# 'form_class': form_fields.PoSafeTextField
# }
# defaults.update(kwargs)
# return super(SafeTextField, self).formfield(**defaults)
#
# class SafeHTMLField(TextField):
# """
# A html field with the following properties:
#
# 1. Escapes cariage returns
# 2. Will render as html, without escaping < and >
# 3. Validates that html and will log errors when invalid html
# is discovered, instead of crash.
# 4. Allows the max_length attribute, the max_length is then computed,
# without counting markup. Also html entities are converted to normal
# characters before measuring the length as well.
# 5. accepts tinymce configuration options.
#
# usage::
#
# html = SafeHTMLField(_('some rich text'), max_length=200, width=300, height=100, buttons="link,unlink,code")
#
# :param max_length: The maximum length of the text, after stripping markup and
# converting html entities to normal characters.
# :param width: The width of the html editor in the admin
# :param height: The height of the html editor in the admin
# :param buttons: Configuration for the
# `theme_advanced_buttons1 <http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/theme_advanced_buttons_1_n>`_.
# The default is "bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat".
# """
# _south_introspects = True
#
# def __init__(self, *args, **kwargs):
# mce_config = DEFAULT_MCE_CONFIG or \
# "bullist,numlist,|,undo,redo,|,link,unlink,|,code,|,cleanup,removeformat"
#
# self.mce_width = kwargs.pop('width', 340)
# self.mce_height = kwargs.pop('height', 160)
# self.buttons = kwargs.pop('buttons', mce_config)
#
# super(SafeHTMLField, self).__init__(*args, **kwargs)
#
# def __serialize__(self, obj, xml):
# richtext = self.value_to_string(obj)
# value = u"<richtext>%s</richtext>" % richtext
#
# if xmlutils.is_valid(value):
# parser = sax.make_parser(["easymode.utils.xmlutils"])
# parser.setContentHandler(xml)
# parser.parse(StringIO(value.encode('utf-8')))
# else:
# logging.error('Invalid xml in %s: %s' % (obj, value))
#
# def formfield(self, **kwargs):
# mce_default_attrs = {
# 'theme_advanced_buttons1' : self.buttons,
# 'theme_advanced_resizing' : True,
# 'width': self.mce_width,
# 'height': self. mce_height,
# }
#
# defaults = {
# 'form_class': form_fields.PoSafeTextField,
# }
#
# # if this thing has a max_length then use a
# # special form field
# if hasattr(self, 'max_length'):
# defaults['form_class'] = form_fields.HtmlEntityField
# defaults['max_length'] = self.max_length
#
# defaults.update(kwargs)
# defaults['widget'] = TinyMCE(mce_attrs=mce_default_attrs)
#
# return super(SafeHTMLField, self).formfield(**defaults)
. Output only the next line. | body = SafeHTMLField(default='hi i am an error') |
Here is a snippet: <|code_start|>"""
Contains a modeladmin class that shows links to all related items in its change_view.
If you want to use :class:`InvisibleModelAdmin` make sure easymode comes before
``django.contrib.admin`` in the ``INSTALLED_APPS`` because it has to
override admin/index.html to make it work.
"""
if 'reversion' in settings.INSTALLED_APPS:
AdminBase = VersionAdmin
else:
AdminBase = admin.ModelAdmin
class _CanFindParentLink(object):
"""Adds function to find a link to a parent model"""
def _get_parent_link(self, object_id):
parent_link_data = {}
if hasattr(self, 'parent_link'):
parent_link = getattr(self.model, self.parent_link)
instance = self.model.objects.get(pk=object_id)
parent = parent_link.__get__(instance)
parent_type_name = parent._meta.object_name.lower()
parent_name = parent
parent_id = str(parent_link.field.value_from_object(instance))
info = (self.admin_site.name, parent._meta.app_label, parent_type_name)
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponseRedirect
from django.forms.models import modelformset_factory
from django.core import urlresolvers
from django.conf import settings
from django.utils.encoding import force_unicode
from easymode.tree.introspection import get_foreign_key_desciptors
from easymode.tree.admin.formsets import VisiblePrimaryKeyFormset
from easymode.utils.languagecode import strip_language_code
from reversion.admin import VersionAdmin
from django.contrib import admin
and context from other files:
# Path: easymode/utils/languagecode.py
# def strip_language_code(url):
# """
# Strip the language code from the beginning of string
#
# >>> strip_language_code('http://example.com/en/example.html')
# 'http://example.com/example.html'
#
# :param url: An url.
# :rtype: The ``url`` but the language code is removed.
# """
# return STRIP_LANGUAGE_CODE_REGEX.sub('/',url, 1)
, which may include functions, classes, or code. Output only the next line. | parent_link_data['parent_model'] = strip_language_code(urlresolvers.reverse("%s:%s_%s_change" % info, args=[parent_id])) |
Given the following code snippet before the placeholder: <|code_start|>"""
Contains widgets that can be used for admin models
with related items.
"""
__all__ = ('RenderLink', 'LinkWidget')
class RenderLink(forms.Widget):
"""
Renders a link to an admin page based on the primary key
value of the model.
"""
input_type = None
def _has_changed(self, initial, data):
return False
def id_for_label(self, id_):
return "hmm geen idee"
def render(self, name, value, attrs=None):
modelname = self.attrs['modelname']
app_label = self.attrs['app_label']
label = self.attrs['label']
url_pattern = '%s:%s_%s_change' % ('admin', app_label, modelname)
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from django.conf import settings
from django.core import urlresolvers
from django.forms import widgets
from django.template.loader import render_to_string
from django.utils.encoding import force_unicode
from django.utils.html import mark_safe
from django.utils.translation import ugettext
from easymode.utils.languagecode import strip_language_code
and context including class names, function names, and sometimes code from other files:
# Path: easymode/utils/languagecode.py
# def strip_language_code(url):
# """
# Strip the language code from the beginning of string
#
# >>> strip_language_code('http://example.com/en/example.html')
# 'http://example.com/example.html'
#
# :param url: An url.
# :rtype: The ``url`` but the language code is removed.
# """
# return STRIP_LANGUAGE_CODE_REGEX.sub('/',url, 1)
. Output only the next line. | url = strip_language_code(urlresolvers.reverse(url_pattern, args=[value])) |
Next line prediction: <|code_start|>"""
When ``get_absolute_url`` is defined on a model, django will place a
*view on site* link in the ``change_view`` of the model.
If you are using easymode's multilanguage features and especially
:class:`~easymode.middleware.LocaleFromUrlMiddleWare` and
:class:`~easymode.middleware.LocaliseUrlsMiddleware` you will find that the
*view on site* link will not point to the correct (current) language.
The routes specified here will override the default admin routes and
make the *view on site* link take the current language into account.
include the urls in your urlconf like this::
(r'^', include('easymode.urls')),
"""
try:
# before 1.6
except:
# 1.6 and later
<|code_end|>
. Use current file imports:
( from django.conf.urls.defaults import *
from django.conf.urls import *
from easymode.utils.languagecode import get_language_codes_as_disjunction)
and context including class names, function names, or small code snippets from other files:
# Path: easymode/utils/languagecode.py
# def get_language_codes_as_disjunction():
# """
# return a pattern that matches any language defined in ``settings.LANGUAGES``
#
# >>> from django.conf import settings
# >>> settings.USE_SHORT_LANGUAGE_CODES = False
# >>> settings.LANGUAGES = (('en-us','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> get_language_codes_as_disjunction()
# 'de|en-us|nl-be|fr-be'
#
# usage::
#
# languages = get_language_codes_as_disjunction()
# urlpatterns = patterns('',
# url(r'^(%{languages})/admin/' % locals(), include(admin.site.urls), name="language-admin"),
# )
#
# """
# language_codes = map(get_shorthand_from_language_code, get_language_codes())
# languages = "|".join(language_codes)
# return languages
. Output only the next line. | languages = get_language_codes_as_disjunction() |
Continue the code snippet: <|code_start|>"""
Contains an instance of Serializer and extends it to allow for recusive
serialization of django models with foreign keys.
"""
MANY_TO_MANY_RECURSION_LIMIT_ERROR = """
Deep recursion in easymode.tree.xml.serializers.RecursiveXmlSerializer:
Serializer found ManyToManyField named: %s from %s to %s.
You probably built a cycle in your model tree using many to many relations.
Please inspect the stack trace and try to fix the problem.
If you are sure these is no cycle and you just have lots and lots of models
with a gigantic deep tree, you can also try to set settings.RECURSION_LIMIT to
a value greater then 100.
"""
# startDocument must only be called once
# so override it
def startDocumentOnlyOnce(self):
if hasattr(self, 'allready_called'):
return
self.allready_called = True
<|code_end|>
. Use current file imports:
import sys
from StringIO import StringIO
from django.conf import settings
from django.core.serializers import xml_serializer
from django.utils.encoding import smart_unicode, force_unicode
from easymode.tree.introspection import get_default_field_descriptors, \
get_foreign_key_desciptors, get_generic_relation_descriptors
from easymode.utils import recursion_depth
from easymode.utils.xmlutils import XmlPrinter
and context (classes, functions, or code) from other files:
# Path: easymode/utils/xmlutils.py
# class XmlPrinter(SimplerXMLGenerator):
# """
# XmlPrinter can be used as a contenthandler for the
# :class:`~easymode.utils.xmlutils.XmlScanner`.
#
# It will convert all skippedEntities to their unicode characters
# and copy these to the output stream.
#
# You can use it as a simple xml generator, to create xml::
#
# stream = StringIO.StringIO()
# xml = XmlPrinter(stream, settings.DEFAULT_CHARSET)
#
# def _render_page(page):
# xml.startElement('title', {})
# xml.characters(page.title)
# xml.endElement('title')
# xml.startElement('template', {})
# xml.characters(page.template)
# xml.endElement('template')
#
# for child in Page.children.all():
# xml.startElement('page', {})
# _render_page(child)
# xml.endElement('page')
# """
# def skippedEntity(self, name):
# self._out.write(_unicode_for_entity_with_name(name).encode('utf-8'))
. Output only the next line. | XmlPrinter.startDocument(self) |
Given the code snippet: <|code_start|>"""
utility functions used by easymode's i18n.meta package to get localized attributes
from a class.
"""
def valid_for_gettext(value):
"""Gettext acts weird when empty string is passes, and passing none would be even weirder"""
return value not in (None, "")
def get_fallback_languages():
"""Retrieve the fallback languages from the settings.py"""
lang = translation.get_language()
fallback_list = settings.FALLBACK_LANGUAGES.get(lang, None)
if fallback_list:
return fallback_list
return settings.FALLBACK_LANGUAGES.get(lang[:2], [])
def get_localized_property(context, field=None, language=None):
'''
When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned.
'''
if language:
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.utils import translation
from easymode.utils import first_match
from easymode.utils.languagecode import get_real_fieldname
from easymode.utils import first_match
and context (functions, classes, or occasionally code) from other files:
# Path: easymode/utils/languagecode.py
# def get_real_fieldname(field, lang):
# """
# Depending on the language a field can have a different name.
#
# If you want to do a query, using a localized field, you have
# to use the name this function returns, not the default name.
#
# >>> get_real_fieldname('name', 'en-us')
# 'name_en_us'
#
# Usage::
#
# def index(request):
# published_in_language = get_real_fieldname('published', request.LANGUAGE_CODE)
# qs = SomeModel.objects.filter(**{published_in_language:True})
# return render_to_response('index.html', {'queryset':qs})
#
#
# :param field: The name of a field in an internationalised model.
# :param lang: The language for which you want to know the real name.
# :rtype: The actual name of the ``field`` in the ``lang``.
# """
# return str('%s_%s' % (field, to_locale(lang).lower()))
. Output only the next line. | return getattr(context, get_real_fieldname(field, language)) |
Using the snippet: <|code_start|> self.location = (hasattr(settings, 'LOCALE_DIR') and \
settings.LOCALE_DIR) or settings.PROJECT_DIR
elif os.path.isdir(location) is False and os.path.exists(location):
self.location = os.path.dirname(location)
else:
self.location = location
self.sender = sender
def __call__(self, instance, sender=None, **kwargs):
"""
Handler for the post_save signal.
Will create a django.po file in each language,
in the directory specified by self.location.
"""
# no need to create translation files if not in the master site
if not getattr(settings, 'MASTER_SITE', False):
return
if hasattr(instance, 'language') and instance.language != settings.LANGUAGE_CODE:
return
if get_language() != settings.LANGUAGE_CODE:
return
po_form = self.poify(instance)
if po_form is not None:
# for each language create a po file
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import subprocess
import codecs
import logging
import StringIO
import unicodedata
import easymode.tree.introspection
import polib
from datetime import datetime
from django.conf import settings
from django.core.management.base import CommandError
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import templatize, to_locale, get_language
from django.utils.timezone import tzinfo
from django.utils import tzinfo
from django.template.loader import render_to_string
from easymode.utils import mutex
from easymode.utils.languagecode import get_language_codes
from easymode.utils import polibext
and context (class names, function names, or code) available:
# Path: easymode/utils/languagecode.py
# def get_language_codes():
# """
# Retrieves all the language codes defined in ``settings.LANGUAGES``.
#
# >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> sorted( get_language_codes() )
# ['de', 'en', 'fr-be', 'nl-be']
#
# :rtype: A :class:`list` of language codes.
# """
# return dict(settings.LANGUAGES).keys()
#
# Path: easymode/utils/polibext.py
# def po_to_unicode(po_obj):
# def __init__(self, stream, fpath=None, encoding='utf-8', wrapwidth=78):
# class PoStream(polib._POFileParser):
. Output only the next line. | for language in get_language_codes(): |
Based on the snippet: <|code_start|> return
if hasattr(instance, 'language') and instance.language != settings.LANGUAGE_CODE:
return
if get_language() != settings.LANGUAGE_CODE:
return
po_form = self.poify(instance)
if po_form is not None:
# for each language create a po file
for language in get_language_codes():
locale_dir = os.path.join( self.location , 'locale',
to_locale(language), 'LC_MESSAGES')
locale_file = os.path.join( locale_dir, 'django.po')
# create locale dir if not available
if not os.path.isdir(locale_dir):
os.makedirs(locale_dir)
# acquire exclusive lock this should only be run
# by one process at a time
with mutex(max_wait=30):
# write proper header if the file is new
# this header contains the character set.
write_header = not os.path.exists(locale_file)
if write_header: # write header and po stuffz0r
with codecs.open(locale_file, 'w', 'utf-8') as fp:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import subprocess
import codecs
import logging
import StringIO
import unicodedata
import easymode.tree.introspection
import polib
from datetime import datetime
from django.conf import settings
from django.core.management.base import CommandError
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import templatize, to_locale, get_language
from django.utils.timezone import tzinfo
from django.utils import tzinfo
from django.template.loader import render_to_string
from easymode.utils import mutex
from easymode.utils.languagecode import get_language_codes
from easymode.utils import polibext
and context (classes, functions, sometimes code) from other files:
# Path: easymode/utils/languagecode.py
# def get_language_codes():
# """
# Retrieves all the language codes defined in ``settings.LANGUAGES``.
#
# >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
# >>> sorted( get_language_codes() )
# ['de', 'en', 'fr-be', 'nl-be']
#
# :rtype: A :class:`list` of language codes.
# """
# return dict(settings.LANGUAGES).keys()
#
# Path: easymode/utils/polibext.py
# def po_to_unicode(po_obj):
# def __init__(self, stream, fpath=None, encoding='utf-8', wrapwidth=78):
# class PoStream(polib._POFileParser):
. Output only the next line. | fp.write(polibext.po_to_unicode(po_form)) |
Continue the code snippet: <|code_start|> )
launched_by = serializers.SlugRelatedField(
read_only=True,
slug_field='username'
)
class Meta:
model = PlaybookRunHistory
fields = ('url', 'playbook', 'date_launched', 'date_finished', 'status', 'task_id', 'launched_by', 'log_url')
class FilteredHistorySerializer(serializers.ListSerializer):
def to_representation(self, data):
data = data.order_by('-date_launched')[:10]
return super(FilteredHistorySerializer, self).to_representation(data)
class PlaybookRunHistoryLastSerializer(PlaybookRunHistorySerializer):
class Meta:
model = PlaybookRunHistory
list_serializer_class = FilteredHistorySerializer
class PlaybookSerializer(serializers.HyperlinkedModelSerializer):
group = GroupSerializerNoValidator(many=False, required=True)
history = PlaybookRunHistoryLastSerializer(many=True, read_only=True)
class Meta:
<|code_end|>
. Use current file imports:
from .models import Playbook, PlaybookRunHistory
from django.contrib.auth.models import Group
from rest_framework import serializers
from ..Cyclosible.serializers import GroupSerializerNoValidator
from django.core.exceptions import ObjectDoesNotExist
and context (classes, functions, or code) from other files:
# Path: cyclosible/playbook/models.py
# class Playbook(models.Model):
# class Meta:
# app_label = 'playbook'
# permissions = (
# ("view_playbook", "Can view the playbook"),
# ("can_override_skip_tags", 'Can override skip_tags'),
# ("can_override_only_tags", 'Can override only_tags'),
# ("can_override_extra_vars", 'Can override extra_vars'),
# ("can_override_subset", 'Can override subset'),
# ("can_run_playbook", 'Can run the playbook')
# )
#
# name = models.CharField(max_length=100, unique=True, db_index=True)
# only_tags = models.CharField(max_length=1024, default='', blank=True)
# skip_tags = models.CharField(max_length=1024, default='', blank=True)
# extra_vars = models.CharField(max_length=1024, default='', blank=True)
# subset = models.CharField(max_length=1024, default='', blank=True)
# group = models.ForeignKey(Group, null=True)
#
# def __unicode__(self):
# return self.name
#
# class PlaybookRunHistory(models.Model):
# class Meta:
# app_label = 'playbook'
#
# STATUS = (
# ('SUCCESS', 'Success'),
# ('RUNNING', 'Running'),
# ('FAILURE', 'Failure'),
# )
#
# playbook = models.ForeignKey(Playbook, db_index=True, related_name='history')
# date_launched = models.DateTimeField(blank=True)
# date_finished = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=1024, default='RUNNING')
# task_id = models.CharField(max_length=1024, default='', blank=True)
# log_url = models.CharField(max_length=1024, default='', blank=True)
# launched_by = models.ForeignKey(User)
#
# Path: cyclosible/Cyclosible/serializers.py
# class GroupSerializerNoValidator(serializers.HyperlinkedModelSerializer):
# name = serializers.SlugField(validators=[])
#
# class Meta:
# model = Group
# lookup_field = 'name'
# fields = ('url', 'name')
# extra_kwargs = {
# 'url': {'lookup_field': 'name'}
# }
. Output only the next line. | model = Playbook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.