Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> self.subscription.disposable = d
d.disposable = self.parent.source.subscribeSafe(self)
return self.subscription
def onNext(self, value):
self.observer.onNext(value)
def onError(self, exception):
if isinstance(exception, self.parent.exceptionType):
result = None
try:
result = self.parent.handler(exception)
except Exception as e:
self.observer.onError(e)
self.dispose()
return
d = SingleAssignmentDisposable()
self.subscription.disposable = d
d.disposable = result.subscribeSafe(CatchException.WrapObserver(self))
else:
self.observer.onError(exception)
self.dispose()
def onCompleted(self):
self.observer.onCompleted()
self.dispose()
<|code_end|>
, generate the next line using the imports in this file:
from rx.disposable import SerialDisposable, SingleAssignmentDisposable
from rx.observable import Producer
from rx.observer import Observer
import rx.linq.sink
and context (functions, classes, or occasionally code) from other files:
# Path: rx/disposable.py
# class SerialDisposable(Cancelable):
# """Represents a disposable resource whose underlying
# disposable resource can be replaced by
# another disposable resource, causing automatic
# disposal of the previous underlying disposable resource.
# Also known as MultipleAssignmentDisposable."""
#
# def __init__(self):
# super(SerialDisposable, self).__init__()
# self.current = None
#
# def disposable():
# doc = "The disposable property."
# def fget(self):
# with self.lock:
# if self.isDisposed:
# return Disposable.empty()
# else:
# return self.current
# def fset(self, value):
# old = None
# shouldDispose = False
#
# with self.lock:
# shouldDispose = self.isDisposed
#
# if not shouldDispose:
# old = self.current
# self.current = value
#
# if old != None:
# old.dispose()
#
# if shouldDispose:
# value.dispose()
# return locals()
# disposable = property(**disposable())
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# old = self.current
#
# self.current = None
#
# if old != None:
# old.dispose()
#
# class SingleAssignmentDisposable(Cancelable):
# """Represents a disposable resource which only allows
# a single assignment of its underlying disposable resource.
# If an underlying disposable resource has already been set,
# future attempts to set the underlying disposable resource
# will throw an Error."""
#
# def __init__(self):
# super(SingleAssignmentDisposable, self).__init__()
# self.current = None
#
# def disposable():
# def fget(self):
# with self.lock:
# if self.isDisposed:
# return Disposable.empty()
# else:
# return self.current
# def fset(self, value):
# old = self.current
# self.current = value
#
# if old != None: raise Exception("Disposable has already been assigned")
#
# if self.isDisposed and value != None: value.dispose()
# return locals()
#
# disposable = property(**disposable())
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# if self.current != None:
# self.current.dispose()
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
#
# Path: rx/observer.py
# class Observer(Disposable):
# """Represents the IObserver Interface.
# Has some static helper methods attached"""
#
# @staticmethod
# def create(onNext=None, onError=None, onCompleted=None):
# if onNext == None:
# onNext = noop
# if onError == None:
# onError = defaultError
# if onCompleted == None:
# onCompleted = noop
#
# return AnonymousObserver(onNext, onError, onCompleted)
#
# @staticmethod
# def synchronize(observer, lock=None):
# if lock == None:
# lock = RLock()
#
# return SynchronizedObserver(observer, lock)
#
# @staticmethod
# def fromNotifier(handler):
# return AnonymousObserver(
# lambda x: handler(Notification.createOnNext(x)),
# lambda ex: handler(Notification.createOnError(ex)),
# lambda: handler(Notification.createOnCompleted())
# )
#
# def toNotifier(self):
# return lambda n: n.accept(self)
#
# def asObserver(self):
# return AnonymousObserver(self.onNext, self.onError, self.onCompleted)
#
# def checked(self):
# return CheckedObserver(self)
#
# def notifyOn(self, scheduler):
# return ScheduledObserver(scheduler, self)
#
# def onNext(self, value):
# raise NotImplementedError()
#
# def onError(self, exception):
# raise NotImplementedError()
#
# def onCompleted(self):
# raise NotImplementedError()
. Output only the next line. | class WrapObserver(Observer): |
Here is a snippet: <|code_start|> def onError(self, exception):
self.observer.onError(exception)
self.dispose()
def onCompleted(self):
self.observer.onCompleted()
self.dispose()
class SkipTime(Producer):
def __init__(self, source, duration, scheduler):
self.source = source
self.duration = duration
self.scheduler = scheduler
def omega(self, duration):
if duration < self.duration:
duration = self.duration
return SkipTime(self.source, self.duration)
def run(self, observer, cancel, setSink):
sink = self.Sink(self, observer, cancel)
setSink(sink)
return sink.run()
class Sink(rx.linq.sink.Sink):
def __init__(self, parent, observer, cancel):
super(SkipTime.Sink, self).__init__(observer, cancel)
self.parent = parent
<|code_end|>
. Write the next line using the current file imports:
from rx.concurrency import Atomic
from rx.disposable import CompositeDisposable
from rx.observable import Producer
import rx.linq.sink
and context from other files:
# Path: rx/concurrency.py
# class Atomic:
# def __init__(self, value=None, lock=RLock()):
# self.lock = lock
# self._value = value
#
# def value():
# doc = "The value property."
# def fget(self):
# return self._value
# def fset(self, value):
# self.exchange(value)
# return locals()
# value = property(**value())
#
# def exchange(self, value):
# with self.lock:
# old = self._value
# self._value = value
# return old
#
# def compareExchange(self, value, expected):
# with self.lock:
# old = self._value
#
# if old == expected:
# self._value = value
#
# return old
#
# def inc(self, by=1):
# with self.lock:
# self._value += by
# return self.value
#
# def dec(self, by=1):
# with self.lock:
# self._value -= by
# return self.value
#
# Path: rx/disposable.py
# class CompositeDisposable(Cancelable):
# """Represents a group of disposable resources that
# are disposed together"""
#
# def __init__(self, *disposables):
# super(CompositeDisposable, self).__init__()
#
# if len(disposables) == 0:
# self.disposables = []
# elif len(disposables) == 1 and not isinstance(disposables[0], Disposable):
# self.disposables = [d for d in disposables[0] if d != None]
# else:
# self.disposables = [d for d in disposables if d != None]
#
# self.length = len(self.disposables)
#
# def add(self, disposable):
# shouldDispose = False
#
# with self.lock:
# shouldDispose = self.isDisposed
#
# if not shouldDispose:
# self.disposables.append(disposable)
# self.length += 1
#
# if shouldDispose:
# disposable.dispose()
#
# def contains(self, disposable):
# with self.lock:
# return self.disposables.index(disposable) >= 0
#
# def remove(self, disposable):
# shouldDispose = False
#
# with self.lock:
# if self.isDisposed:
# return False
#
# index = self.disposables.index(disposable)
#
# if index < 0:
# return False
#
# shouldDispose = True
#
# self.disposables.remove(disposable)
# self.length -= 1
#
# if shouldDispose:
# disposable.dispose()
#
# return shouldDispose
#
# def clear(self):
# disposables = []
#
# with self.lock:
# disposables = self.disposables
# self.disposables = []
# self.length = 0
#
# for disposable in disposables:
# disposable.dispose()
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# self.clear()
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
, which may include functions, classes, or code. Output only the next line. | self.open = Atomic(False) |
Given the following code snippet before the placeholder: <|code_start|> self.dispose()
class SkipTime(Producer):
def __init__(self, source, duration, scheduler):
self.source = source
self.duration = duration
self.scheduler = scheduler
def omega(self, duration):
if duration < self.duration:
duration = self.duration
return SkipTime(self.source, self.duration)
def run(self, observer, cancel, setSink):
sink = self.Sink(self, observer, cancel)
setSink(sink)
return sink.run()
class Sink(rx.linq.sink.Sink):
def __init__(self, parent, observer, cancel):
super(SkipTime.Sink, self).__init__(observer, cancel)
self.parent = parent
self.open = Atomic(False)
def run(self):
t = self.parent.scheduler.scheduleWithRelative(self.parent.duration, self.tick)
d = self.parent.source.subscribeSafe(self)
<|code_end|>
, predict the next line using imports from the current file:
from rx.concurrency import Atomic
from rx.disposable import CompositeDisposable
from rx.observable import Producer
import rx.linq.sink
and context including class names, function names, and sometimes code from other files:
# Path: rx/concurrency.py
# class Atomic:
# def __init__(self, value=None, lock=RLock()):
# self.lock = lock
# self._value = value
#
# def value():
# doc = "The value property."
# def fget(self):
# return self._value
# def fset(self, value):
# self.exchange(value)
# return locals()
# value = property(**value())
#
# def exchange(self, value):
# with self.lock:
# old = self._value
# self._value = value
# return old
#
# def compareExchange(self, value, expected):
# with self.lock:
# old = self._value
#
# if old == expected:
# self._value = value
#
# return old
#
# def inc(self, by=1):
# with self.lock:
# self._value += by
# return self.value
#
# def dec(self, by=1):
# with self.lock:
# self._value -= by
# return self.value
#
# Path: rx/disposable.py
# class CompositeDisposable(Cancelable):
# """Represents a group of disposable resources that
# are disposed together"""
#
# def __init__(self, *disposables):
# super(CompositeDisposable, self).__init__()
#
# if len(disposables) == 0:
# self.disposables = []
# elif len(disposables) == 1 and not isinstance(disposables[0], Disposable):
# self.disposables = [d for d in disposables[0] if d != None]
# else:
# self.disposables = [d for d in disposables if d != None]
#
# self.length = len(self.disposables)
#
# def add(self, disposable):
# shouldDispose = False
#
# with self.lock:
# shouldDispose = self.isDisposed
#
# if not shouldDispose:
# self.disposables.append(disposable)
# self.length += 1
#
# if shouldDispose:
# disposable.dispose()
#
# def contains(self, disposable):
# with self.lock:
# return self.disposables.index(disposable) >= 0
#
# def remove(self, disposable):
# shouldDispose = False
#
# with self.lock:
# if self.isDisposed:
# return False
#
# index = self.disposables.index(disposable)
#
# if index < 0:
# return False
#
# shouldDispose = True
#
# self.disposables.remove(disposable)
# self.length -= 1
#
# if shouldDispose:
# disposable.dispose()
#
# return shouldDispose
#
# def clear(self):
# disposables = []
#
# with self.lock:
# disposables = self.disposables
# self.disposables = []
# self.length = 0
#
# for disposable in disposables:
# disposable.dispose()
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# self.clear()
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
. Output only the next line. | return CompositeDisposable(t, d) |
Given snippet: <|code_start|> self.selector = selector
self.sources = sources
self.defaultSource = defaultSource
def eval(self):
res = self.sources.get(self.selector())
if res != None:
return res
else:
self.defaultSource
def run(self, observer, cancel, setSink):
sink = self.Sink(self, observer, cancel)
setSink(sink)
return sink.run()
class Sink(rx.linq.sink.Sink):
def __init__(self, parent, observer, cancel):
super(Case.Sink, self).__init__(observer, cancel)
self.parent = parent
def run(self):
result = None
try:
result = self.parent.eval()
except Exception as e:
self.observer.onError(e)
self.dispose()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rx.disposable import Disposable
from rx.observable import Producer
import rx.linq.sink
and context:
# Path: rx/disposable.py
# class Disposable(object):
# """Represents a disposable object"""
#
# def dispose(self):
# pass
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, traceback):
# self.dispose()
#
# @staticmethod
# def create(action):
# return AnonymouseDisposable(action)
#
# @staticmethod
# def empty():
# return disposableEmpty
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
which might include code, classes, or functions. Output only the next line. | return Disposable.empty() |
Given the code snippet: <|code_start|>
class Latest(PushToPullAdapter):
def __init__(self, source):
super(Latest, self).__init__(source)
def run(self, subscription):
return self.Sink(subscription)
class Sink(rx.linq.sink.PushToPullSink):
def __init__(self, subscription):
super(Latest.Sink, self).__init__(subscription)
self.gate = RLock()
self.semaphore = BoundedSemaphore(1)
self.semaphore.acquire()
self.notificationAvailable = False
self.kind = None
self.value = None
self.error = None
def onNext(self, value):
lackedValue = False
with self.gate:
lackedValue = not self.notificationAvailable
self.notificationAvailable = True
<|code_end|>
, generate the next line using the imports in this file:
from rx.notification import Notification
from rx.observable import PushToPullAdapter
from threading import RLock, BoundedSemaphore
import rx.linq.sink
and context (functions, classes, or occasionally code) from other files:
# Path: rx/notification.py
# class Notification(object):
# """Represents a notification to an observer."""
#
# KIND_NEXT = 0
# KIND_ERROR = 1
# KIND_COMPLETED = 2
#
# def __eq__(self, other):
# if not isinstance(other, Notification):
# return False
#
# return (
# self.kind == other.kind and
# self.value == other.value and
# self.hasValue == other.hasValue and
# self.exception == other.exception
# )
#
# def accept(self, observerOrOnNext, onError=None, onCompleted=None):
# """Accepts an observer or the methods onNext, onError, onCompleted and invokes
# either onNext, onError, onCompleted depending on which type of :class:`Notification`
# it is. This is an abstract method that is implemented by
# :class:`OnNextNotification`, :class:`OnErrorNotification`,
# and :class:`OnCompletedNotification`."""
# # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'):
# # observer = Observer.create(observerOrOnNext, onError, onComplete)
# raise NotImplementedError()
#
# @staticmethod
# def createOnNext(value):
# return OnNextNotification(value)
#
# @staticmethod
# def createOnError(exception):
# return OnErrorNotification(exception)
#
# @staticmethod
# def createOnCompleted():
# return OnCompletedNotification()
#
# Path: rx/observable.py
# class PushToPullAdapter(object):
# def __init__(self, source):
# self.source = source
#
# def __iter__(self):
# d = SingleAssignmentDisposable()
# res = self.run(d)
# d.disposable = self.source.subscribeSafe(res)
# return res
#
# def run(self, subscription):
# raise NotImplementedError()
. Output only the next line. | self.kind = Notification.KIND_NEXT |
Given snippet: <|code_start|> def run(self):
self.first = True
self.hasResult = False
self.result = None
return self.parent.scheduler.scheduleWithState(
self.parent.initialState,
self.invokeRec
)
def invokeRec(self, scheduler, state):
time = 0
if self.hasResult:
self.observer.onNext(self.result)
try:
if self.first:
self.first = False
else:
state = self.parent.iterate(state)
self.hasResult = self.parent.condition(state)
if self.hasResult:
self.result = self.parent.resultSelector(state)
time = self.parent.timeSelector(state)
except Exception as e:
self.observer.onError(e)
self.dispose()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rx.disposable import Disposable
from rx.observable import Producer
import rx.linq.sink
and context:
# Path: rx/disposable.py
# class Disposable(object):
# """Represents a disposable object"""
#
# def dispose(self):
# pass
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, traceback):
# self.dispose()
#
# @staticmethod
# def create(action):
# return AnonymouseDisposable(action)
#
# @staticmethod
# def empty():
# return disposableEmpty
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
which might include code, classes, or functions. Output only the next line. | return Disposable.empty() |
Continue the code snippet: <|code_start|>
class Next(PushToPullAdapter):
def __init__(self, source):
super(Next, self).__init__(source)
def run(self, subscription):
return self.Sink(subscription)
class Sink(rx.linq.sink.PushToPullSink):
def __init__(self, subscription):
super(Next.Sink, self).__init__(subscription)
self.gate = RLock()
self.semaphore = BoundedSemaphore(1)
self.semaphore.acquire()
self.waiting = False
self.kind = None
self.value = None
self.error = None
def onNext(self, value):
with self.gate:
if self.waiting:
self.value = value
<|code_end|>
. Use current file imports:
from rx.notification import Notification
from rx.observable import PushToPullAdapter
from threading import RLock, BoundedSemaphore
import rx.linq.sink
and context (classes, functions, or code) from other files:
# Path: rx/notification.py
# class Notification(object):
# """Represents a notification to an observer."""
#
# KIND_NEXT = 0
# KIND_ERROR = 1
# KIND_COMPLETED = 2
#
# def __eq__(self, other):
# if not isinstance(other, Notification):
# return False
#
# return (
# self.kind == other.kind and
# self.value == other.value and
# self.hasValue == other.hasValue and
# self.exception == other.exception
# )
#
# def accept(self, observerOrOnNext, onError=None, onCompleted=None):
# """Accepts an observer or the methods onNext, onError, onCompleted and invokes
# either onNext, onError, onCompleted depending on which type of :class:`Notification`
# it is. This is an abstract method that is implemented by
# :class:`OnNextNotification`, :class:`OnErrorNotification`,
# and :class:`OnCompletedNotification`."""
# # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'):
# # observer = Observer.create(observerOrOnNext, onError, onComplete)
# raise NotImplementedError()
#
# @staticmethod
# def createOnNext(value):
# return OnNextNotification(value)
#
# @staticmethod
# def createOnError(exception):
# return OnErrorNotification(exception)
#
# @staticmethod
# def createOnCompleted():
# return OnCompletedNotification()
#
# Path: rx/observable.py
# class PushToPullAdapter(object):
# def __init__(self, source):
# self.source = source
#
# def __iter__(self):
# d = SingleAssignmentDisposable()
# res = self.run(d)
# d.disposable = self.source.subscribeSafe(res)
# return res
#
# def run(self, subscription):
# raise NotImplementedError()
. Output only the next line. | self.kind = Notification.KIND_NEXT |
Predict the next line after this snippet: <|code_start|>
class If(Producer):
def __init__(self, condition, thenSource, elseSource):
self.condition = condition
self.thenSource = thenSource
self.elseSource = elseSource
def eval(self):
if self.condition():
return self.thenSource
else:
return self.elseSource
def run(self, observer, cancel, setSink):
sink = self.Sink(self, observer, cancel)
setSink(sink)
return sink.run()
class Sink(rx.linq.sink.Sink):
def __init__(self, parent, observer, cancel):
super(If.Sink, self).__init__(observer, cancel)
self.parent = parent
def run(self):
try:
result = self.parent.eval()
except Exception as e:
self.observer.onError(e)
self.dispose()
<|code_end|>
using the current file's imports:
from rx.disposable import Disposable
from rx.observable import Producer
import rx.linq.sink
and any relevant context from other files:
# Path: rx/disposable.py
# class Disposable(object):
# """Represents a disposable object"""
#
# def dispose(self):
# pass
#
# def __enter__(self):
# return self
#
# def __exit__(self, exc_type, exc_value, traceback):
# self.dispose()
#
# @staticmethod
# def create(action):
# return AnonymouseDisposable(action)
#
# @staticmethod
# def empty():
# return disposableEmpty
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
. Output only the next line. | return Disposable.empty() |
Predict the next line for this snippet: <|code_start|>
class AddRef(Producer):
def __init__(self, source, refCount):
self.source = source
self.refCount = refCount
def run(self, observer, cancel, setSink):
<|code_end|>
with the help of current file imports:
from rx.disposable import CompositeDisposable
from rx.observable import Producer
import rx.linq.sink
and context from other files:
# Path: rx/disposable.py
# class CompositeDisposable(Cancelable):
# """Represents a group of disposable resources that
# are disposed together"""
#
# def __init__(self, *disposables):
# super(CompositeDisposable, self).__init__()
#
# if len(disposables) == 0:
# self.disposables = []
# elif len(disposables) == 1 and not isinstance(disposables[0], Disposable):
# self.disposables = [d for d in disposables[0] if d != None]
# else:
# self.disposables = [d for d in disposables if d != None]
#
# self.length = len(self.disposables)
#
# def add(self, disposable):
# shouldDispose = False
#
# with self.lock:
# shouldDispose = self.isDisposed
#
# if not shouldDispose:
# self.disposables.append(disposable)
# self.length += 1
#
# if shouldDispose:
# disposable.dispose()
#
# def contains(self, disposable):
# with self.lock:
# return self.disposables.index(disposable) >= 0
#
# def remove(self, disposable):
# shouldDispose = False
#
# with self.lock:
# if self.isDisposed:
# return False
#
# index = self.disposables.index(disposable)
#
# if index < 0:
# return False
#
# shouldDispose = True
#
# self.disposables.remove(disposable)
# self.length -= 1
#
# if shouldDispose:
# disposable.dispose()
#
# return shouldDispose
#
# def clear(self):
# disposables = []
#
# with self.lock:
# disposables = self.disposables
# self.disposables = []
# self.length = 0
#
# for disposable in disposables:
# disposable.dispose()
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# self.clear()
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
, which may contain function names, class names, or code. Output only the next line. | d = CompositeDisposable(self.refCount.getDisposable(), cancel) |
Predict the next line after this snippet: <|code_start|>
class TakeTime(Producer):
def __init__(self, source, duration, scheduler):
self.source = source
self.duration = duration
self.scheduler = scheduler
def omega(self, duration):
if self.duration <= duration:
return self
else:
return TakeTime(self.source, duration, self.scheduler)
def run(self, observer, cancel, setSink):
sink = self.Sink(self, observer, cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
class Sink(rx.linq.sink.Sink):
def __init__(self, parent, observer, cancel):
super(TakeTime.Sink, self).__init__(observer, cancel)
self.parent = parent
self.remaining = self.parent.count
def run(self):
self.gate = RLock()
t = self.parent.scheduler.scheduleWithRelative(self.parent.duration, self.tick)
d = self.parent.source.subscribeSafe(self)
<|code_end|>
using the current file's imports:
from rx.disposable import CompositeDisposable
from rx.observable import Producer
from threading import RLock
import rx.linq.sink
and any relevant context from other files:
# Path: rx/disposable.py
# class CompositeDisposable(Cancelable):
# """Represents a group of disposable resources that
# are disposed together"""
#
# def __init__(self, *disposables):
# super(CompositeDisposable, self).__init__()
#
# if len(disposables) == 0:
# self.disposables = []
# elif len(disposables) == 1 and not isinstance(disposables[0], Disposable):
# self.disposables = [d for d in disposables[0] if d != None]
# else:
# self.disposables = [d for d in disposables if d != None]
#
# self.length = len(self.disposables)
#
# def add(self, disposable):
# shouldDispose = False
#
# with self.lock:
# shouldDispose = self.isDisposed
#
# if not shouldDispose:
# self.disposables.append(disposable)
# self.length += 1
#
# if shouldDispose:
# disposable.dispose()
#
# def contains(self, disposable):
# with self.lock:
# return self.disposables.index(disposable) >= 0
#
# def remove(self, disposable):
# shouldDispose = False
#
# with self.lock:
# if self.isDisposed:
# return False
#
# index = self.disposables.index(disposable)
#
# if index < 0:
# return False
#
# shouldDispose = True
#
# self.disposables.remove(disposable)
# self.length -= 1
#
# if shouldDispose:
# disposable.dispose()
#
# return shouldDispose
#
# def clear(self):
# disposables = []
#
# with self.lock:
# disposables = self.disposables
# self.disposables = []
# self.length = 0
#
# for disposable in disposables:
# disposable.dispose()
#
# def dispose(self):
# if not self._isDisposed.exchange(True):
# self.clear()
#
# Path: rx/observable.py
# class Producer(Observable):
# """Base class for implementation of query operators, providing
# performance benefits over the use of Observable.Create"""
#
# def subscribeCore(self, observer):
# return self.subscribeRaw(observer, True)
#
# def subscribeRaw(self, observer, enableSafequard):
# sink = SingleAssignmentDisposable()
# subscription = SingleAssignmentDisposable()
#
# d = CompositeDisposable(sink, subscription)
#
# if enableSafequard:
# observer = AutoDetachObserver(observer, d)
#
# def assignSink(s):
# sink.disposable = s
#
# def scheduled():
# subscription.disposable = self.run(observer, subscription, assignSink)
# return Disposable.empty()
#
# if Scheduler.currentThread.isScheduleRequired():
# Scheduler.currentThread.schedule(scheduled)
# else:
# scheduled()
#
# return d
#
# def run(self, observer, cancel, setSink):
# raise NotImplementedError()
. Output only the next line. | return CompositeDisposable(t, d) |
Given snippet: <|code_start|>
def run_tests(test_files):
print('Will run the following tests \n\t%s' % "\n\t".join(test_files))
results = list()
for test_file in test_files:
test_name = os.path.splitext(test_file)[0]
test_module = imp.load_source(test_name, test_file)
if hasattr(test_module, 'get_test_banner'):
banner = test_module.get_test_banner()
else:
banner = "Test: %s" %(test_name)
def run_test(test_module, test_banner):
print("\n>>> Running %s" %test_banner)
#results.append("\n%s" %test_banner)
result, t_info = test_module.run()
if result:
info = "%s[Pass]%s" %(Colors.GREEN, Colors.DEFAULT)
else:
info = "%s[Fail]%s" %(Colors.RED, Colors.DEFAULT)
info = "%s\n%s\n" %(info, t_info)
print("Result:%s\n<<<Finished" %info)
return info
if "v4l" in test_name:
test_name = os.path.basename(test_name)
for device in v4l_get_devices():
device_path = '/dev/%s' %device
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import imp
import argparse
from utils.v4l import v4l_get_name, v4l_get_devices, v4l_set_current_device
from utils.colors import Colors
and context:
# Path: utils/v4l.py
# def v4l_get_name(device='video0'):
# path_pattern = "/sys/class/video4linux/%s/name"
# from utils.files import read_file
# path = path_pattern %device
# return read_file(path).strip()
#
# def v4l_get_devices():
# return os.listdir('/sys/class/video4linux')
#
# def v4l_set_current_device(device):
# os.environ['V4L2_TEST_DEVICE'] = device
#
# Path: utils/colors.py
# class Colors():
# RED = '\033[91m'
# GREEN = '\033[92m'
# YELLOW = '\033[93m'
# BLUE = '\033[94m'
# PURPLE = '\033[95m'
# TEAL = '\033[96m'
# DEFAULT = '\033[0m'
which might include code, classes, or functions. Output only the next line. | banner = 'V4L %s test of device %s (%s)' %(test_name, v4l_get_name(), device_path) |
Given the following code snippet before the placeholder: <|code_start|> test_files.append(os.path.join(root, f))
return test_files
def run_tests(test_files):
print('Will run the following tests \n\t%s' % "\n\t".join(test_files))
results = list()
for test_file in test_files:
test_name = os.path.splitext(test_file)[0]
test_module = imp.load_source(test_name, test_file)
if hasattr(test_module, 'get_test_banner'):
banner = test_module.get_test_banner()
else:
banner = "Test: %s" %(test_name)
def run_test(test_module, test_banner):
print("\n>>> Running %s" %test_banner)
#results.append("\n%s" %test_banner)
result, t_info = test_module.run()
if result:
info = "%s[Pass]%s" %(Colors.GREEN, Colors.DEFAULT)
else:
info = "%s[Fail]%s" %(Colors.RED, Colors.DEFAULT)
info = "%s\n%s\n" %(info, t_info)
print("Result:%s\n<<<Finished" %info)
return info
if "v4l" in test_name:
test_name = os.path.basename(test_name)
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import imp
import argparse
from utils.v4l import v4l_get_name, v4l_get_devices, v4l_set_current_device
from utils.colors import Colors
and context including class names, function names, and sometimes code from other files:
# Path: utils/v4l.py
# def v4l_get_name(device='video0'):
# path_pattern = "/sys/class/video4linux/%s/name"
# from utils.files import read_file
# path = path_pattern %device
# return read_file(path).strip()
#
# def v4l_get_devices():
# return os.listdir('/sys/class/video4linux')
#
# def v4l_set_current_device(device):
# os.environ['V4L2_TEST_DEVICE'] = device
#
# Path: utils/colors.py
# class Colors():
# RED = '\033[91m'
# GREEN = '\033[92m'
# YELLOW = '\033[93m'
# BLUE = '\033[94m'
# PURPLE = '\033[95m'
# TEAL = '\033[96m'
# DEFAULT = '\033[0m'
. Output only the next line. | for device in v4l_get_devices(): |
Given snippet: <|code_start|>def run_tests(test_files):
print('Will run the following tests \n\t%s' % "\n\t".join(test_files))
results = list()
for test_file in test_files:
test_name = os.path.splitext(test_file)[0]
test_module = imp.load_source(test_name, test_file)
if hasattr(test_module, 'get_test_banner'):
banner = test_module.get_test_banner()
else:
banner = "Test: %s" %(test_name)
def run_test(test_module, test_banner):
print("\n>>> Running %s" %test_banner)
#results.append("\n%s" %test_banner)
result, t_info = test_module.run()
if result:
info = "%s[Pass]%s" %(Colors.GREEN, Colors.DEFAULT)
else:
info = "%s[Fail]%s" %(Colors.RED, Colors.DEFAULT)
info = "%s\n%s\n" %(info, t_info)
print("Result:%s\n<<<Finished" %info)
return info
if "v4l" in test_name:
test_name = os.path.basename(test_name)
for device in v4l_get_devices():
device_path = '/dev/%s' %device
banner = 'V4L %s test of device %s (%s)' %(test_name, v4l_get_name(), device_path)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import imp
import argparse
from utils.v4l import v4l_get_name, v4l_get_devices, v4l_set_current_device
from utils.colors import Colors
and context:
# Path: utils/v4l.py
# def v4l_get_name(device='video0'):
# path_pattern = "/sys/class/video4linux/%s/name"
# from utils.files import read_file
# path = path_pattern %device
# return read_file(path).strip()
#
# def v4l_get_devices():
# return os.listdir('/sys/class/video4linux')
#
# def v4l_set_current_device(device):
# os.environ['V4L2_TEST_DEVICE'] = device
#
# Path: utils/colors.py
# class Colors():
# RED = '\033[91m'
# GREEN = '\033[92m'
# YELLOW = '\033[93m'
# BLUE = '\033[94m'
# PURPLE = '\033[95m'
# TEAL = '\033[96m'
# DEFAULT = '\033[0m'
which might include code, classes, or functions. Output only the next line. | v4l_set_current_device(device_path) |
Continue the code snippet: <|code_start|>
TESTS_DIR = 'tests'
def scan_test_folder(folder=TESTS_DIR):
test_files = list()
for root, dirs, files in os.walk(folder):
for f in files:
if f.endswith('.py'):
test_files.append(os.path.join(root, f))
return test_files
def run_tests(test_files):
print('Will run the following tests \n\t%s' % "\n\t".join(test_files))
results = list()
for test_file in test_files:
test_name = os.path.splitext(test_file)[0]
test_module = imp.load_source(test_name, test_file)
if hasattr(test_module, 'get_test_banner'):
banner = test_module.get_test_banner()
else:
banner = "Test: %s" %(test_name)
def run_test(test_module, test_banner):
print("\n>>> Running %s" %test_banner)
#results.append("\n%s" %test_banner)
result, t_info = test_module.run()
if result:
<|code_end|>
. Use current file imports:
import os
import sys
import imp
import argparse
from utils.v4l import v4l_get_name, v4l_get_devices, v4l_set_current_device
from utils.colors import Colors
and context (classes, functions, or code) from other files:
# Path: utils/v4l.py
# def v4l_get_name(device='video0'):
# path_pattern = "/sys/class/video4linux/%s/name"
# from utils.files import read_file
# path = path_pattern %device
# return read_file(path).strip()
#
# def v4l_get_devices():
# return os.listdir('/sys/class/video4linux')
#
# def v4l_set_current_device(device):
# os.environ['V4L2_TEST_DEVICE'] = device
#
# Path: utils/colors.py
# class Colors():
# RED = '\033[91m'
# GREEN = '\033[92m'
# YELLOW = '\033[93m'
# BLUE = '\033[94m'
# PURPLE = '\033[95m'
# TEAL = '\033[96m'
# DEFAULT = '\033[0m'
. Output only the next line. | info = "%s[Pass]%s" %(Colors.GREEN, Colors.DEFAULT) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink -v | grep v4l2src0"
def run():
try:
<|code_end|>
. Use current file imports:
import os
from utils.process import get_stdout
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context (classes, functions, or code) from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | caps = get_stdout(cmd_pattern %v4l_get_current_device(), shell=True).split('caps = ')[1].strip().replace('\\', '') |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink -v | grep v4l2src0"
def run():
try:
<|code_end|>
. Use current file imports:
import os
from utils.process import get_stdout
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context (classes, functions, or code) from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | caps = get_stdout(cmd_pattern %v4l_get_current_device(), shell=True).split('caps = ')[1].strip().replace('\\', '') |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
#http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/
RPI_REV = {
'0002': 'Model B',
'0003': 'Model B',
'0004': 'Model B',
'0005': 'Model B',
'0006': 'Model B',
'0007': 'Model A',
'0008': 'Model A',
'0009': 'Model A',
'000d': 'Model B',
'000e': 'Model B',
'000f': 'Model B',
'0010': 'Model B+',
'0011': 'Compute Module',
'0012': 'Model A+',
'a01041': 'Pi 2 Model B',
'a21041': 'Pi 2 Model B',
}
def get_pi_model():
<|code_end|>
using the current file's imports:
from utils.process import get_stdout
and any relevant context from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
. Output only the next line. | rev = get_stdout('grep Revision /proc/cpuinfo', shell=True).split(': ')[1].strip() |
Using the snippet: <|code_start|> if self.ENABLE_QUALITY_ANALYSIS:
quality, min_quality, quality_log = self.get_quality_score(caps, framerate, output_files)
quality_results.append(quality)
min_quality_results.append(min_quality)
if not self.ENABLE_LIVE:
fps = int(round(num_buffers_test/took))
else:
realtime_duration = num_buffers/framerate
fps = int(round(framerate*(realtime_duration / took)))
# Assuming that encoders should not be late by more than 1 sec
if int(took) > realtime_duration:
# If multiple passes are expected, run at least twice
if self.PASS_COUNT == 1 or (self.PASS_COUNT > 1 and i > 0):
print('Slower than realtime, aborting next tests')
abort = True
else:
print('Slower than realtime, trying again')
else:
fps = 0
fps_results.append(fps)
sample_desc = "%s-%sch" % (sample, channel_count)
mean_fps = int(round(mean(fps_results)))
variation_fps = int(max(max(fps_results) - mean_fps, mean_fps - min(fps_results)))
result = "%s\t%s\t%s\t%s" %(plugin_string, sample_desc, mean_fps, variation_fps)
if self.ENABLE_QUALITY_ANALYSIS:
result += '\t%.2f\t%.2f\t%s' %(quality, min(min_quality_results), quality_log)
info += "\n%s" %result
success = True
if os.path.exists(self.RAW_BUF_FILE):
os.remove(self.RAW_BUF_FILE)
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (class names, function names, or code) available:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | write_timestamped_results(info) |
Using the snippet: <|code_start|> write_timestamped_results(info)
return (success, info)
def get_quality_score(self, raw_caps, framerate, files):
print('Running quality analysis with %s' % self.QUALITY_METHOD)
muxed_raw_file = os.path.join(self.OUTPUT_FOLDER, self.RAW_REF_FILE)
cmd = 'gst-launch-1.0 filesrc location=%s ! %s ! matroskamux ! filesink location=%s' % (self.RAW_BUF_FILE, raw_caps, muxed_raw_file)
rc, stdout, stderr = run_cmd(cmd)
cmd = 'qpsnr -a %s -o fps=%s -r %s %s' % (self.QUALITY_METHOD, framerate, muxed_raw_file, ' '.join([os.path.join(self.OUTPUT_FOLDER, f) for f in files]))
rc, stdout, stderr = run_cmd(cmd)
scores = list()
header = list()
warnings = list()
for index, line in enumerate(stdout.split('\n')):
if line:
fields = line.strip(',').split(',')
if index == 0:
header = fields
else:
frame_count = fields[0]
scores_line = [float(f) for f in fields[1:]]
for index, score in enumerate(scores_line):
scores.append(score)
if score < 0.99:
warning = 'frame %s of %s is below threshold : %s' % (frame_count, header[index + 1], score)
warnings.append(warning)
os.remove(muxed_raw_file)
fname = ''
if warnings:
fname = os.path.join(self.OUTPUT_FOLDER, '%s-%s.log' % (self.QUALITY_METHOD, int(time.time())))
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (class names, function names, or code) available:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | write_results('\n'.join(warnings), fname) |
Using the snippet: <|code_start|> else:
sink = "fakesink sync=%s" % self.ENABLE_LIVE
encoders = list()
encoders_short = list()
for i in range(1, channel_count + 1):
if self.ENABLE_QUALITY_ANALYSIS:
output_file_name = self.OUTPUT_FILE_TEMPLATE % output_file_count
sink_pattern = 'matroskamux ! tee name=tee%%s ! queue ! filesink location=%s tee%%s. ! queue ! fakesink sync=%s' % (os.path.join(self.OUTPUT_FOLDER, output_file_name), self.ENABLE_LIVE)
output_files.append(output_file_name)
sink = sink_pattern % (output_file_count, output_file_count)
output_file_count += 1
if self.ENABLE_PARALLEL_PLUGINS:
plugin_string_template = parallel_plugins[i % len(parallel_plugins)]
plugin_string = plugin_string_template.format(**encoding_params)
encoders.append("queue name=enc_%s max-size-buffers=1 ! %s ! %s " % (i, plugin_string, sink))
encoders_short.append(plugin_string)
if self.ENABLE_PARALLEL_PLUGINS:
plugin_string = ""
for p in self.PLUGINS:
pname = p[0]
pname_count = " ".join(encoders).count(pname)
if pname_count > 0:
plugin_string += "%s x%s " %(pname, pname_count)
encoders_string = "encoder. ! ".join(encoders)
num_buffers_test = channel_count*num_buffers
cmd = self.CMD_PATTERN %(input_file, bufsize, caps, encoders_string)
# check cmd and push sample data into RAM
print("Heating cache for test %s/%s (%i%%) %s" % (test_count, total_tests, 100*test_count/float(total_tests), plugin_string))
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (class names, function names, or code) available:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | took = run_gst_cmd(cmd) |
Given snippet: <|code_start|> realtime_duration = num_buffers/framerate
fps = int(round(framerate*(realtime_duration / took)))
# Assuming that encoders should not be late by more than 1 sec
if int(took) > realtime_duration:
# If multiple passes are expected, run at least twice
if self.PASS_COUNT == 1 or (self.PASS_COUNT > 1 and i > 0):
print('Slower than realtime, aborting next tests')
abort = True
else:
print('Slower than realtime, trying again')
else:
fps = 0
fps_results.append(fps)
sample_desc = "%s-%sch" % (sample, channel_count)
mean_fps = int(round(mean(fps_results)))
variation_fps = int(max(max(fps_results) - mean_fps, mean_fps - min(fps_results)))
result = "%s\t%s\t%s\t%s" %(plugin_string, sample_desc, mean_fps, variation_fps)
if self.ENABLE_QUALITY_ANALYSIS:
result += '\t%.2f\t%.2f\t%s' %(quality, min(min_quality_results), quality_log)
info += "\n%s" %result
success = True
if os.path.exists(self.RAW_BUF_FILE):
os.remove(self.RAW_BUF_FILE)
write_timestamped_results(info)
return (success, info)
def get_quality_score(self, raw_caps, framerate, files):
print('Running quality analysis with %s' % self.QUALITY_METHOD)
muxed_raw_file = os.path.join(self.OUTPUT_FOLDER, self.RAW_REF_FILE)
cmd = 'gst-launch-1.0 filesrc location=%s ! %s ! matroskamux ! filesink location=%s' % (self.RAW_BUF_FILE, raw_caps, muxed_raw_file)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
which might include code, classes, or functions. Output only the next line. | rc, stdout, stderr = run_cmd(cmd) |
Based on the snippet: <|code_start|>
encoders = list()
encoders_short = list()
for i in range(1, channel_count + 1):
if self.ENABLE_QUALITY_ANALYSIS:
output_file_name = self.OUTPUT_FILE_TEMPLATE % output_file_count
sink_pattern = 'matroskamux ! tee name=tee%%s ! queue ! filesink location=%s tee%%s. ! queue ! fakesink sync=%s' % (os.path.join(self.OUTPUT_FOLDER, output_file_name), self.ENABLE_LIVE)
output_files.append(output_file_name)
sink = sink_pattern % (output_file_count, output_file_count)
output_file_count += 1
if self.ENABLE_PARALLEL_PLUGINS:
plugin_string_template = parallel_plugins[i % len(parallel_plugins)]
plugin_string = plugin_string_template.format(**encoding_params)
encoders.append("queue name=enc_%s max-size-buffers=1 ! %s ! %s " % (i, plugin_string, sink))
encoders_short.append(plugin_string)
if self.ENABLE_PARALLEL_PLUGINS:
plugin_string = ""
for p in self.PLUGINS:
pname = p[0]
pname_count = " ".join(encoders).count(pname)
if pname_count > 0:
plugin_string += "%s x%s " %(pname, pname_count)
encoders_string = "encoder. ! ".join(encoders)
num_buffers_test = channel_count*num_buffers
cmd = self.CMD_PATTERN %(input_file, bufsize, caps, encoders_string)
# check cmd and push sample data into RAM
print("Heating cache for test %s/%s (%i%%) %s" % (test_count, total_tests, 100*test_count/float(total_tests), plugin_string))
took = run_gst_cmd(cmd)
if took <= 0:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (classes, functions, sometimes code) from other files:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | print_red('<<< Heat test failed: %s' %plugin_string) |
Continue the code snippet: <|code_start|> info += '\nEncoder\tSample\tfps\tdeviation'
if self.ENABLE_QUALITY_ANALYSIS:
info += "\tq\tminq\tqlog"
return info
def parse_pattern(self, pattern_string):
name, w, h, f = pattern_string.split('=')[1].split('-')
return name, int(w), int(h), int(f)
def run(self):
success = False
if hw.is_intel() and hasattr(self, 'PLUGINS_INTEL'):
os.environ['LIBVA_DRIVER_NAME'] = 'i965'
self.PLUGINS.extend(self.PLUGINS_INTEL)
elif hw.is_nvidia() and hasattr(self, 'PLUGINS_NV'):
self.PLUGINS.extend(self.PLUGINS_NV)
else:
if hw.is_pi() and hasattr(self, 'PLUGINS_PI'):
self.PLUGINS.extend(self.PLUGINS_PI)
if hw.is_jetson() and hasattr(self, 'PLUGINS_JETSON'):
self.PLUGINS.extend(self.PLUGINS_JETSON)
w = 1920
h = 1080
colorspace = self.COLORSPACE
info = self.get_test_banner()
available_plugins = list()
for plugin in self.PLUGINS:
<|code_end|>
. Use current file imports:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (classes, functions, or code) from other files:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | if is_plugin_present(plugin[0]): |
Given the code snippet: <|code_start|> ['x264enc', 'x264enc speed-preset=ultrafast bitrate={bitrate_kb} tune=zerolatency key-int-max={keyframes}'],
]
PLUGINS_INTEL = []
PLUGINS_PI = []
PLUGINS_JETSON = []
PLUGINS_NV = []
# List of bitrates in kbit/s
BITRATES_K = [
20000,
]
# List of available input samples
# Can be generated with videotestsrc (see available patterns)
# Can be mp4/qt video samples located into the SAMPLES_FOLDER
SAMPLES = [
'pattern=black-1920-1080-30',
'pattern=smpte-1920-1080-30',
'pattern=snow-1920-1080-30',
'pattern=black-3840-2160-30',
'pattern=smpte-3840-2160-30',
'pattern=snow-3840-2160-30',
]
# If enabled, will scan the SAMPLES_FOLDER automatically; else, add them manually
SCAN_SAMPLES = True
SAMPLES_FOLDER = 'samples'
CMD_PATTERN = "gst-launch-1.0 -f filesrc location=%s blocksize=%s ! %s ! tee name=encoder ! %s"
def get_test_banner(self):
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import utils.video as video
import utils.hardware as hw
from statistics import mean
from utils.files import write_timestamped_results, write_results
from utils.process import run_gst_cmd, run_cmd
from utils.colors import print_red
from utils.gstreamer import is_plugin_present, get_gst_version
from utils.run import run_test
and context (functions, classes, or occasionally code) from other files:
# Path: utils/files.py
# def write_timestamped_results(data):
# fname = get_timestamped_fname()
# with open(fname, 'w') as f:
# f.write(data)
# print('Wrote results to %s' % fname)
#
# def write_results(data, path):
# with open(path, 'w') as f:
# f.write(data)
# print('Wrote %s' % path)
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
#
# Path: utils/gstreamer.py
# def is_plugin_present(plugin_name):
# result = process.check_cmd('gst-inspect-1.0 %s &> /dev/null' %plugin_name.split(' ')[0], shell=True, complain=False)[0]
# if not result:
# print('Plugin %s not found' % plugin_name)
# return result
#
# def get_gst_version():
# return process.get_stdout('gst-launch-1.0 --gst-version').strip().split(' ')[-1]
. Output only the next line. | info = "Gstreamer %s: %s Encoding benchmark (mean fps over %s passes), GPU: %s CPU: %s (live mode: %s)" %(get_gst_version(), self.COLORSPACE, self.PASS_COUNT, hw.gpu(), hw.cpu(), self.ENABLE_LIVE) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
def read_file(path):
with open(path, 'r') as f:
data = f.read()
return data
def check_temp_path(path='/tmp'):
path = os.path.dirname(path)
if not check_path_is_tmpfs(path):
print('Path %s is not a tmpfs' % path)
return False
if not check_path_is_writable(path):
print('Path %s is not writable' % path)
return False
return True
def check_path_is_writable(path='/tmp'):
return os.access(path, os.W_OK)
def check_path_is_tmpfs(path='/tmp'):
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import socket
from utils.process import get_stdout
and context including class names, function names, and sometimes code from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
. Output only the next line. | d = get_stdout('df %s | tail -n 1' % path, shell=True) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink"
MAX_TIME_S = 1
def _run():
run_cmd(cmd_pattern %v4l_get_current_device())
def run():
<|code_end|>
with the help of current file imports:
import os
from utils.time import time_took
from utils.process import run_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context from other files:
# Path: utils/time.py
# def time_took(function):
# before = time.time()
# try:
# success = function()
# except Exception as e:
# print('Error: %s' %e)
# return 0
# after = time.time()
# took = (after - before) if success else 0
# return took
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
, which may contain function names, class names, or code. Output only the next line. | took = time_took(_run) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink"
MAX_TIME_S = 1
def _run():
<|code_end|>
, predict the next line using imports from the current file:
import os
from utils.time import time_took
from utils.process import run_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context including class names, function names, and sometimes code from other files:
# Path: utils/time.py
# def time_took(function):
# before = time.time()
# try:
# success = function()
# except Exception as e:
# print('Error: %s' %e)
# return 0
# after = time.time()
# took = (after - before) if success else 0
# return took
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | run_cmd(cmd_pattern %v4l_get_current_device()) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink"
MAX_TIME_S = 1
def _run():
<|code_end|>
. Write the next line using the current file imports:
import os
from utils.time import time_took
from utils.process import run_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context from other files:
# Path: utils/time.py
# def time_took(function):
# before = time.time()
# try:
# success = function()
# except Exception as e:
# print('Error: %s' %e)
# return 0
# after = time.time()
# took = (after - before) if success else 0
# return took
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
, which may include functions, classes, or code. Output only the next line. | run_cmd(cmd_pattern %v4l_get_current_device()) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink"
def run():
input('Please make sure that input is NOT connected')
print('Running test')
<|code_end|>
with the help of current file imports:
import os
from utils.process import check_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context from other files:
# Path: utils/process.py
# def check_cmd(cmd, shell=False, complain=True):
# try:
# run_cmd(cmd, shell=shell)
# return True, 'no errors'
# except Exception as e:
# if complain:
# print(e)
# return False, e
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
, which may contain function names, class names, or code. Output only the next line. | result, info = check_cmd(cmd_pattern %v4l_get_current_device()) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=1 ! fakesink"
def run():
input('Please make sure that input is NOT connected')
print('Running test')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from utils.process import check_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context:
# Path: utils/process.py
# def check_cmd(cmd, shell=False, complain=True):
# try:
# run_cmd(cmd, shell=shell)
# return True, 'no errors'
# except Exception as e:
# if complain:
# print(e)
# return False, e
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
which might include code, classes, or functions. Output only the next line. | result, info = check_cmd(cmd_pattern %v4l_get_current_device()) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
COLORSPACES_BPP = {
'I420': 12,
'YUY2': 16,
'UYVY': 16,
'RGB': 24,
'RGBA': 32,
'NV12': 12,
}
TMP_BUF_FILE = 'tmp.raw'
def get_buffer_size_bytes(colorspace, width, height):
bpp = COLORSPACES_BPP[colorspace]
return int(round(width*height*bpp/8))
RAW_BUF_FILE = '/tmp/buf.raw'
TEMP_BUF_FILE = 'tmp.raw'
def get_num_buffers_for_path(colorspace, width, height, raw_buf_file, max_buffers=1000):
bufsize = get_buffer_size_bytes(colorspace, width, height)
<|code_end|>
with the help of current file imports:
import os
from utils.mem import get_free_space_bytes
from utils.files import check_temp_path
from utils.process import run_cmd
and context from other files:
# Path: utils/mem.py
# def get_free_space_bytes(path="/tmp"):
# cmd = "/bin/df %s --output=avail | tail -n 1" %path
# return int(get_stdout(cmd, shell=True))*1024
#
# Path: utils/files.py
# def check_temp_path(path='/tmp'):
# path = os.path.dirname(path)
# if not check_path_is_tmpfs(path):
# print('Path %s is not a tmpfs' % path)
# return False
# if not check_path_is_writable(path):
# print('Path %s is not writable' % path)
# return False
# return True
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
, which may contain function names, class names, or code. Output only the next line. | memsize = get_free_space_bytes(os.path.dirname(os.path.abspath(raw_buf_file))) |
Continue the code snippet: <|code_start|># Copyright 2015, Florent Thiery
COLORSPACES_BPP = {
'I420': 12,
'YUY2': 16,
'UYVY': 16,
'RGB': 24,
'RGBA': 32,
'NV12': 12,
}
TMP_BUF_FILE = 'tmp.raw'
def get_buffer_size_bytes(colorspace, width, height):
bpp = COLORSPACES_BPP[colorspace]
return int(round(width*height*bpp/8))
RAW_BUF_FILE = '/tmp/buf.raw'
TEMP_BUF_FILE = 'tmp.raw'
def get_num_buffers_for_path(colorspace, width, height, raw_buf_file, max_buffers=1000):
bufsize = get_buffer_size_bytes(colorspace, width, height)
memsize = get_free_space_bytes(os.path.dirname(os.path.abspath(raw_buf_file)))
return min(int(0.45*memsize/bufsize), max_buffers)
def generate_buffers_from_file(location, colorspace, width, height, raw_buf_file=RAW_BUF_FILE, framerate=30, num_buffers=None, max_buffers=1000):
if not os.path.exists(location):
print("Sample %s not found, skipping" % location)
return None, None, None
<|code_end|>
. Use current file imports:
import os
from utils.mem import get_free_space_bytes
from utils.files import check_temp_path
from utils.process import run_cmd
and context (classes, functions, or code) from other files:
# Path: utils/mem.py
# def get_free_space_bytes(path="/tmp"):
# cmd = "/bin/df %s --output=avail | tail -n 1" %path
# return int(get_stdout(cmd, shell=True))*1024
#
# Path: utils/files.py
# def check_temp_path(path='/tmp'):
# path = os.path.dirname(path)
# if not check_path_is_tmpfs(path):
# print('Path %s is not a tmpfs' % path)
# return False
# if not check_path_is_writable(path):
# print('Path %s is not writable' % path)
# return False
# return True
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
. Output only the next line. | if not check_temp_path(raw_buf_file): |
Given the code snippet: <|code_start|> memsize = get_free_space_bytes(os.path.dirname(os.path.abspath(tmp_location)))
# assumption: 20 Mbits/s file, build 1s blocks
#blocksize = int(20*1000*1000/8)
# FIXME: why is gst-launch-1.0 filesrc location=samples/1080p.mp4 num-buffers=60 blocksize=2500000 ! decodebin ! videoscale ! video/x-raw\,\ format\=\(string\)I420\,\ width\=\(int\)1920\,\ height\=\(int\)1080\,\ framerate\=\(fraction\)30/1 ! filesink location=samples/tmp.raw
# generating only 53 buffers ?
# FIXME: try not to convert the whole file
tmp_num_buffers = 1000
#tmp_max_size = tmp_num_buffers * blocksize
#if tmp_max_size > memsize:
# print('Not enough space for the whole intermediate raw sample')
pattern_caps = "video/x-raw\,\ format\=\(string\){colorspace}\,\ width\=\(int\){width}\,\ height\=\(int\){height}\,\ framerate\=\(fraction\){framerate}/1"
format_dict = {
'num_buffers': num_buffers,
'width': width,
'height': height,
'colorspace': colorspace,
'framerate': framerate,
'raw_buf_file': raw_buf_file,
'location': location,
'blocksize': bufsize,
'tmp_location': tmp_location,
'tmp_num_buffers': tmp_num_buffers,
}
# vaapi decoder sometimes decodes 1080p as 1920x1088 frames, hence the videoscale
# add videoconvert to fix https://bugzilla.gnome.org/show_bug.cgi?id=772457
#pattern_gen_buf = "gst-launch-1.0 filesrc location={location} num-buffers={tmp_num_buffers} blocksize={blocksize} ! decodebin ! videoscale ! %s ! filesink location={tmp_location}" % pattern_caps
pattern_gen_buf = "gst-launch-1.0 filesrc location={location} num-buffers={tmp_num_buffers} ! decodebin ! videoconvert ! videoscale ! %s ! filesink location={tmp_location}" % pattern_caps
cmd = pattern_gen_buf.format(**format_dict)
<|code_end|>
, generate the next line using the imports in this file:
import os
from utils.mem import get_free_space_bytes
from utils.files import check_temp_path
from utils.process import run_cmd
and context (functions, classes, or occasionally code) from other files:
# Path: utils/mem.py
# def get_free_space_bytes(path="/tmp"):
# cmd = "/bin/df %s --output=avail | tail -n 1" %path
# return int(get_stdout(cmd, shell=True))*1024
#
# Path: utils/files.py
# def check_temp_path(path='/tmp'):
# path = os.path.dirname(path)
# if not check_path_is_tmpfs(path):
# print('Path %s is not a tmpfs' % path)
# return False
# if not check_path_is_writable(path):
# print('Path %s is not writable' % path)
# return False
# return True
#
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
. Output only the next line. | run_cmd(cmd) |
Here is a snippet: <|code_start|> 'UYVY',
'RGB',
'RGBA'
]
def get_test_banner():
info = "glimagesink benchmark, GPU: %s CPU: %s" %(hw.gpu(), hw.cpu())
info += "\nTest\tFramerate"
return info
def run():
# Ensure that we are not limited by vblank
os.environ['vblank_mode'] = '0'
info = get_test_banner()
for gl_platform in GST_GL_PLATFORMS:
os.environ['GST_GL_PLATFORM'] = gl_platform
gl_windows = GST_GL_WINDOW[gl_platform]
for gl_window in gl_windows:
os.environ['GST_GL_WINDOW'] = gl_window
for gl_api in GST_GL_API:
os.environ['GST_GL_API'] = gl_api
for colorspace in CSP:
for resolution in RESOLUTIONS:
w, h = resolution[0], resolution[1]
testname = "%s %s %s %sx%s %s" %(gl_platform, gl_window, gl_api, w, h, colorspace)
num_buffers, bufsize, caps = video.generate_buffers_from_pattern(colorspace, w, h, RAW_BUF_FILE, max_buffers=MAX_BUFFERS)
cmd = cmd_pattern %(bufsize, caps)
<|code_end|>
. Write the next line using the current file imports:
import os
import utils.video as video
import utils.hardware as hw
from utils.time import time_took
from utils.process import run_gst_cmd
from utils.colors import print_red
from utils.run import run_test
and context from other files:
# Path: utils/time.py
# def time_took(function):
# before = time.time()
# try:
# success = function()
# except Exception as e:
# print('Error: %s' %e)
# return 0
# after = time.time()
# took = (after - before) if success else 0
# return took
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
, which may include functions, classes, or code. Output only the next line. | took = run_gst_cmd(cmd) |
Given the code snippet: <|code_start|> 'RGBA'
]
def get_test_banner():
info = "glimagesink benchmark, GPU: %s CPU: %s" %(hw.gpu(), hw.cpu())
info += "\nTest\tFramerate"
return info
def run():
# Ensure that we are not limited by vblank
os.environ['vblank_mode'] = '0'
info = get_test_banner()
for gl_platform in GST_GL_PLATFORMS:
os.environ['GST_GL_PLATFORM'] = gl_platform
gl_windows = GST_GL_WINDOW[gl_platform]
for gl_window in gl_windows:
os.environ['GST_GL_WINDOW'] = gl_window
for gl_api in GST_GL_API:
os.environ['GST_GL_API'] = gl_api
for colorspace in CSP:
for resolution in RESOLUTIONS:
w, h = resolution[0], resolution[1]
testname = "%s %s %s %sx%s %s" %(gl_platform, gl_window, gl_api, w, h, colorspace)
num_buffers, bufsize, caps = video.generate_buffers_from_pattern(colorspace, w, h, RAW_BUF_FILE, max_buffers=MAX_BUFFERS)
cmd = cmd_pattern %(bufsize, caps)
took = run_gst_cmd(cmd)
if took <= 0:
<|code_end|>
, generate the next line using the imports in this file:
import os
import utils.video as video
import utils.hardware as hw
from utils.time import time_took
from utils.process import run_gst_cmd
from utils.colors import print_red
from utils.run import run_test
and context (functions, classes, or occasionally code) from other files:
# Path: utils/time.py
# def time_took(function):
# before = time.time()
# try:
# success = function()
# except Exception as e:
# print('Error: %s' %e)
# return 0
# after = time.time()
# took = (after - before) if success else 0
# return took
#
# Path: utils/process.py
# def run_gst_cmd(cmd):
# try:
# rc, stdout, stderr = run_cmd(cmd, shell=False)
# took = parse_gst_execution_time(stdout)
# except Exception as e:
# print(e)
# took = 0
# return took
#
# Path: utils/colors.py
# def print_red(text):
# print("%s%s%s" %(Colors.RED, text, Colors.DEFAULT))
. Output only the next line. | print_red('test %s failed' %testname) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
framerates = [60, 30, 25]
resolutions = [
(3840, 2160),
(1920, 1200),
(1920, 1080),
(1280, 720),
(1024, 768),
]
cmd_pattern = 'gst-launch-1.0 v4l2src num-buffers=1 device=%s ! "video/x-raw, width=(int)%s, height=(int)%s, framerate=(fraction)%s/1" ! fakesink'
def run():
results = list()
at_least_one_success = False
for f in framerates:
for r in resolutions:
info = "Scaling test %sx%s@%s" %(r[0], r[1], f)
cmd = cmd_pattern %(v4l_get_current_device(), r[0], r[1], f)
try:
<|code_end|>
, determine the next line of code. You have imports:
import os
from utils.process import run_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context (class names, function names, or code) available:
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | run_cmd(cmd) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
framerates = [60, 30, 25]
resolutions = [
(3840, 2160),
(1920, 1200),
(1920, 1080),
(1280, 720),
(1024, 768),
]
cmd_pattern = 'gst-launch-1.0 v4l2src num-buffers=1 device=%s ! "video/x-raw, width=(int)%s, height=(int)%s, framerate=(fraction)%s/1" ! fakesink'
def run():
results = list()
at_least_one_success = False
for f in framerates:
for r in resolutions:
info = "Scaling test %sx%s@%s" %(r[0], r[1], f)
<|code_end|>
. Use current file imports:
(import os
from utils.process import run_cmd
from utils.v4l import v4l_get_current_device
from utils.run import run_test)
and context including class names, function names, or small code snippets from other files:
# Path: utils/process.py
# def run_cmd(cmd, shell=False):
# env = dict(os.environ)
# env["LANG"] = "C"
# if shell:
# args = cmd
# else:
# args = shlex.split(cmd)
# p = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=shell)
# stdout, stderr = p.communicate()
# rc = p.returncode
# if rc != 0:
# if '|' in cmd:
# raise Exception('Command %s failed, maybe shell=True is required' %cmd)
# else:
# raise Exception('Command %s failed, error: %s' % (cmd, stderr))
# elif contains_errors(stderr):
# raise Exception('Command %s had an error' %cmd)
# return rc, stdout, stderr
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | cmd = cmd_pattern %(v4l_get_current_device(), r[0], r[1], f) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=10 ! fakesink silent=false -v | grep chain"
def run():
failed = False
for i in range(10):
success, msg = _run()
if not success:
return success, msg
return success, msg
def _run():
try:
<|code_end|>
, generate the next line using the imports in this file:
import os
from utils.process import get_stdout
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context (functions, classes, or occasionally code) from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | data = get_stdout(cmd_pattern %v4l_get_current_device(), shell=True).strip().split('\n') |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Florent Thiery
cmd_pattern = "gst-launch-1.0 v4l2src device=%s num-buffers=10 ! fakesink silent=false -v | grep chain"
def run():
failed = False
for i in range(10):
success, msg = _run()
if not success:
return success, msg
return success, msg
def _run():
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from utils.process import get_stdout
from utils.v4l import v4l_get_current_device
from utils.run import run_test
and context (classes, functions, sometimes code) from other files:
# Path: utils/process.py
# def get_stdout(cmd, shell=False):
# rc, stdout, stderr = run_cmd(cmd, shell=shell)
# return stdout
#
# Path: utils/v4l.py
# def v4l_get_current_device():
# return os.environ.get('V4L2_TEST_DEVICE', '/dev/video0')
. Output only the next line. | data = get_stdout(cmd_pattern %v4l_get_current_device(), shell=True).strip().split('\n') |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError: # pragma: no cover
# Python < 2.7
logger = logging.getLogger('staticgen')
class StaticgenPool(object):
def __init__(self):
self._discovered = False
self.modules = {}
def log_error(self, message):
logger.error(message)
<|code_end|>
. Use current file imports:
(import logging
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .exceptions import StaticgenError
from importlib import import_module
from django.utils.importlib import import_module
from .staticgen_views import StaticgenView)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
. Output only the next line. | if not settings.STATICGEN_FAIL_SILENTLY: |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError: # pragma: no cover
# Python < 2.7
logger = logging.getLogger('staticgen')
class StaticgenPool(object):
def __init__(self):
self._discovered = False
self.modules = {}
def log_error(self, message):
logger.error(message)
if not settings.STATICGEN_FAIL_SILENTLY:
<|code_end|>
. Write the next line using the current file imports:
import logging
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .exceptions import StaticgenError
from importlib import import_module
from django.utils.importlib import import_module
from .staticgen_views import StaticgenView
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | raise StaticgenError(message) |
Predict the next line for this snippet: <|code_start|>
class TestStaticgenStorage(TestCase):
@mock_s3
def _upload(self, storage, folder):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# upload a file
file_name = 's3dummyfile.txt'
file_text = 'django-staticgen is awesome!'
file_content = ContentFile(file_text)
storage.save(file_name, file_content)
# confirm it was uploaded
self.assertTrue(storage.exists(file_name))
# check folder
temp_file = storage.open(file_name, 'r')
expected_path = '{folder}/{file_name}'.format(folder=folder, file_name=file_name)
self.assertEqual(temp_file.key.name, expected_path)
temp_file.close()
def test_s3_defaultfiles_storage(self):
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.staticgen_storages import StaticgenDefaultFilesStorage, StaticgenStaticFilesStorage
and context from other files:
# Path: staticgen/staticgen_storages.py
# class StaticgenDefaultFilesStorage(S3BotoStorage):
# location = settings.AWS_S3_DEFAULT_FILES_LOCATION
#
# class StaticgenStaticFilesStorage(S3BotoStorage):
# location = settings.AWS_S3_STATIC_FILES_LOCATION
, which may contain function names, class names, or code. Output only the next line. | self._upload(StaticgenDefaultFilesStorage(), settings.AWS_S3_DEFAULT_FILES_LOCATION) |
Continue the code snippet: <|code_start|>
class TestStaticgenStorage(TestCase):
@mock_s3
def _upload(self, storage, folder):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# upload a file
file_name = 's3dummyfile.txt'
file_text = 'django-staticgen is awesome!'
file_content = ContentFile(file_text)
storage.save(file_name, file_content)
# confirm it was uploaded
self.assertTrue(storage.exists(file_name))
# check folder
temp_file = storage.open(file_name, 'r')
expected_path = '{folder}/{file_name}'.format(folder=folder, file_name=file_name)
self.assertEqual(temp_file.key.name, expected_path)
temp_file.close()
def test_s3_defaultfiles_storage(self):
self._upload(StaticgenDefaultFilesStorage(), settings.AWS_S3_DEFAULT_FILES_LOCATION)
def test_s3_staticfiles_storage(self):
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.staticgen_storages import StaticgenDefaultFilesStorage, StaticgenStaticFilesStorage
and context (classes, functions, or code) from other files:
# Path: staticgen/staticgen_storages.py
# class StaticgenDefaultFilesStorage(S3BotoStorage):
# location = settings.AWS_S3_DEFAULT_FILES_LOCATION
#
# class StaticgenStaticFilesStorage(S3BotoStorage):
# location = settings.AWS_S3_STATIC_FILES_LOCATION
. Output only the next line. | self._upload(StaticgenStaticFilesStorage(), settings.AWS_S3_STATIC_FILES_LOCATION) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestCommands(TestCase):
@mock_s3
def test_publish(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# actual test
call_command('staticgen_publish')
# Every page should be published – 16 pages in total
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.core.management import call_command
from django.test import TestCase
from boto import connect_s3
from mock import patch
from moto import mock_s3
from staticgen.models import Page)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
. Output only the next line. | self.assertEqual(Page.objects.published().count(), 16) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
logger = logging.getLogger('staticgen')
class StaticgenView(object):
is_paginated = False
def __init__(self, *args, **kwargs):
super(StaticgenView, self).__init__(*args, **kwargs)
self.client = Client(SERVER_NAME=get_static_site_domain())
def items(self):
return []
def log_error(self, message):
logger.error(message)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from django.core.urlresolvers import resolve, reverse
from django.shortcuts import resolve_url
from django.test import Client
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_success
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
. Output only the next line. | if not settings.STATICGEN_FAIL_SILENTLY: |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
logger = logging.getLogger('staticgen')
class StaticgenView(object):
is_paginated = False
def __init__(self, *args, **kwargs):
super(StaticgenView, self).__init__(*args, **kwargs)
self.client = Client(SERVER_NAME=get_static_site_domain())
def items(self):
return []
def log_error(self, message):
logger.error(message)
if not settings.STATICGEN_FAIL_SILENTLY:
<|code_end|>
using the current file's imports:
import logging
from django.core.urlresolvers import resolve, reverse
from django.shortcuts import resolve_url
from django.test import Client
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_success
and any relevant context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
. Output only the next line. | raise StaticgenError(message) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
logger = logging.getLogger('staticgen')
class StaticgenView(object):
is_paginated = False
def __init__(self, *args, **kwargs):
super(StaticgenView, self).__init__(*args, **kwargs)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from django.core.urlresolvers import resolve, reverse
from django.shortcuts import resolve_url
from django.test import Client
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_success
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
. Output only the next line. | self.client = Client(SERVER_NAME=get_static_site_domain()) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenPageAdmin(TestCase):
def setUp(self):
for id in range(1, 6):
path = '/page{0}/'.format(id)
page = Page.objects.create(
pk=id,
path=path, site_id=settings.SITE_ID,
publisher_state=Page.PUBLISHER_STATE_PUBLISHED)
change_message = 'Added page {page}'.format(page=force_text(page))
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils.encoding import force_text
from mock import patch
from staticgen.models import LogEntry, Page
and context from other files:
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
, which may contain function names, class names, or code. Output only the next line. | LogEntry.objects.log_action(change_message, page_id=id) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenPageAdmin(TestCase):
def setUp(self):
for id in range(1, 6):
path = '/page{0}/'.format(id)
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils.encoding import force_text
from mock import patch
from staticgen.models import LogEntry, Page
and context (class names, function names, or code) available:
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
. Output only the next line. | page = Page.objects.create( |
Predict the next line for this snippet: <|code_start|>logger = logging.getLogger('staticgen')
class UrlRegistry(object):
def __init__(self):
self.visited = set()
self.to_visit = set()
def enqueue(self, url):
if url and url not in self.visited:
self.to_visit.add(url)
def __iter__(self):
while self.to_visit:
url = self.to_visit.pop()
self.visited.add(url)
yield url
class StaticgenCrawler(object):
def __init__(self):
current_site = Site.objects.get_current()
self.base_domain = current_site.domain
self.url_registry = UrlRegistry()
self.client = Client(SERVER_NAME=get_static_site_domain())
def log_error(self, message):
logger.error(message)
<|code_end|>
with the help of current file imports:
import logging
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.translation import ugettext_lazy as _
from django.test import Client
from bs4 import BeautifulSoup
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
, which may contain function names, class names, or code. Output only the next line. | if not settings.STATICGEN_FAIL_SILENTLY: |
Given snippet: <|code_start|>
class UrlRegistry(object):
def __init__(self):
self.visited = set()
self.to_visit = set()
def enqueue(self, url):
if url and url not in self.visited:
self.to_visit.add(url)
def __iter__(self):
while self.to_visit:
url = self.to_visit.pop()
self.visited.add(url)
yield url
class StaticgenCrawler(object):
def __init__(self):
current_site = Site.objects.get_current()
self.base_domain = current_site.domain
self.url_registry = UrlRegistry()
self.client = Client(SERVER_NAME=get_static_site_domain())
def log_error(self, message):
logger.error(message)
if not settings.STATICGEN_FAIL_SILENTLY:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.translation import ugettext_lazy as _
from django.test import Client
from bs4 import BeautifulSoup
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
which might include code, classes, or functions. Output only the next line. | raise StaticgenError(message) |
Here is a snippet: <|code_start|>except ImportError: # pragma: no cover
# Python 2.X
logger = logging.getLogger('staticgen')
class UrlRegistry(object):
def __init__(self):
self.visited = set()
self.to_visit = set()
def enqueue(self, url):
if url and url not in self.visited:
self.to_visit.add(url)
def __iter__(self):
while self.to_visit:
url = self.to_visit.pop()
self.visited.add(url)
yield url
class StaticgenCrawler(object):
def __init__(self):
current_site = Site.objects.get_current()
self.base_domain = current_site.domain
self.url_registry = UrlRegistry()
<|code_end|>
. Write the next line using the current file imports:
import logging
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.translation import ugettext_lazy as _
from django.test import Client
from bs4 import BeautifulSoup
from .conf import settings
from .exceptions import StaticgenError
from .helpers import get_static_site_domain
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
, which may include functions, classes, or code. Output only the next line. | self.client = Client(SERVER_NAME=get_static_site_domain()) |
Based on the snippet: <|code_start|>
from __future__ import unicode_literals
class ExampleStaticView(StaticgenView):
def items(self):
return (
'homepage',
'error_page',
'redirect_home',
'django.contrib.sitemaps.views.sitemap',
)
class ExampleListView(StaticgenView):
is_paginated = True
def items(self):
return ('post_list', )
class ExampleDetailView(StaticgenView):
def items(self):
return Post.objects.all()
<|code_end|>
, predict the immediate next line with the help of imports:
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
and context (classes, functions, sometimes code) from other files:
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# def log_error(self, message):
# def register(self, cls):
# def autodiscover(self):
# def get_urls(self):
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/models.py
# class Post(models.Model):
# title = models.CharField(max_length=100)
# body = models.TextField(blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('post_detail', args=[str(self.id)])
. Output only the next line. | staticgen_pool.register(ExampleStaticView) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ExampleStaticView(StaticgenView):
def items(self):
return (
'homepage',
'error_page',
'redirect_home',
'django.contrib.sitemaps.views.sitemap',
)
class ExampleListView(StaticgenView):
is_paginated = True
def items(self):
return ('post_list', )
class ExampleDetailView(StaticgenView):
def items(self):
<|code_end|>
. Use current file imports:
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
and context (classes, functions, or code) from other files:
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# def log_error(self, message):
# def register(self, cls):
# def autodiscover(self):
# def get_urls(self):
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/models.py
# class Post(models.Model):
# title = models.CharField(max_length=100)
# body = models.TextField(blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('post_detail', args=[str(self.id)])
. Output only the next line. | return Post.objects.all() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ExampleSitemap(Sitemap):
changefreq = 'never'
priority = 0.5
def items(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib.sitemaps import Sitemap
from .models import Post
and context (functions, classes, or occasionally code) from other files:
# Path: example/models.py
# class Post(models.Model):
# title = models.CharField(max_length=100)
# body = models.TextField(blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('post_detail', args=[str(self.id)])
. Output only the next line. | return Post.objects.all() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class IndexView(TemplateView):
template_name = 'example/home.html'
class ErrorView(TemplateView):
template_name = 'example/error.html'
class PostListView(ListView):
<|code_end|>
. Use current file imports:
(from django.views.generic import DetailView, ListView, TemplateView, RedirectView
from .models import Post)
and context including class names, function names, or small code snippets from other files:
# Path: example/models.py
# class Post(models.Model):
# title = models.CharField(max_length=100)
# body = models.TextField(blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('post_detail', args=[str(self.id)])
. Output only the next line. | model = Post |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class PostAdmin(admin.ModelAdmin):
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from .models import Post
and context:
# Path: example/models.py
# class Post(models.Model):
# title = models.CharField(max_length=100)
# body = models.TextField(blank=True)
# created = models.DateTimeField(auto_now_add=True)
#
# def __str__(self):
# return self.title
#
# def get_absolute_url(self):
# return reverse('post_detail', args=[str(self.id)])
which might include code, classes, or functions. Output only the next line. | admin.site.register(Post, PostAdmin) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenContextProcessors(TestCase):
def test_request_with_custom_header(self):
request = Mock()
request.META = {'HTTP_X_STATICGEN_PUBLISHER': True}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf import settings
from django.test import TestCase
from mock import Mock
from staticgen.context_processors import staticgen_publisher
and context:
# Path: staticgen/context_processors.py
# def staticgen_publisher(request):
# context = {}
#
# is_publishing = request.META.get('HTTP_X_STATICGEN_PUBLISHER', False)
# context['STATICGEN_IS_PUBLISHING'] = is_publishing
#
# current_site = Site.objects.get_current()
#
# base_url = current_site.domain
# if is_publishing:
# base_url = get_static_site_domain()
#
# context['STATICGEN_BASE_URL'] = base_url
#
# return context
which might include code, classes, or functions. Output only the next line. | context = staticgen_publisher(request) |
Next line prediction: <|code_start|>
from __future__ import unicode_literals
try:
except ImportError: # pragma: no cover
# Python 2.X
logger = logging.getLogger('staticgen')
class PageQuerySet(models.QuerySet):
def changed(self):
return self.filter(publisher_state=self.model.PUBLISHER_STATE_CHANGED)
def pending(self):
return self.filter(publisher_state=self.model.PUBLISHER_STATE_DEFAULT)
def pending_and_changed(self):
return self.filter(
Q(publisher_state=self.model.PUBLISHER_STATE_DEFAULT) |
Q(publisher_state=self.model.PUBLISHER_STATE_CHANGED)
)
def published(self):
return self.filter(publisher_state=self.model.PUBLISHER_STATE_PUBLISHED)
<|code_end|>
. Use current file imports:
(import logging
import time
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .staticgen_pool import staticgen_pool
from .staticgen_crawler import StaticgenCrawler
from urllib.parse import urlparse
from urlparse import urlparse)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# def log_error(self, message):
# def register(self, cls):
# def autodiscover(self):
# def get_urls(self):
#
# Path: staticgen/staticgen_crawler.py
# class StaticgenCrawler(object):
#
# def __init__(self):
# current_site = Site.objects.get_current()
# self.base_domain = current_site.domain
# self.url_registry = UrlRegistry()
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def clean_url(self, url):
# url = url.lower().strip()
#
# special_links = [
# url.startswith(prefix) for prefix in ('mailto', 'tel', 'sms', 'skype', 'geo')]
#
# if any([url.startswith(settings.MEDIA_URL), # skip media files urls
# url.startswith(settings.STATIC_URL), # skip static files urls
# url.startswith('#')] + special_links): # skip anchors & special links e.g 'tel:'
# return None
#
# if url.startswith('/'):
# return url
#
# # strip web prefixes
# for prefix in ('http://', 'https://', 'www.', ):
# if url.startswith(prefix):
# url = url[len(prefix):]
#
# if not url.startswith(self.base_domain):
# return None
#
# return '//{url}'.format(url=url)
#
# def get_sitemap_url(self):
# sitemap_url = settings.STATICGEN_SITEMAP_URL
# if sitemap_url is None:
# try:
# # Try for the "global" sitemap URL.
# sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
# except NoReverseMatch:
# message = _('You did not provide a sitemap_url, '
# 'and the sitemap URL could not be auto-detected.')
# self.log_error(message)
#
# return sitemap_url
#
# def get_sitemap_links(self):
# urls = []
# sitemap_url = self.get_sitemap_url()
# if sitemap_url:
# response = self.client.get(sitemap_url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving sitemap: {sitemap_url} - Code: {code}').format(
# sitemap_url=sitemap_url, code=response.status_code)
# self.log_error(message)
# else:
# soup = BeautifulSoup(response.content, 'lxml')
# urls = [loc.get_text() for loc in soup.find_all('loc')]
#
# return urls
#
# @staticmethod
# def get_links(response):
# links = []
#
# if is_redirect(response.status_code):
# links.append(response['Location'])
#
# if is_success(response.status_code):
# soup = BeautifulSoup(response.content, 'lxml')
# for link in soup.find_all('a', href=True):
# links.append(link['href'])
#
# return links
#
# def get_urls(self):
# urls = []
#
# sitemap_links = self.get_sitemap_links()
# for url in sitemap_links:
# parsed_url = urlparse(url)
# self.url_registry.enqueue(parsed_url.path)
#
# for url in self.url_registry:
# urls.append(url)
#
# response = self.client.get(url)
# for link in self.get_links(response):
# cleaned_url = self.clean_url(link)
# if cleaned_url:
# parsed_url = urlparse(cleaned_url)
# self.url_registry.enqueue(parsed_url.path)
#
# urls = list(set(urls))
# urls.sort()
# return urls
. Output only the next line. | def on_site(self, site_id=settings.SITE_ID): |
Here is a snippet: <|code_start|> return self.get_queryset().pending()
def pending_and_changed(self):
return self.get_queryset().pending_and_changed()
def published(self):
return self.get_queryset().published()
def deleted(self):
return self.get_queryset().deleted()
def on_site(self, site_id=settings.SITE_ID):
return self.get_queryset().on_site(site_id=site_id)
def get_or_create_url(self, url, site_id=settings.SITE_ID):
parse_result = urlparse(url)
obj, created = self.model.objects.get_or_create(
site_id=site_id,
path=parse_result.path
)
return obj, created
def sync(self, site_id=settings.SITE_ID):
start_time = time.time()
urls = []
crawler = StaticgenCrawler()
urls.extend(crawler.get_urls())
<|code_end|>
. Write the next line using the current file imports:
import logging
import time
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .staticgen_pool import staticgen_pool
from .staticgen_crawler import StaticgenCrawler
from urllib.parse import urlparse
from urlparse import urlparse
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# def log_error(self, message):
# def register(self, cls):
# def autodiscover(self):
# def get_urls(self):
#
# Path: staticgen/staticgen_crawler.py
# class StaticgenCrawler(object):
#
# def __init__(self):
# current_site = Site.objects.get_current()
# self.base_domain = current_site.domain
# self.url_registry = UrlRegistry()
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def clean_url(self, url):
# url = url.lower().strip()
#
# special_links = [
# url.startswith(prefix) for prefix in ('mailto', 'tel', 'sms', 'skype', 'geo')]
#
# if any([url.startswith(settings.MEDIA_URL), # skip media files urls
# url.startswith(settings.STATIC_URL), # skip static files urls
# url.startswith('#')] + special_links): # skip anchors & special links e.g 'tel:'
# return None
#
# if url.startswith('/'):
# return url
#
# # strip web prefixes
# for prefix in ('http://', 'https://', 'www.', ):
# if url.startswith(prefix):
# url = url[len(prefix):]
#
# if not url.startswith(self.base_domain):
# return None
#
# return '//{url}'.format(url=url)
#
# def get_sitemap_url(self):
# sitemap_url = settings.STATICGEN_SITEMAP_URL
# if sitemap_url is None:
# try:
# # Try for the "global" sitemap URL.
# sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
# except NoReverseMatch:
# message = _('You did not provide a sitemap_url, '
# 'and the sitemap URL could not be auto-detected.')
# self.log_error(message)
#
# return sitemap_url
#
# def get_sitemap_links(self):
# urls = []
# sitemap_url = self.get_sitemap_url()
# if sitemap_url:
# response = self.client.get(sitemap_url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving sitemap: {sitemap_url} - Code: {code}').format(
# sitemap_url=sitemap_url, code=response.status_code)
# self.log_error(message)
# else:
# soup = BeautifulSoup(response.content, 'lxml')
# urls = [loc.get_text() for loc in soup.find_all('loc')]
#
# return urls
#
# @staticmethod
# def get_links(response):
# links = []
#
# if is_redirect(response.status_code):
# links.append(response['Location'])
#
# if is_success(response.status_code):
# soup = BeautifulSoup(response.content, 'lxml')
# for link in soup.find_all('a', href=True):
# links.append(link['href'])
#
# return links
#
# def get_urls(self):
# urls = []
#
# sitemap_links = self.get_sitemap_links()
# for url in sitemap_links:
# parsed_url = urlparse(url)
# self.url_registry.enqueue(parsed_url.path)
#
# for url in self.url_registry:
# urls.append(url)
#
# response = self.client.get(url)
# for link in self.get_links(response):
# cleaned_url = self.clean_url(link)
# if cleaned_url:
# parsed_url = urlparse(cleaned_url)
# self.url_registry.enqueue(parsed_url.path)
#
# urls = list(set(urls))
# urls.sort()
# return urls
, which may include functions, classes, or code. Output only the next line. | urls.extend(staticgen_pool.get_urls()) |
Next line prediction: <|code_start|> return self.get_queryset().changed()
def pending(self):
return self.get_queryset().pending()
def pending_and_changed(self):
return self.get_queryset().pending_and_changed()
def published(self):
return self.get_queryset().published()
def deleted(self):
return self.get_queryset().deleted()
def on_site(self, site_id=settings.SITE_ID):
return self.get_queryset().on_site(site_id=site_id)
def get_or_create_url(self, url, site_id=settings.SITE_ID):
parse_result = urlparse(url)
obj, created = self.model.objects.get_or_create(
site_id=site_id,
path=parse_result.path
)
return obj, created
def sync(self, site_id=settings.SITE_ID):
start_time = time.time()
urls = []
<|code_end|>
. Use current file imports:
(import logging
import time
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Q
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from .conf import settings
from .staticgen_pool import staticgen_pool
from .staticgen_crawler import StaticgenCrawler
from urllib.parse import urlparse
from urlparse import urlparse)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# def log_error(self, message):
# def register(self, cls):
# def autodiscover(self):
# def get_urls(self):
#
# Path: staticgen/staticgen_crawler.py
# class StaticgenCrawler(object):
#
# def __init__(self):
# current_site = Site.objects.get_current()
# self.base_domain = current_site.domain
# self.url_registry = UrlRegistry()
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def clean_url(self, url):
# url = url.lower().strip()
#
# special_links = [
# url.startswith(prefix) for prefix in ('mailto', 'tel', 'sms', 'skype', 'geo')]
#
# if any([url.startswith(settings.MEDIA_URL), # skip media files urls
# url.startswith(settings.STATIC_URL), # skip static files urls
# url.startswith('#')] + special_links): # skip anchors & special links e.g 'tel:'
# return None
#
# if url.startswith('/'):
# return url
#
# # strip web prefixes
# for prefix in ('http://', 'https://', 'www.', ):
# if url.startswith(prefix):
# url = url[len(prefix):]
#
# if not url.startswith(self.base_domain):
# return None
#
# return '//{url}'.format(url=url)
#
# def get_sitemap_url(self):
# sitemap_url = settings.STATICGEN_SITEMAP_URL
# if sitemap_url is None:
# try:
# # Try for the "global" sitemap URL.
# sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
# except NoReverseMatch:
# message = _('You did not provide a sitemap_url, '
# 'and the sitemap URL could not be auto-detected.')
# self.log_error(message)
#
# return sitemap_url
#
# def get_sitemap_links(self):
# urls = []
# sitemap_url = self.get_sitemap_url()
# if sitemap_url:
# response = self.client.get(sitemap_url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving sitemap: {sitemap_url} - Code: {code}').format(
# sitemap_url=sitemap_url, code=response.status_code)
# self.log_error(message)
# else:
# soup = BeautifulSoup(response.content, 'lxml')
# urls = [loc.get_text() for loc in soup.find_all('loc')]
#
# return urls
#
# @staticmethod
# def get_links(response):
# links = []
#
# if is_redirect(response.status_code):
# links.append(response['Location'])
#
# if is_success(response.status_code):
# soup = BeautifulSoup(response.content, 'lxml')
# for link in soup.find_all('a', href=True):
# links.append(link['href'])
#
# return links
#
# def get_urls(self):
# urls = []
#
# sitemap_links = self.get_sitemap_links()
# for url in sitemap_links:
# parsed_url = urlparse(url)
# self.url_registry.enqueue(parsed_url.path)
#
# for url in self.url_registry:
# urls.append(url)
#
# response = self.client.get(url)
# for link in self.get_links(response):
# cleaned_url = self.clean_url(link)
# if cleaned_url:
# parsed_url = urlparse(cleaned_url)
# self.url_registry.enqueue(parsed_url.path)
#
# urls = list(set(urls))
# urls.sort()
# return urls
. Output only the next line. | crawler = StaticgenCrawler() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class Command(BaseCommand):
help = 'Publish/update all registered pages to Amazon S3 via a Celery task.'
def handle(self, *args, **options):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
from staticgen.tasks import publish_pages
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
. Output only the next line. | publish_pages.delay() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap
and context from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
, which may contain function names, class names, or code. Output only the next line. | {'sitemaps': override_sitemaps_domain(sitemaps)}, |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': override_sitemaps_domain(sitemaps)},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', IndexView.as_view(), name='homepage'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
. Output only the next line. | url(r'^error\.html$', ErrorView.as_view(), name='error_page'), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': override_sitemaps_domain(sitemaps)},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap
and context from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
, which may contain function names, class names, or code. Output only the next line. | url(r'^$', IndexView.as_view(), name='homepage'), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': override_sitemaps_domain(sitemaps)},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', IndexView.as_view(), name='homepage'),
url(r'^error\.html$', ErrorView.as_view(), name='error_page'),
url(r'^redirect/$', RedirectToHomeView.as_view(), name='redirect_home'),
url(r'^posts/$', PostListView.as_view(), name='post_list'),
url(r'^posts/page/(?P<page>\d+)/$', PostListView.as_view(), name='post_list'),
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap
and context from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
, which may contain function names, class names, or code. Output only the next line. | url(r'^posts/(?P<pk>[-\w]+)/$', PostDetailView.as_view(), name='post_detail'), |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': override_sitemaps_domain(sitemaps)},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', IndexView.as_view(), name='homepage'),
url(r'^error\.html$', ErrorView.as_view(), name='error_page'),
url(r'^redirect/$', RedirectToHomeView.as_view(), name='redirect_home'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
. Output only the next line. | url(r'^posts/$', PostListView.as_view(), name='post_list'), |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
'posts': ExampleSitemap
}
urlpatterns = patterns(
'',
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': override_sitemaps_domain(sitemaps)},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', IndexView.as_view(), name='homepage'),
url(r'^error\.html$', ErrorView.as_view(), name='error_page'),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap
and context (classes, functions, sometimes code) from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
. Output only the next line. | url(r'^redirect/$', RedirectToHomeView.as_view(), name='redirect_home'), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
admin.autodiscover()
sitemaps = {
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from staticgen.sitemaps import override_sitemaps_domain
from .views import ErrorView, IndexView, PostDetailView, PostListView, RedirectToHomeView
from .sitemaps import ExampleSitemap
and context from other files:
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
#
# Path: example/views.py
# class ErrorView(TemplateView):
# template_name = 'example/error.html'
#
# class IndexView(TemplateView):
# template_name = 'example/home.html'
#
# class PostDetailView(DetailView):
# model = Post
# context_object_name = 'post'
# template_name = 'example/post_detail.html'
#
# class PostListView(ListView):
# model = Post
# paginate_by = 5
# context_object_name = 'post_list'
# template_name = 'example/post_list.html'
#
# class RedirectToHomeView(RedirectView):
# permanent = False
# query_string = True
# pattern_name = 'homepage'
#
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
, which may contain function names, class names, or code. Output only the next line. | 'posts': ExampleSitemap |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenRoutablePageTemplateTag(TestCase):
def setUp(self):
self.rf = RequestFactory()
self.request = self.rf.get(reverse('post_list'))
self.context = {'request': self.request}
def test_routable_pageurl_templatetag(self):
<|code_end|>
. Use current file imports:
(from django.core.urlresolvers import reverse
from django.test import TestCase, RequestFactory
from staticgen.templatetags.staticgen_tags import routable_pageurl)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/templatetags/staticgen_tags.py
# @register.simple_tag(takes_context=True)
# def routable_pageurl(context, page=1, page_kwarg='page'):
# request = context['request']
#
# try:
# match = resolve(request.path_info)
# except Resolver404: # pragma: no cover
# pass
# else:
# if match.namespace:
# namespace = '{0}:'.format(match.namespace)
# else:
# namespace = ''
#
# current_url = '{namespace}{url_name}'.format(
# namespace=namespace, url_name=match.url_name)
#
# match.kwargs[page_kwarg] = page
# return reverse(current_url, args=match.args, kwargs=match.kwargs)
#
# return ''
. Output only the next line. | self.assertEqual(routable_pageurl(self.context, 2), '/posts/page/2/') |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenSitemapsDomainOverride(TestCase):
def test_domain_override(self):
<|code_end|>
using the current file's imports:
from django.test import TestCase
from example.sitemaps import ExampleSitemap
from staticgen.helpers import get_static_site_domain
from staticgen.sitemaps import override_sitemaps_domain
and any relevant context from other files:
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
. Output only the next line. | sitemaps = override_sitemaps_domain({'test': ExampleSitemap}) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenSitemapsDomainOverride(TestCase):
def test_domain_override(self):
sitemaps = override_sitemaps_domain({'test': ExampleSitemap})
sitemap = sitemaps['test']
if callable(sitemap):
sitemap = sitemap()
url = sitemap.get_urls()[0]
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from example.sitemaps import ExampleSitemap
from staticgen.helpers import get_static_site_domain
from staticgen.sitemaps import override_sitemaps_domain
and context (classes, functions, sometimes code) from other files:
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
. Output only the next line. | domain = 'http://{domain}'.format(domain=get_static_site_domain()) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenSitemapsDomainOverride(TestCase):
def test_domain_override(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from example.sitemaps import ExampleSitemap
from staticgen.helpers import get_static_site_domain
from staticgen.sitemaps import override_sitemaps_domain
and context including class names, function names, and sometimes code from other files:
# Path: example/sitemaps.py
# class ExampleSitemap(Sitemap):
# changefreq = 'never'
# priority = 0.5
#
# def items(self):
# return Post.objects.all()
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/sitemaps.py
# def override_sitemaps_domain(sitemaps):
# staticgen_sitemaps = {}
# for section, site in sitemaps.items():
# cls_name = 'Staticgen{name}'.format(name=site.__name__)
# staticgen_sitemaps[section] = type(cls_name, (StaticgenSitemap, site), {})
# return staticgen_sitemaps
. Output only the next line. | sitemaps = override_sitemaps_domain({'test': ExampleSitemap}) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenCrawler(TestCase):
def setUp(self):
self.crawler = StaticgenCrawler()
@override_settings(STATICGEN_SITEMAP_URL='sitemap.xml')
def test_get_sitemap_url_from_settings(self):
sitemap_url = self.crawler.get_sitemap_url()
self.assertEqual(sitemap_url, 'sitemap.xml')
def test_get_sitemap_url_autodiscover(self):
sitemap_url = self.crawler.get_sitemap_url()
self.assertEqual(sitemap_url, '/sitemap.xml')
@override_settings(ROOT_URLCONF=(), STATICGEN_FAIL_SILENTLY=False)
def test_get_sitemap_url_raises_error(self):
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.test import TestCase, override_settings
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_crawler import StaticgenCrawler
and context (class names, function names, or code) available:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_crawler.py
# class StaticgenCrawler(object):
#
# def __init__(self):
# current_site = Site.objects.get_current()
# self.base_domain = current_site.domain
# self.url_registry = UrlRegistry()
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def clean_url(self, url):
# url = url.lower().strip()
#
# special_links = [
# url.startswith(prefix) for prefix in ('mailto', 'tel', 'sms', 'skype', 'geo')]
#
# if any([url.startswith(settings.MEDIA_URL), # skip media files urls
# url.startswith(settings.STATIC_URL), # skip static files urls
# url.startswith('#')] + special_links): # skip anchors & special links e.g 'tel:'
# return None
#
# if url.startswith('/'):
# return url
#
# # strip web prefixes
# for prefix in ('http://', 'https://', 'www.', ):
# if url.startswith(prefix):
# url = url[len(prefix):]
#
# if not url.startswith(self.base_domain):
# return None
#
# return '//{url}'.format(url=url)
#
# def get_sitemap_url(self):
# sitemap_url = settings.STATICGEN_SITEMAP_URL
# if sitemap_url is None:
# try:
# # Try for the "global" sitemap URL.
# sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
# except NoReverseMatch:
# message = _('You did not provide a sitemap_url, '
# 'and the sitemap URL could not be auto-detected.')
# self.log_error(message)
#
# return sitemap_url
#
# def get_sitemap_links(self):
# urls = []
# sitemap_url = self.get_sitemap_url()
# if sitemap_url:
# response = self.client.get(sitemap_url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving sitemap: {sitemap_url} - Code: {code}').format(
# sitemap_url=sitemap_url, code=response.status_code)
# self.log_error(message)
# else:
# soup = BeautifulSoup(response.content, 'lxml')
# urls = [loc.get_text() for loc in soup.find_all('loc')]
#
# return urls
#
# @staticmethod
# def get_links(response):
# links = []
#
# if is_redirect(response.status_code):
# links.append(response['Location'])
#
# if is_success(response.status_code):
# soup = BeautifulSoup(response.content, 'lxml')
# for link in soup.find_all('a', href=True):
# links.append(link['href'])
#
# return links
#
# def get_urls(self):
# urls = []
#
# sitemap_links = self.get_sitemap_links()
# for url in sitemap_links:
# parsed_url = urlparse(url)
# self.url_registry.enqueue(parsed_url.path)
#
# for url in self.url_registry:
# urls.append(url)
#
# response = self.client.get(url)
# for link in self.get_links(response):
# cleaned_url = self.clean_url(link)
# if cleaned_url:
# parsed_url = urlparse(cleaned_url)
# self.url_registry.enqueue(parsed_url.path)
#
# urls = list(set(urls))
# urls.sort()
# return urls
. Output only the next line. | self.assertRaises(StaticgenError, self.crawler.get_sitemap_url) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenCrawler(TestCase):
def setUp(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.test import TestCase, override_settings
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_crawler import StaticgenCrawler
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_crawler.py
# class StaticgenCrawler(object):
#
# def __init__(self):
# current_site = Site.objects.get_current()
# self.base_domain = current_site.domain
# self.url_registry = UrlRegistry()
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def clean_url(self, url):
# url = url.lower().strip()
#
# special_links = [
# url.startswith(prefix) for prefix in ('mailto', 'tel', 'sms', 'skype', 'geo')]
#
# if any([url.startswith(settings.MEDIA_URL), # skip media files urls
# url.startswith(settings.STATIC_URL), # skip static files urls
# url.startswith('#')] + special_links): # skip anchors & special links e.g 'tel:'
# return None
#
# if url.startswith('/'):
# return url
#
# # strip web prefixes
# for prefix in ('http://', 'https://', 'www.', ):
# if url.startswith(prefix):
# url = url[len(prefix):]
#
# if not url.startswith(self.base_domain):
# return None
#
# return '//{url}'.format(url=url)
#
# def get_sitemap_url(self):
# sitemap_url = settings.STATICGEN_SITEMAP_URL
# if sitemap_url is None:
# try:
# # Try for the "global" sitemap URL.
# sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
# except NoReverseMatch:
# message = _('You did not provide a sitemap_url, '
# 'and the sitemap URL could not be auto-detected.')
# self.log_error(message)
#
# return sitemap_url
#
# def get_sitemap_links(self):
# urls = []
# sitemap_url = self.get_sitemap_url()
# if sitemap_url:
# response = self.client.get(sitemap_url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving sitemap: {sitemap_url} - Code: {code}').format(
# sitemap_url=sitemap_url, code=response.status_code)
# self.log_error(message)
# else:
# soup = BeautifulSoup(response.content, 'lxml')
# urls = [loc.get_text() for loc in soup.find_all('loc')]
#
# return urls
#
# @staticmethod
# def get_links(response):
# links = []
#
# if is_redirect(response.status_code):
# links.append(response['Location'])
#
# if is_success(response.status_code):
# soup = BeautifulSoup(response.content, 'lxml')
# for link in soup.find_all('a', href=True):
# links.append(link['href'])
#
# return links
#
# def get_urls(self):
# urls = []
#
# sitemap_links = self.get_sitemap_links()
# for url in sitemap_links:
# parsed_url = urlparse(url)
# self.url_registry.enqueue(parsed_url.path)
#
# for url in self.url_registry:
# urls.append(url)
#
# response = self.client.get(url)
# for link in self.get_links(response):
# cleaned_url = self.clean_url(link)
# if cleaned_url:
# parsed_url = urlparse(cleaned_url)
# self.url_registry.enqueue(parsed_url.path)
#
# urls = list(set(urls))
# urls.sort()
# return urls
. Output only the next line. | self.crawler = StaticgenCrawler() |
Using the snippet: <|code_start|> # Python 2.X
logger = logging.getLogger('staticgen')
class StaticgenPublisher(object):
model = Page
def __init__(self):
self.client = None
self.connection = None
self.bucket = None
self.updated_paths = []
self.deleted_paths = []
def get_client(self):
if self.client is None:
self.client = Client(SERVER_NAME=get_static_site_domain())
return self.client
def get_page(self, path):
client = self.get_client()
extra_kwargs = {
'HTTP_X_STATICGEN_PUBLISHER': True
}
return client.get(path, **extra_kwargs)
def get_connection(self):
if self.connection is None:
self.connection = connect_s3(
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import time
from multiprocessing.pool import ThreadPool
from django.core.files.base import ContentFile
from django.test import Client
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from boto import connect_s3
from .conf import settings
from .helpers import get_static_site_domain
from .models import LogEntry, Page
from .signals import publishing_complete
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context (class names, function names, or code) available:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/signals.py
. Output only the next line. | settings.AWS_ACCESS_KEY_ID, |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError: # pragma: no cover
# Python 2.X
logger = logging.getLogger('staticgen')
class StaticgenPublisher(object):
model = Page
def __init__(self):
self.client = None
self.connection = None
self.bucket = None
self.updated_paths = []
self.deleted_paths = []
def get_client(self):
if self.client is None:
<|code_end|>
using the current file's imports:
import logging
import os
import time
from multiprocessing.pool import ThreadPool
from django.core.files.base import ContentFile
from django.test import Client
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from boto import connect_s3
from .conf import settings
from .helpers import get_static_site_domain
from .models import LogEntry, Page
from .signals import publishing_complete
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and any relevant context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/signals.py
. Output only the next line. | self.client = Client(SERVER_NAME=get_static_site_domain()) |
Predict the next line for this snippet: <|code_start|> queryset = queryset.changed()
elif pending and changed:
queryset = queryset.pending_and_changed()
return queryset
def get_output_path(self, path):
if path.endswith('/'):
path = os.path.join(path, 'index.html')
return path[1:] if path.startswith('/') else path
def log_error(self, page, message):
self.log_action(page, message)
page.publisher_state = self.model.PUBLISHER_STATE_ERROR
page.save()
message = _('Page: {path} - {message}').format(
path=page.path, message=message)
logger.error(message)
def log_success(self, page, message):
self.log_action(page, message)
page.publisher_state = self.model.PUBLISHER_STATE_PUBLISHED
page.save()
message = _('Page: {path} - {message}').format(
path=page.path, message=message)
logger.info(message)
def log_action(self, page, message):
<|code_end|>
with the help of current file imports:
import logging
import os
import time
from multiprocessing.pool import ThreadPool
from django.core.files.base import ContentFile
from django.test import Client
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from boto import connect_s3
from .conf import settings
from .helpers import get_static_site_domain
from .models import LogEntry, Page
from .signals import publishing_complete
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/signals.py
, which may contain function names, class names, or code. Output only the next line. | LogEntry.objects.log_action( |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError: # pragma: no cover
# Python 2.X
logger = logging.getLogger('staticgen')
class StaticgenPublisher(object):
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
import time
from multiprocessing.pool import ThreadPool
from django.core.files.base import ContentFile
from django.test import Client
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from boto import connect_s3
from .conf import settings
from .helpers import get_static_site_domain
from .models import LogEntry, Page
from .signals import publishing_complete
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context (class names, function names, or code) available:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/signals.py
. Output only the next line. | model = Page |
Here is a snippet: <|code_start|> self.deleted_paths.append((page.path, output_path))
if to_delete:
key_chunks = []
for i in range(0, len(to_delete), 100):
key_chunks.append(to_delete[i:i+100])
for chunk in key_chunks:
bucket.delete_keys(chunk)
message = _('Successfully deleted {deleted_count} pages.').format(
deleted_count=len(to_delete))
logger.info(message)
# finally delete records from the database
deleted_pages.delete()
def pre_publish(self, sync_pages=True):
# start timer
self.start_time = time.time()
def post_publish(self):
# delete pages that have been marked for deletion
self.delete_removed()
elapsed_time = time.time() - self.start_time
message = _('Publishing completed successfully. {updated_count} page(s) was updated, '
'deleted {deleted_count} page(s), in {elapsed_time:.2f} seconds.').format(
updated_count=len(self.updated_paths), deleted_count=len(self.deleted_paths),
elapsed_time=elapsed_time)
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import time
from multiprocessing.pool import ThreadPool
from django.core.files.base import ContentFile
from django.test import Client
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from boto import connect_s3
from .conf import settings
from .helpers import get_static_site_domain
from .models import LogEntry, Page
from .signals import publishing_complete
from .status import is_redirect, is_success
from urllib.parse import urlparse
from urlparse import urlparse
and context from other files:
# Path: staticgen/conf.py
# class StaticgenConf(AppConf):
# class Meta:
# SITEMAP_URL = None
# FAIL_SILENTLY = True
# MULTITHREAD = True
# BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', '')
# STATIC_SITE_DOMAIN = None
#
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
#
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/signals.py
, which may include functions, classes, or code. Output only the next line. | publishing_complete.send( |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenLogEntryManager(TestCase):
change_message = 'Something changed'
def setUp(self):
self.page = Page.objects.create(path='/', site_id=settings.SITE_ID)
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.contrib.sites.models import Site
from django.test import TestCase
from staticgen.models import LogEntry, Page
and any relevant context from other files:
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
. Output only the next line. | self.log_entry = LogEntry.objects.log_action(self.change_message, page_id=self.page.id) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenLogEntryManager(TestCase):
change_message = 'Something changed'
def setUp(self):
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.contrib.sites.models import Site
from django.test import TestCase
from staticgen.models import LogEntry, Page
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/models.py
# class LogEntry(models.Model):
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.CASCADE)
# change_message = models.TextField(_('change message'))
# action_time = models.DateTimeField(_('action time'), auto_now=True)
#
# objects = LogEntryManager()
#
# class Meta:
# verbose_name = _('log entry')
# verbose_name_plural = _('log entries')
# ordering = ('-action_time',)
#
# def __str__(self):
# return self.change_message
#
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
. Output only the next line. | self.page = Page.objects.create(path='/', site_id=settings.SITE_ID) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenHelpers(TestCase):
@mock_s3
@override_settings(STATICGEN_STATIC_SITE_DOMAIN=None)
def test_request_with_custom_header(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
<|code_end|>
using the current file's imports:
from django.conf import settings
from django.test import TestCase, override_settings
from boto import connect_s3
from moto import mock_s3
from staticgen.helpers import get_static_site_domain
and any relevant context from other files:
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
. Output only the next line. | static_domain = get_static_site_domain() |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestCeleryTasks(TestCase):
def test_sync_pages(self):
# this should should add 16 pages to database
sync_pages()
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.models import Page
from staticgen.tasks import publish_pages, publish_pending, sync_pages, publish_changed)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
#
# @shared_task
# def publish_pending():
# message = _('Received task to publish all pending pages.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(pending=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pending pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task()
# def sync_pages():
# message = _('Received task to sync all registered pages.')
# log_action(message)
#
# start_time = time.time()
#
# Page.objects.sync()
#
# elapsed_time = time.time() - start_time
# message = _('Synced all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task
# def publish_changed():
# message = _('Received task to publish all pages marked as changed.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(changed=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pages marked as changed successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
. Output only the next line. | self.assertEqual(Page.objects.all().count(), 16) |
Here is a snippet: <|code_start|>
@mock_s3
def test_publish_changed(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
Page.objects.sync() # adds 16 pages to database
# mark 5 pages as changed.
page_ids = Page.objects.values_list('pk', flat=True)[:5]
Page.objects.filter(pk__in=page_ids).update(publisher_state=Page.PUBLISHER_STATE_CHANGED)
# there should be 5 pages - marked as changed
self.assertEqual(Page.objects.changed().count(), 5)
# actual test - this should publish 5 pages marked as changed.
publish_changed()
# there should no more unpublished pages
self.assertEqual(Page.objects.changed().count(), 0)
@mock_s3
def test_publish_pages(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
Page.objects.sync() # adds 16 pages to database
# actual test - this should publish/update all registered pages
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.models import Page
from staticgen.tasks import publish_pages, publish_pending, sync_pages, publish_changed
and context from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
#
# @shared_task
# def publish_pending():
# message = _('Received task to publish all pending pages.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(pending=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pending pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task()
# def sync_pages():
# message = _('Received task to sync all registered pages.')
# log_action(message)
#
# start_time = time.time()
#
# Page.objects.sync()
#
# elapsed_time = time.time() - start_time
# message = _('Synced all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task
# def publish_changed():
# message = _('Received task to publish all pages marked as changed.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(changed=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pages marked as changed successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
, which may include functions, classes, or code. Output only the next line. | publish_pages() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestCeleryTasks(TestCase):
def test_sync_pages(self):
# this should should add 16 pages to database
sync_pages()
self.assertEqual(Page.objects.all().count(), 16)
@mock_s3
def test_publish_pending(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
Page.objects.sync()
# there should be 16 pending publish pages in the database
self.assertEqual(Page.objects.pending().count(), 16)
# actual test - this should publish all 16 pages
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.models import Page
from staticgen.tasks import publish_pages, publish_pending, sync_pages, publish_changed
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
#
# @shared_task
# def publish_pending():
# message = _('Received task to publish all pending pages.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(pending=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pending pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task()
# def sync_pages():
# message = _('Received task to sync all registered pages.')
# log_action(message)
#
# start_time = time.time()
#
# Page.objects.sync()
#
# elapsed_time = time.time() - start_time
# message = _('Synced all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task
# def publish_changed():
# message = _('Received task to publish all pages marked as changed.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(changed=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pages marked as changed successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
. Output only the next line. | publish_pending() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestCeleryTasks(TestCase):
def test_sync_pages(self):
# this should should add 16 pages to database
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.models import Page
from staticgen.tasks import publish_pages, publish_pending, sync_pages, publish_changed
and context (functions, classes, or occasionally code) from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
#
# @shared_task
# def publish_pending():
# message = _('Received task to publish all pending pages.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(pending=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pending pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task()
# def sync_pages():
# message = _('Received task to sync all registered pages.')
# log_action(message)
#
# start_time = time.time()
#
# Page.objects.sync()
#
# elapsed_time = time.time() - start_time
# message = _('Synced all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task
# def publish_changed():
# message = _('Received task to publish all pages marked as changed.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(changed=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pages marked as changed successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
. Output only the next line. | sync_pages() |
Continue the code snippet: <|code_start|> connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
Page.objects.sync()
# there should be 16 pending publish pages in the database
self.assertEqual(Page.objects.pending().count(), 16)
# actual test - this should publish all 16 pages
publish_pending()
# there should no more pending pages.
self.assertEqual(Page.objects.pending().count(), 0)
@mock_s3
def test_publish_changed(self):
# setUp
connection = connect_s3()
connection.create_bucket(settings.AWS_STORAGE_BUCKET_NAME)
Page.objects.sync() # adds 16 pages to database
# mark 5 pages as changed.
page_ids = Page.objects.values_list('pk', flat=True)[:5]
Page.objects.filter(pk__in=page_ids).update(publisher_state=Page.PUBLISHER_STATE_CHANGED)
# there should be 5 pages - marked as changed
self.assertEqual(Page.objects.changed().count(), 5)
# actual test - this should publish 5 pages marked as changed.
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.test import TestCase
from boto import connect_s3
from moto import mock_s3
from staticgen.models import Page
from staticgen.tasks import publish_pages, publish_pending, sync_pages, publish_changed
and context (classes, functions, or code) from other files:
# Path: staticgen/models.py
# class Page(models.Model):
# PUBLISHER_STATE_DEFAULT = 0
# PUBLISHER_STATE_CHANGED = 1
# PUBLISHER_STATE_PUBLISHED = 2
# PUBLISHER_STATE_ERROR = 3
# PUBLISHER_STATE_DELETE = 4
#
# PUBLISHER_STATES = (
# (PUBLISHER_STATE_DEFAULT, _('Pending')),
# (PUBLISHER_STATE_CHANGED, _('Changed')),
# (PUBLISHER_STATE_PUBLISHED, _('Published')),
# (PUBLISHER_STATE_ERROR, _('Error')),
# (PUBLISHER_STATE_DELETE, _('Deleted'))
# )
#
# site = models.ForeignKey(Site, verbose_name=_('Site'))
# path = models.CharField(_('URL'), max_length=255)
# publisher_state = models.SmallIntegerField(
# _('State'), choices=PUBLISHER_STATES, default=PUBLISHER_STATE_DEFAULT,
# editable=False, db_index=True)
# updated_at = models.DateTimeField(auto_now=True)
# objects = PageManager()
#
# class Meta:
# verbose_name = _('page')
# verbose_name_plural = _('pages')
# ordering = ('path', )
# unique_together = ('site', 'path')
#
# def __str__(self):
# return self.path
#
# @property
# def has_changed(self):
# return self.publisher_state == self.PUBLISHER_STATE_CHANGED
#
# Path: staticgen/tasks.py
# @shared_task
# def publish_pages():
# message = _('Received task to publish/update all registered pages.')
# logger.info(force_text(message))
# LogEntry.objects.log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(sync=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published or updated all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# logger.info(message)
#
# @shared_task
# def publish_pending():
# message = _('Received task to publish all pending pages.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(pending=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pending pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task()
# def sync_pages():
# message = _('Received task to sync all registered pages.')
# log_action(message)
#
# start_time = time.time()
#
# Page.objects.sync()
#
# elapsed_time = time.time() - start_time
# message = _('Synced all registered pages successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
#
# @shared_task
# def publish_changed():
# message = _('Received task to publish all pages marked as changed.')
# log_action(message)
#
# start_time = time.time()
#
# publisher = StaticgenPublisher()
# publisher.publish(changed=True)
#
# elapsed_time = time.time() - start_time
# message = _('Published all pages marked as changed successfully, '
# 'in {elapsed_time:.2f} seconds.').format(elapsed_time=elapsed_time)
# log_action(message)
. Output only the next line. | publish_changed() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenViews(TestCase):
def test_base_staticgen_view_items(self):
# base StaticgenView() - this should return empty list.
staticgen_view = StaticgenView()
self.assertEqual(len(staticgen_view.items()), 0)
@patch('staticgen.staticgen_views.logger')
def test_base_staticgen_log_error_logging(self, logger):
staticgen_view = StaticgenView()
message = 'Something bad happened'
staticgen_view.log_error(message)
self.assertTrue(logger.error.called)
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_base_staticgen_log_error_exception(self):
staticgen_view = StaticgenView()
message = 'Something bad happened'
<|code_end|>
using the current file's imports:
from django.test import TestCase, override_settings
from mock import patch
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_views import StaticgenView
from example.staticgen_views import (
ExampleDetailView,
ExampleListView,
ExampleStaticView
)
and any relevant context from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleDetailView(StaticgenView):
#
# def items(self):
# return Post.objects.all()
#
# class ExampleListView(StaticgenView):
# is_paginated = True
#
# def items(self):
# return ('post_list', )
#
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | self.assertRaises(StaticgenError, staticgen_view.log_error, message) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenViews(TestCase):
def test_base_staticgen_view_items(self):
# base StaticgenView() - this should return empty list.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase, override_settings
from mock import patch
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_views import StaticgenView
from example.staticgen_views import (
ExampleDetailView,
ExampleListView,
ExampleStaticView
)
and context:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleDetailView(StaticgenView):
#
# def items(self):
# return Post.objects.all()
#
# class ExampleListView(StaticgenView):
# is_paginated = True
#
# def items(self):
# return ('post_list', )
#
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
which might include code, classes, or functions. Output only the next line. | staticgen_view = StaticgenView() |
Predict the next line after this snippet: <|code_start|> # base StaticgenView() - this should return empty list.
staticgen_view = StaticgenView()
self.assertEqual(len(staticgen_view.items()), 0)
@patch('staticgen.staticgen_views.logger')
def test_base_staticgen_log_error_logging(self, logger):
staticgen_view = StaticgenView()
message = 'Something bad happened'
staticgen_view.log_error(message)
self.assertTrue(logger.error.called)
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_base_staticgen_log_error_exception(self):
staticgen_view = StaticgenView()
message = 'Something bad happened'
self.assertRaises(StaticgenError, staticgen_view.log_error, message)
def test_static_views(self):
# should return 3 urls - homepage/error/redirect/sitemaps page: see example app urls
module = ExampleStaticView()
self.assertEqual(len(module.get_urls()), 4)
def test_list_views(self):
# should return 3 urls for Post ListView
# first page without page number + 2 paginated page
module = ExampleListView()
self.assertEqual(len(module.get_urls()), 3)
def test_detail_views(self):
# should return 9 urls for Post DetailViews
<|code_end|>
using the current file's imports:
from django.test import TestCase, override_settings
from mock import patch
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_views import StaticgenView
from example.staticgen_views import (
ExampleDetailView,
ExampleListView,
ExampleStaticView
)
and any relevant context from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleDetailView(StaticgenView):
#
# def items(self):
# return Post.objects.all()
#
# class ExampleListView(StaticgenView):
# is_paginated = True
#
# def items(self):
# return ('post_list', )
#
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | module = ExampleDetailView() |
Predict the next line after this snippet: <|code_start|>
class TestStaticgenViews(TestCase):
def test_base_staticgen_view_items(self):
# base StaticgenView() - this should return empty list.
staticgen_view = StaticgenView()
self.assertEqual(len(staticgen_view.items()), 0)
@patch('staticgen.staticgen_views.logger')
def test_base_staticgen_log_error_logging(self, logger):
staticgen_view = StaticgenView()
message = 'Something bad happened'
staticgen_view.log_error(message)
self.assertTrue(logger.error.called)
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_base_staticgen_log_error_exception(self):
staticgen_view = StaticgenView()
message = 'Something bad happened'
self.assertRaises(StaticgenError, staticgen_view.log_error, message)
def test_static_views(self):
# should return 3 urls - homepage/error/redirect/sitemaps page: see example app urls
module = ExampleStaticView()
self.assertEqual(len(module.get_urls()), 4)
def test_list_views(self):
# should return 3 urls for Post ListView
# first page without page number + 2 paginated page
<|code_end|>
using the current file's imports:
from django.test import TestCase, override_settings
from mock import patch
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_views import StaticgenView
from example.staticgen_views import (
ExampleDetailView,
ExampleListView,
ExampleStaticView
)
and any relevant context from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleDetailView(StaticgenView):
#
# def items(self):
# return Post.objects.all()
#
# class ExampleListView(StaticgenView):
# is_paginated = True
#
# def items(self):
# return ('post_list', )
#
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | module = ExampleListView() |
Next line prediction: <|code_start|>
from __future__ import unicode_literals
class TestStaticgenViews(TestCase):
def test_base_staticgen_view_items(self):
# base StaticgenView() - this should return empty list.
staticgen_view = StaticgenView()
self.assertEqual(len(staticgen_view.items()), 0)
@patch('staticgen.staticgen_views.logger')
def test_base_staticgen_log_error_logging(self, logger):
staticgen_view = StaticgenView()
message = 'Something bad happened'
staticgen_view.log_error(message)
self.assertTrue(logger.error.called)
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_base_staticgen_log_error_exception(self):
staticgen_view = StaticgenView()
message = 'Something bad happened'
self.assertRaises(StaticgenError, staticgen_view.log_error, message)
def test_static_views(self):
# should return 3 urls - homepage/error/redirect/sitemaps page: see example app urls
<|code_end|>
. Use current file imports:
(from django.test import TestCase, override_settings
from mock import patch
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_views import StaticgenView
from example.staticgen_views import (
ExampleDetailView,
ExampleListView,
ExampleStaticView
))
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_views.py
# class StaticgenView(object):
# is_paginated = False
#
# def __init__(self, *args, **kwargs):
# super(StaticgenView, self).__init__(*args, **kwargs)
# self.client = Client(SERVER_NAME=get_static_site_domain())
#
# def items(self):
# return []
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def url(self, item):
# return resolve_url(item)
#
# def _get_context_data(self, response):
# for key in ('context', 'context_data',):
# context = getattr(response, key, None)
# if context:
# return context
#
# def _get_paginator(self, url):
# response = self.client.get(url)
# if not is_success(response.status_code): # pragma: no cover
# message = _('Error retrieving: {url} - Code: {code}').format(
# url=url, code=response.status_code)
# self.log_error(message)
# else:
# context_data = self._get_context_data(response)
# if context_data:
# try:
# return context_data['paginator'], context_data['is_paginated']
# except KeyError: # pragma: no cover
# pass
# return None, False
#
# def _urls(self, page):
# urls = []
#
# url = self.url(page)
# urls.append(url) # first page
#
# if self.is_paginated:
# paginator, is_paginated = self._get_paginator(url)
# if paginator is not None and is_paginated:
# page_range = paginator.page_range
# match = resolve(url)
# for page_num in page_range:
# kwargs = match.kwargs.copy()
# kwargs.update({
# 'page': page_num
# })
# urls.append(reverse(match.view_name, args=match.args, kwargs=kwargs))
#
# return urls
#
# def get_urls(self):
# urls = []
# for page in self.items():
# if getattr(self, 'i18n', False):
# current_lang_code = translation.get_language()
# for lang_code, lang_name in settings.LANGUAGES:
# translation.activate(lang_code)
# urls += self._urls(page)
# translation.activate(current_lang_code)
# else:
# urls += self._urls(page)
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleDetailView(StaticgenView):
#
# def items(self):
# return Post.objects.all()
#
# class ExampleListView(StaticgenView):
# is_paginated = True
#
# def items(self):
# return ('post_list', )
#
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | module = ExampleStaticView() |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenPool(TestCase):
def setUp(self):
self.staticgen_pool = StaticgenPool()
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_register(self):
self.staticgen_pool.register(ExampleStaticView)
self.assertTrue('example.staticgen_views.ExampleStaticView' in self.staticgen_pool.modules)
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase, override_settings
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_pool import StaticgenPool
from example.staticgen_views import ExampleStaticView
and context (class names, function names, or code) available:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# self._discovered = False
# self.modules = {}
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def register(self, cls):
# from .staticgen_views import StaticgenView
# if not issubclass(cls, StaticgenView):
# message = _('Staticgen Views must inherit '
# '"staticgen.staticgen_views.StaticgenView", '
# '{cls} does not').format(cls=cls)
# self.log_error(message)
# return False # pragma: no cover
#
# name = '{module}.{name}'.format(module=cls.__module__, name=cls.__name__)
# if name in self.modules.keys():
# message = _('"{name}" a Staticgen view with this name '
# 'is already registered'.format(name=name))
# self.log_error(message)
# return False # pragma: no cover
#
# self.modules[name] = cls()
#
# def autodiscover(self):
# if self._discovered: # pragma: no cover
# return
#
# for app in settings.INSTALLED_APPS:
# staticgen_views = app + '.staticgen_views'
# try:
# import_module(staticgen_views)
# except ImportError:
# pass
# self._discovered = True
#
# def get_urls(self):
# urls = []
# for name, module in self.modules.items():
# urls.extend(module.get_urls())
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | self.assertRaises(StaticgenError, self.staticgen_pool.register, ExampleStaticView) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenPool(TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase, override_settings
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_pool import StaticgenPool
from example.staticgen_views import ExampleStaticView
and context (classes, functions, sometimes code) from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# self._discovered = False
# self.modules = {}
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def register(self, cls):
# from .staticgen_views import StaticgenView
# if not issubclass(cls, StaticgenView):
# message = _('Staticgen Views must inherit '
# '"staticgen.staticgen_views.StaticgenView", '
# '{cls} does not').format(cls=cls)
# self.log_error(message)
# return False # pragma: no cover
#
# name = '{module}.{name}'.format(module=cls.__module__, name=cls.__name__)
# if name in self.modules.keys():
# message = _('"{name}" a Staticgen view with this name '
# 'is already registered'.format(name=name))
# self.log_error(message)
# return False # pragma: no cover
#
# self.modules[name] = cls()
#
# def autodiscover(self):
# if self._discovered: # pragma: no cover
# return
#
# for app in settings.INSTALLED_APPS:
# staticgen_views = app + '.staticgen_views'
# try:
# import_module(staticgen_views)
# except ImportError:
# pass
# self._discovered = True
#
# def get_urls(self):
# urls = []
# for name, module in self.modules.items():
# urls.extend(module.get_urls())
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | self.staticgen_pool = StaticgenPool() |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestStaticgenPool(TestCase):
def setUp(self):
self.staticgen_pool = StaticgenPool()
@override_settings(STATICGEN_FAIL_SILENTLY=False)
def test_register(self):
<|code_end|>
. Use current file imports:
(from django.test import TestCase, override_settings
from staticgen.exceptions import StaticgenError
from staticgen.staticgen_pool import StaticgenPool
from example.staticgen_views import ExampleStaticView)
and context including class names, function names, or small code snippets from other files:
# Path: staticgen/exceptions.py
# class StaticgenError(Exception):
# pass
#
# Path: staticgen/staticgen_pool.py
# class StaticgenPool(object):
# def __init__(self):
# self._discovered = False
# self.modules = {}
#
# def log_error(self, message):
# logger.error(message)
# if not settings.STATICGEN_FAIL_SILENTLY:
# raise StaticgenError(message)
#
# def register(self, cls):
# from .staticgen_views import StaticgenView
# if not issubclass(cls, StaticgenView):
# message = _('Staticgen Views must inherit '
# '"staticgen.staticgen_views.StaticgenView", '
# '{cls} does not').format(cls=cls)
# self.log_error(message)
# return False # pragma: no cover
#
# name = '{module}.{name}'.format(module=cls.__module__, name=cls.__name__)
# if name in self.modules.keys():
# message = _('"{name}" a Staticgen view with this name '
# 'is already registered'.format(name=name))
# self.log_error(message)
# return False # pragma: no cover
#
# self.modules[name] = cls()
#
# def autodiscover(self):
# if self._discovered: # pragma: no cover
# return
#
# for app in settings.INSTALLED_APPS:
# staticgen_views = app + '.staticgen_views'
# try:
# import_module(staticgen_views)
# except ImportError:
# pass
# self._discovered = True
#
# def get_urls(self):
# urls = []
# for name, module in self.modules.items():
# urls.extend(module.get_urls())
#
# urls = list(set(urls))
# urls.sort()
# return urls
#
# Path: example/staticgen_views.py
# class ExampleStaticView(StaticgenView):
#
# def items(self):
# return (
# 'homepage',
# 'error_page',
# 'redirect_home',
# 'django.contrib.sitemaps.views.sitemap',
# )
. Output only the next line. | self.staticgen_pool.register(ExampleStaticView) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
def staticgen_publisher(request):
context = {}
is_publishing = request.META.get('HTTP_X_STATICGEN_PUBLISHER', False)
context['STATICGEN_IS_PUBLISHING'] = is_publishing
current_site = Site.objects.get_current()
base_url = current_site.domain
if is_publishing:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.sites.models import Site
from .helpers import get_static_site_domain
and context (classes, functions, sometimes code) from other files:
# Path: staticgen/helpers.py
# def get_static_site_domain():
# static_site_domain = settings.STATICGEN_STATIC_SITE_DOMAIN
# if static_site_domain is None:
# connection = connect_s3(
# settings.AWS_ACCESS_KEY_ID,
# settings.AWS_SECRET_ACCESS_KEY
# )
# bucket = connection.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
# static_site_domain = bucket.get_website_endpoint()
# return static_site_domain.rstrip('/')
. Output only the next line. | base_url = get_static_site_domain() |
Using the snippet: <|code_start|>
def test_get_body_gm():
with pytest.raises(ValueError):
body = get_body_gm('no_name_body')
body_gm = get_body_gm('moon')
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from pygeoid.constants.solar_system_gm import get_body_gm, gm_moon
and context (class names, function names, or code) available:
# Path: pygeoid/constants/solar_system_gm.py
# def get_body_gm(body):
. Output only the next line. | assert gm_moon == body_gm |
Next line prediction: <|code_start|>
def common_precompute(lat, lon, r, r0, lmax):
lat = np.atleast_2d(lat)
lon = np.atleast_2d(lon)
r = np.atleast_2d(r)
degrees = np.arange(lmax + 1)
m = np.atleast_2d(lon[0]).T * degrees
cosin = np.array([np.cos(m), np.sin(m)])
if np.allclose(r[:, 0, None], r):
ri = 1 / r[:, 0]
x = np.sin(lat[:, 0])
else:
ri = 1 / r
x = np.sin(lat)
q = np.asarray(r0 * ri)
if np.any(q > 1.01):
warnings.filterwarnings('once')
warnings.warn("Possible singularity in downward continuation, r << r0")
return lat, lon, degrees, cosin, x, q
def in_coeff_potential(x, q, lmax, degrees):
<|code_end|>
. Use current file imports:
(import warnings
import numpy as np
from joblib import Parallel, delayed
from .legendre import lplm, lplm_d1)
and context including class names, function names, or small code snippets from other files:
# Path: pygeoid/sharm/legendre.py
# def lplm(lmax, x):
# """Associated Legendre functions of the first kind.
#
# Parameters
# ----------
# lmax : int
# Maximum degree and order of the Plm(x).
# x : float
# Input value.
#
# Returns
# -------
# Plm(x) : (lmax + 1, lmax + 1) array
# Values of Plm(x) for all orders and degrees.
# """
# return PlmBar(lmax, x)[_lplm_index(lmax)]
#
# def lplm_d1(lmax, x):
# """Associated Legendre functions of the first kind and their derivatives.
#
# Parameters
# ----------
# lmax : int
# Maximum degree and order.
# x : float
# Input value.
#
# Returns
# -------
# Plm(x) : (lmax + 1, lmax + 1) array
# Values of Plm(x) for all orders and degrees.
# Plm_d(x) : {(lmax + 1, lmax + 1), None} array
# Values of Plm_d(x) for all orders and degrees.
# Will return None if `x` is very close or equal
# to -1 or 1.
# """
# if not (np.allclose(-1, x) or np.allclose(1, x)):
# index = _lplm_index(lmax)
# p, p_d1 = PlmBar_d1(lmax, x)
# return p[index], p_d1[index]
# else:
# p = lplm(lmax, x)
# return p, None
. Output only the next line. | p = lplm(lmax, x) |
Given snippet: <|code_start|>def in_coeff_potential(x, q, lmax, degrees):
p = lplm(lmax, x)
q = np.power(q, degrees)
l_coeff = np.tile(q, (lmax + 1, 1)).T
in_coeff = l_coeff * p
return in_coeff
def sum_potential(in_coeff, cosin, cilm):
cosm_sinm_sum = cilm[0] * cosin[0] + cilm[1] * cosin[1]
pot = np.sum(in_coeff * (cosm_sinm_sum))
return pot
def in_coeff_r_derivative(x, q, lmax, degrees):
p = lplm(lmax, x)
q = np.power(q, degrees)
l_coeff = np.tile(q * (degrees + 1), (lmax + 1, 1)).T
in_coeff = l_coeff * p
return in_coeff
def in_coeff_lat_derivative(x, q, lmax, degrees):
pole = np.allclose(x, -1) | np.allclose(x, 1)
if not pole:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import warnings
import numpy as np
from joblib import Parallel, delayed
from .legendre import lplm, lplm_d1
and context:
# Path: pygeoid/sharm/legendre.py
# def lplm(lmax, x):
# """Associated Legendre functions of the first kind.
#
# Parameters
# ----------
# lmax : int
# Maximum degree and order of the Plm(x).
# x : float
# Input value.
#
# Returns
# -------
# Plm(x) : (lmax + 1, lmax + 1) array
# Values of Plm(x) for all orders and degrees.
# """
# return PlmBar(lmax, x)[_lplm_index(lmax)]
#
# def lplm_d1(lmax, x):
# """Associated Legendre functions of the first kind and their derivatives.
#
# Parameters
# ----------
# lmax : int
# Maximum degree and order.
# x : float
# Input value.
#
# Returns
# -------
# Plm(x) : (lmax + 1, lmax + 1) array
# Values of Plm(x) for all orders and degrees.
# Plm_d(x) : {(lmax + 1, lmax + 1), None} array
# Values of Plm_d(x) for all orders and degrees.
# Will return None if `x` is very close or equal
# to -1 or 1.
# """
# if not (np.allclose(-1, x) or np.allclose(1, x)):
# index = _lplm_index(lmax)
# p, p_d1 = PlmBar_d1(lmax, x)
# return p[index], p_d1[index]
# else:
# p = lplm(lmax, x)
# return p, None
which might include code, classes, or functions. Output only the next line. | _, p_d1 = lplm_d1(lmax, x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.